
- Set up project structure with FastAPI and SQLite - Implement user authentication with JWT - Create models for learning content (subjects, lessons, quizzes) - Add progress tracking and gamification features - Implement comprehensive API documentation - Add error handling and validation - Set up proper logging and health check endpoint
94 lines
2.6 KiB
Python
94 lines
2.6 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import List
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.content import Answer, Question
|
|
from app.schemas.content import QuestionCreate, QuestionUpdate
|
|
from app.utils.db import CRUDBase
|
|
|
|
|
|
class CRUDQuestion(CRUDBase[Question, QuestionCreate, QuestionUpdate]):
|
|
def get_by_quiz(
|
|
self, db: Session, *, quiz_id: int, skip: int = 0, limit: int = 100
|
|
) -> List[Question]:
|
|
"""
|
|
Get questions by quiz.
|
|
"""
|
|
return (
|
|
db.query(Question)
|
|
.filter(Question.quiz_id == quiz_id)
|
|
.order_by(Question.order)
|
|
.offset(skip)
|
|
.limit(limit)
|
|
.all()
|
|
)
|
|
|
|
def get_active_by_quiz(
|
|
self, db: Session, *, quiz_id: int, skip: int = 0, limit: int = 100
|
|
) -> List[Question]:
|
|
"""
|
|
Get active questions by quiz.
|
|
"""
|
|
return (
|
|
db.query(Question)
|
|
.filter(Question.quiz_id == quiz_id, Question.is_active == True)
|
|
.order_by(Question.order)
|
|
.offset(skip)
|
|
.limit(limit)
|
|
.all()
|
|
)
|
|
|
|
def create_with_answers(self, db: Session, *, obj_in: QuestionCreate) -> Question:
|
|
"""
|
|
Create a question with answers.
|
|
"""
|
|
# Extract answers from input
|
|
answers_data = obj_in.answers
|
|
question_data = obj_in.model_dump(exclude={"answers"})
|
|
|
|
# Create question
|
|
db_obj = Question(**question_data)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
|
|
# Create answers
|
|
for answer_data in answers_data:
|
|
answer = Answer(question_id=db_obj.id, **answer_data.model_dump())
|
|
db.add(answer)
|
|
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
def update_with_answers(
|
|
self, db: Session, *, db_obj: Question, obj_in: QuestionUpdate
|
|
) -> Question:
|
|
"""
|
|
Update a question with answers.
|
|
"""
|
|
# Update question
|
|
question_data = obj_in.model_dump(exclude={"answers"}, exclude_unset=True)
|
|
for field, value in question_data.items():
|
|
setattr(db_obj, field, value)
|
|
|
|
# Update answers if provided
|
|
if obj_in.answers:
|
|
# Delete existing answers
|
|
db.query(Answer).filter(Answer.question_id == db_obj.id).delete()
|
|
|
|
# Create new answers
|
|
for answer_data in obj_in.answers:
|
|
answer = Answer(question_id=db_obj.id, **answer_data.model_dump())
|
|
db.add(answer)
|
|
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
question = CRUDQuestion(Question)
|