
- Add priority field to Todo model - Update Pydantic schemas with priority field - Create Alembic migration for priority column - Add filter by priority to GET /todos endpoint - Update README with new feature details generated with BackendIM... (backend.im)
66 lines
2.1 KiB
Python
66 lines
2.1 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
|
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
|
|
from app.db.database import get_db
|
|
from app.models.todo import Todo as TodoModel
|
|
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
|
|
|
|
router = APIRouter(
|
|
prefix="/todos",
|
|
tags=["todos"]
|
|
)
|
|
|
|
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
|
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
|
db_todo = TodoModel(**todo.dict())
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@router.get("/", response_model=List[Todo])
|
|
def read_todos(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
priority: Optional[int] = Query(None, ge=1, le=3, description="Filter by priority (1=Low, 2=Medium, 3=High)"),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
query = db.query(TodoModel)
|
|
|
|
if priority is not None:
|
|
query = query.filter(TodoModel.priority == priority)
|
|
|
|
todos = query.offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
@router.get("/{todo_id}", response_model=Todo)
|
|
def read_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
@router.put("/{todo_id}", response_model=Todo)
|
|
def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
|
|
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
|
|
update_data = todo.dict(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(db_todo, key, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return None |