
- 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
45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
|
|
from app.models.category import Category
|
|
from app.schemas.category import CategoryCreate
|
|
|
|
|
|
def create_category(db: Session, category_data: CategoryCreate) -> Category:
|
|
"""Create a new category."""
|
|
db_category = Category(**category_data.model_dump())
|
|
db.add(db_category)
|
|
db.commit()
|
|
db.refresh(db_category)
|
|
return db_category
|
|
|
|
|
|
def get_category(db: Session, category_id: int) -> Optional[Category]:
|
|
"""Get a category by ID."""
|
|
return db.query(Category).filter(Category.id == category_id).first()
|
|
|
|
|
|
def get_categories(db: Session, skip: int = 0, limit: int = 100) -> List[Category]:
|
|
"""Get all categories with pagination."""
|
|
return db.query(Category).offset(skip).limit(limit).all()
|
|
|
|
|
|
def update_category(db: Session, category_id: int, category_data: CategoryCreate) -> Optional[Category]:
|
|
"""Update an existing category."""
|
|
db_category = get_category(db, category_id)
|
|
if db_category:
|
|
for key, value in category_data.model_dump().items():
|
|
setattr(db_category, key, value)
|
|
db.commit()
|
|
db.refresh(db_category)
|
|
return db_category
|
|
|
|
|
|
def delete_category(db: Session, category_id: int) -> bool:
|
|
"""Delete a category."""
|
|
db_category = get_category(db, category_id)
|
|
if db_category:
|
|
db.delete(db_category)
|
|
db.commit()
|
|
return True
|
|
return False |