You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5 KiB

from random import randint, random
from fastapi import FastAPI, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import sqlalchemy
from sqlalchemy import text
import pandas as pd
from pydantic import BaseModel
from starlette.staticfiles import StaticFiles
app = FastAPI()
origins = ["http://localhost:5173", "http://localhost:8000"]
# noinspection PyTypeChecker
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
engine = sqlalchemy.create_engine("mariadb+mariadbconnector://root:1212@127.0.0.1:3306/ROLLER_DB")
@app.get("/api/get/get_random_stu")
async def get_random_stu():
with engine.connect() as c:
stu = c.execute(text("SELECT sno, sname, score FROM stu_info;")).fetchall()
avg = (c.execute(text(f"SELECT AVG(score) FROM stu_info;")).fetchall())[0][0]
size = stu.__len__()
while 1:
no = randint(0, size - 1)
diff = stu[no][2] - avg
if diff > 7:
chance = 0.2
elif diff > 3:
chance = 0.7 - (diff-3) / 4 * 0.5
elif diff > 1:
chance = 0.9 - (diff-1) / 2 * 0.2
else:
chance = 1
if random() < chance:
break
return {"sno": stu[no][0], "sname": stu[no][1]}
@app.get("/api/get/get_random_event")
async def get_event():
with engine.connect() as c:
res = c.execute(text("SELECT event_id, event_description FROM events")).fetchall()
if randint(0, 100) < 15:
event_id = randint(1, 2)
else:
event_id = 0
return {"event_id": res[event_id][0], "event_description": res[event_id][1]}
@app.post("/api/post/upload_stu_info")
async def upload_stu_info(file: UploadFile):
upload_file = file.file
data = pd.read_csv(upload_file)
with engine.connect() as c:
c.execute(text("TRUNCATE TABLE stu_info"))
for i in data.index.values:
with engine.begin() as c:
c.execute(text(f"INSERT INTO stu_info VALUES ('{data.values[i, 0]}', '{data.values[i,1]}', 0, 0);"))
return file.filename
class ChangedScore(BaseModel):
sno: str
variation: float
@app.post("/api/post/update_score")
async def update_score(changed_score: ChangedScore):
with engine.begin() as c:
c.execute(text(f"UPDATE stu_info SET score = score + {changed_score.variation} WHERE sno = '{changed_score.sno}'"))
return changed_score
app.mount("/", StaticFiles(directory="dist", html=True), name="dist")