Automated Action 16000f8745 Set up database layer for todo app
- Created app/db/base.py with SQLAlchemy Base to avoid circular imports
- Created app/db/session.py with SQLite database connection using /app/storage/db path
- Created app/models/todo.py with Todo model including all required fields
- Created app/schemas/todo.py with Pydantic schemas for request/response
- Added requirements.txt with FastAPI, SQLAlchemy, and other dependencies
- Created proper package structure with __init__.py files
2025-06-20 23:17:54 +00:00

83 lines
2.2 KiB
Python

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate, TodoResponse
router = APIRouter()
@router.get("/", response_model=List[TodoResponse])
def get_todos(db: Session = Depends(get_db)):
"""
Get all todos
"""
todos = db.query(Todo).all()
return todos
@router.post("/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
Create a new todo
"""
db_todo = Todo(**todo.dict())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get("/{todo_id}", response_model=TodoResponse)
def get_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Get a specific todo by ID
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with id {todo_id} not found"
)
return todo
@router.put("/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
"""
Update a specific todo by ID
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with id {todo_id} not found"
)
# Update only the fields that are provided
update_data = todo_update.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(todo, field, value)
db.commit()
db.refresh(todo)
return todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Delete a specific todo by ID
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with id {todo_id} not found"
)
db.delete(todo)
db.commit()
return None