
- Implement Todo database model with SQLAlchemy - Set up Alembic for database migrations - Create CRUD operations for Todo items - Implement RESTful API endpoints - Add health check endpoint - Include comprehensive README with usage instructions
97 lines
2.3 KiB
Python
97 lines
2.3 KiB
Python
from typing import List, Optional
|
|
from sqlalchemy.orm import Session
|
|
from app.models.todo import Todo
|
|
from app.schemas.todo import TodoCreate, TodoUpdate
|
|
|
|
|
|
def get_todo(db: Session, todo_id: int) -> Optional[Todo]:
|
|
"""
|
|
Get a single todo item by ID.
|
|
|
|
Args:
|
|
db: Database session
|
|
todo_id: ID of the todo to retrieve
|
|
|
|
Returns:
|
|
Todo object if found, None otherwise
|
|
"""
|
|
return db.query(Todo).filter(Todo.id == todo_id).first()
|
|
|
|
|
|
def get_todos(db: Session, skip: int = 0, limit: int = 100) -> List[Todo]:
|
|
"""
|
|
Get multiple todo items with pagination.
|
|
|
|
Args:
|
|
db: Database session
|
|
skip: Number of records to skip
|
|
limit: Maximum number of records to return
|
|
|
|
Returns:
|
|
List of Todo objects
|
|
"""
|
|
return db.query(Todo).order_by(Todo.created_at.desc()).offset(skip).limit(limit).all()
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate) -> Todo:
|
|
"""
|
|
Create a new todo item.
|
|
|
|
Args:
|
|
db: Database session
|
|
todo: TodoCreate schema with new todo data
|
|
|
|
Returns:
|
|
Created Todo object
|
|
"""
|
|
db_todo = Todo(**todo.model_dump())
|
|
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]:
|
|
"""
|
|
Update an existing todo item.
|
|
|
|
Args:
|
|
db: Database session
|
|
todo_id: ID of the todo to update
|
|
todo: TodoUpdate schema with fields to update
|
|
|
|
Returns:
|
|
Updated Todo object if found, None otherwise
|
|
"""
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo is None:
|
|
return None
|
|
|
|
# Update only provided fields
|
|
todo_data = todo.model_dump(exclude_unset=True)
|
|
for key, value in todo_data.items():
|
|
setattr(db_todo, key, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def delete_todo(db: Session, todo_id: int) -> bool:
|
|
"""
|
|
Delete a todo item.
|
|
|
|
Args:
|
|
db: Database session
|
|
todo_id: ID of the todo to delete
|
|
|
|
Returns:
|
|
True if deleted, False if not found
|
|
"""
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo is None:
|
|
return False
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True |