
- Setup project structure with FastAPI app - Create SQLAlchemy models for categories, questions, quizzes, and results - Implement API endpoints for all CRUD operations - Set up Alembic migrations for database schema management - Add comprehensive documentation in README.md
60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
|
|
from app.models.question import Question
|
|
from app.schemas.question import QuestionCreate, QuestionUpdate
|
|
|
|
|
|
def create_question(db: Session, question_data: QuestionCreate) -> Question:
|
|
"""Create a new question."""
|
|
db_question = Question(**question_data.model_dump())
|
|
db.add(db_question)
|
|
db.commit()
|
|
db.refresh(db_question)
|
|
return db_question
|
|
|
|
|
|
def get_question(db: Session, question_id: int) -> Optional[Question]:
|
|
"""Get a question by ID."""
|
|
return db.query(Question).filter(Question.id == question_id).first()
|
|
|
|
|
|
def get_questions(
|
|
db: Session,
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
category_id: Optional[int] = None,
|
|
difficulty: Optional[str] = None
|
|
) -> List[Question]:
|
|
"""Get all questions with optional filtering and pagination."""
|
|
query = db.query(Question)
|
|
|
|
if category_id:
|
|
query = query.filter(Question.category_id == category_id)
|
|
|
|
if difficulty:
|
|
query = query.filter(Question.difficulty == difficulty)
|
|
|
|
return query.offset(skip).limit(limit).all()
|
|
|
|
|
|
def update_question(db: Session, question_id: int, question_data: QuestionUpdate) -> Optional[Question]:
|
|
"""Update an existing question."""
|
|
db_question = get_question(db, question_id)
|
|
if db_question:
|
|
update_data = question_data.model_dump(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(db_question, key, value)
|
|
db.commit()
|
|
db.refresh(db_question)
|
|
return db_question
|
|
|
|
|
|
def delete_question(db: Session, question_id: int) -> bool:
|
|
"""Delete a question."""
|
|
db_question = get_question(db, question_id)
|
|
if db_question:
|
|
db.delete(db_question)
|
|
db.commit()
|
|
return True
|
|
return False |