
- Create Todo model and schemas - Set up API endpoints for CRUD operations - Configure SQLAlchemy for database access - Set up Alembic for database migrations - Add Ruff for code linting - Update README with project documentation
84 lines
1.7 KiB
Python
84 lines
1.7 KiB
Python
"""
|
|
CRUD operations for Todo model.
|
|
"""
|
|
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 Todo by ID.
|
|
"""
|
|
return db.query(Todo).filter(Todo.id == todo_id).first()
|
|
|
|
|
|
def get_todos(
|
|
db: Session,
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
completed: Optional[bool] = None
|
|
) -> List[Todo]:
|
|
"""
|
|
Get all Todos with optional filtering.
|
|
"""
|
|
query = db.query(Todo)
|
|
|
|
if completed is not None:
|
|
query = query.filter(Todo.completed == completed)
|
|
|
|
return query.offset(skip).limit(limit).all()
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate) -> Todo:
|
|
"""
|
|
Create a new 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_update: TodoUpdate
|
|
) -> Optional[Todo]:
|
|
"""
|
|
Update a Todo.
|
|
"""
|
|
db_todo = get_todo(db, todo_id)
|
|
if not db_todo:
|
|
return None
|
|
|
|
update_data = todo_update.dict(exclude_unset=True)
|
|
|
|
for field, value in update_data.items():
|
|
setattr(db_todo, field, value)
|
|
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def delete_todo(db: Session, todo_id: int) -> bool:
|
|
"""
|
|
Delete a Todo.
|
|
"""
|
|
db_todo = get_todo(db, todo_id)
|
|
if not db_todo:
|
|
return False
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True |