
- Set up FastAPI project structure with proper organization - Create Todo model with SQLAlchemy ORM - Set up Alembic for database migrations - Create CRUD operations and API endpoints for todos - Add health check endpoint - Update README with comprehensive documentation generated with BackendIM... (backend.im)
49 lines
1.2 KiB
Python
49 lines
1.2 KiB
Python
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
|
|
from app.models.todo import Todo
|
|
from app.schemas.todo import TodoCreate, TodoUpdate
|
|
|
|
|
|
def get_todo(db: Session, todo_id: int) -> Optional[Todo]:
|
|
return db.query(Todo).filter(Todo.id == todo_id).first()
|
|
|
|
|
|
def get_todos(db: Session, skip: int = 0, limit: int = 100) -> List[Todo]:
|
|
return db.query(Todo).order_by(Todo.created_at.desc()).offset(skip).limit(limit).all()
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate) -> Todo:
|
|
db_todo = Todo(
|
|
title=todo.title,
|
|
description=todo.description,
|
|
completed=todo.completed
|
|
)
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def update_todo(db: Session, todo_id: int, todo: TodoUpdate) -> Optional[Todo]:
|
|
db_todo = get_todo(db, todo_id)
|
|
if db_todo is None:
|
|
return None
|
|
|
|
update_data = todo.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_todo, field, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def delete_todo(db: Session, todo_id: int) -> bool:
|
|
db_todo = get_todo(db, todo_id)
|
|
if db_todo is None:
|
|
return False
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True |