File size: 1,610 Bytes
633c3f1
 
 
b582880
633c3f1
b582880
633c3f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b582880
 
 
 
 
 
 
 
 
 
 
 
 
 
633c3f1
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import uvicorn
from contextlib import asynccontextmanager
import sqlite3
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("startup event")
    yield
    print("shutdown event")

app = FastAPI(lifespan=lifespan)

DATABASE = 'workbook.db'

def get_db():
    db = getattr(app.state, '_database', None)
    if db is None:
        db = app.state._database = sqlite3.connect(DATABASE)
    return db

@app.get('/api/chapters')
def get_chapters():
    db = get_db()
    cursor = db.cursor()
    cursor.execute("SELECT chapter, chapter_name FROM chapter")
    chapters = cursor.fetchall()
    chapter_list = [{"chapter_number": row[0], "chapter_name": row[1]} for row in chapters]
    return JSONResponse(content=chapter_list)

class ChapterRequest(BaseModel):
    chapter_number: int

@app.post('/api/chapter/questions')
def get_questions_by_chapter(request: ChapterRequest):
    db = get_db()
    cursor = db.cursor()
    cursor.execute("SELECT question_id, question_text FROM questions WHERE chapter_number = ?", (request.chapter_number,))
    questions = cursor.fetchall()
    if not questions:
        raise HTTPException(status_code=404, detail="Questions not found for the given chapter number")
    question_list = [{"question_id": row[0], "question_text": row[1]} for row in questions]
    return JSONResponse(content=question_list)

if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="debug")