feat: Generated endpoint endpoints/todo.post.py via AI for Todo with auto lint fixes

This commit is contained in:
Backend IM Bot 2025-04-15 21:05:48 +00:00
parent 064fe39249
commit a97483a990
5 changed files with 204 additions and 0 deletions

View File

@ -0,0 +1,33 @@
"""create table for todos
Revision ID: 2d4e3a8b7f2c
Revises: 0001
Create Date: 2023-05-25 11:18:19.991565
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import func
import uuid
# revision identifiers, used by Alembic.
revision = '2d4e3a8b7f2c'
down_revision = '0001'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'todos',
sa.Column('id', sa.String(36), primary_key=True, default=lambda: str(uuid.uuid4())),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('is_completed', sa.String(), default='False'),
sa.Column('created_at', sa.DateTime(), server_default=func.now()),
sa.Column('updated_at', sa.DateTime(), server_default=func.now(), onupdate=func.now())
)
def downgrade():
op.drop_table('todos')

View File

@ -0,0 +1,37 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from core.database import get_db
from schemas.todo import TodoSchema, TodoCreate, TodoUpdate
from helpers.todo_helpers import create_todo, update_todo, delete_todo
import uuid
router = APIRouter()
@router.post("/todo", status_code=status.HTTP_201_CREATED, response_model=TodoSchema)
async def create_new_todo(
todo_data: TodoCreate,
db: Session = Depends(get_db)
):
new_todo = create_todo(db=db, todo_data=todo_data)
return new_todo
@router.post("/todo/{todo_id}", status_code=status.HTTP_200_OK, response_model=TodoSchema)
async def update_existing_todo(
todo_id: uuid.UUID,
todo_data: TodoUpdate,
db: Session = Depends(get_db)
):
updated_todo = update_todo(db=db, todo_id=todo_id, todo_data=todo_data)
if not updated_todo:
raise HTTPException(status_code=404, detail="Todo not found")
return updated_todo
@router.delete("/todo/{todo_id}", status_code=status.HTTP_200_OK)
async def delete_existing_todo(
todo_id: uuid.UUID,
db: Session = Depends(get_db)
):
deleted = delete_todo(db=db, todo_id=todo_id)
if not deleted:
raise HTTPException(status_code=404, detail="Todo not found")
return {"message": "Todo deleted successfully"}

90
helpers/todo_helpers.py Normal file
View File

@ -0,0 +1,90 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from models.todo import Todo
from schemas.todo import TodoCreate, TodoUpdate
import uuid
def create_todo(db: Session, todo_data: TodoCreate) -> Todo:
"""
Creates a new todo in the database.
Args:
db (Session): The database session.
todo_data (TodoCreate): The data for the todo to create.
Returns:
Todo: The newly created todo object.
"""
db_todo = Todo(**todo_data.dict())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
def get_all_todos(db: Session) -> List[Todo]:
"""
Retrieves all todos from the database.
Args:
db (Session): The database session.
Returns:
List[Todo]: A list of all todo objects.
"""
return db.query(Todo).all()
def get_todo_by_id(db: Session, todo_id: uuid.UUID) -> Optional[Todo]:
"""
Retrieves a single todo by its ID.
Args:
db (Session): The database session.
todo_id (UUID): The ID of the todo to retrieve.
Returns:
Optional[Todo]: The todo object if found, otherwise None.
"""
return db.query(Todo).filter(Todo.id == todo_id).first()
def update_todo(db: Session, todo_id: uuid.UUID, todo_data: TodoUpdate) -> Optional[Todo]:
"""
Updates an existing todo in the database.
Args:
db (Session): The database session.
todo_id (UUID): The ID of the todo to update.
todo_data (TodoUpdate): The updated data for the todo.
Returns:
Optional[Todo]: The updated todo object if found, otherwise None.
"""
existing_todo = get_todo_by_id(db, todo_id)
if not existing_todo:
return None
todo_data_dict = todo_data.dict(exclude_unset=True)
for key, value in todo_data_dict.items():
setattr(existing_todo, key, value)
db.commit()
db.refresh(existing_todo)
return existing_todo
def delete_todo(db: Session, todo_id: uuid.UUID) -> bool:
"""
Deletes a todo from the database.
Args:
db (Session): The database session.
todo_id (UUID): The ID of the todo to delete.
Returns:
bool: True if the todo was deleted, False otherwise.
"""
existing_todo = get_todo_by_id(db, todo_id)
if not existing_todo:
return False
db.delete(existing_todo)
db.commit()
return True

15
models/todo.py Normal file
View File

@ -0,0 +1,15 @@
from sqlalchemy import Column, String, DateTime
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from core.database import Base
import uuid
class Todo(Base):
__tablename__ = "todos"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
title = Column(String, nullable=False)
description = Column(String, nullable=True)
is_completed = Column(String, default=False)
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

29
schemas/todo.py Normal file
View File

@ -0,0 +1,29 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
import uuid
# Base schema for Todo, used for inheritance
class TodoBase(BaseModel):
title: str = Field(..., description="Title of the todo")
description: Optional[str] = Field(None, description="Description of the todo")
is_completed: bool = Field(False, description="Whether the todo is completed or not")
# Schema for creating a new Todo
class TodoCreate(TodoBase):
pass
# Schema for updating an existing Todo
class TodoUpdate(TodoBase):
title: Optional[str] = Field(None, description="Title of the todo")
description: Optional[str] = Field(None, description="Description of the todo")
is_completed: Optional[bool] = Field(None, description="Whether the todo is completed or not")
# Schema for representing a Todo in responses
class TodoSchema(TodoBase):
id: uuid.UUID
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True