| |
|
|
| from fastapi import FastAPI, HTTPException, status |
| from datetime import datetime |
| import threading |
|
|
| from models import QuizRequest |
| from config import STUDENT_SECRET |
| from solver import QuizSolver |
|
|
| app = FastAPI(title="Quiz Solver API") |
| request_times = {} |
|
|
| def start_quiz_solving_task(payload: QuizRequest, start_time: datetime): |
| """Function to run the blocking quiz solver in a thread.""" |
| try: |
| solver = QuizSolver(payload, start_time) |
| result = solver.run_quiz_loop() |
| print(f"Quiz finished for {payload.url} with result: {result}") |
| except Exception as e: |
| print(f"Quiz solving task failed: {e}") |
| finally: |
| if payload.url in request_times: |
| del request_times[payload.url] |
|
|
| @app.post("/solve-quiz") |
| async def handle_quiz_request( |
| payload: QuizRequest |
| ): |
| """ |
| Receives the quiz request, validates the secret, and starts the solver. |
| """ |
| |
| if payload.secret != STUDENT_SECRET: |
| raise HTTPException( |
| status_code=status.HTTP_403_FORBIDDEN, |
| detail="Invalid secret provided." |
| ) |
|
|
| start_time = datetime.now() |
| if payload.url in request_times: |
| return {"message": "Quiz already in progress. Ignoring duplicate request."} |
| |
| request_times[payload.url] = start_time |
| |
| |
| thread = threading.Thread( |
| target=start_quiz_solving_task, |
| args=(payload, start_time) |
| ) |
| thread.start() |
| |
| |
| return { |
| "message": "Quiz solving process started.", |
| "url": payload.url, |
| "email": payload.email |
| } |
|
|
|
|
|
|
| @app.get("/download-log") |
| def download_log(): |
| return FileResponse("app.log", filename="app.log") |