
- Add project structure with FastAPI, SQLAlchemy, and Alembic - Implement Todo model with CRUD operations - Add REST API endpoints for todo management - Configure SQLite database with migrations - Include health check and API documentation endpoints - Add CORS middleware for all origins - Format code with Ruff
42 lines
1.2 KiB
Python
42 lines
1.2 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]:
|
|
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).offset(skip).limit(limit).all()
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate) -> Todo:
|
|
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_update: TodoUpdate) -> Optional[Todo]:
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo:
|
|
update_data = todo_update.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 = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo:
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True
|
|
return False
|