feat: Generated endpoint endpoints/names.post.py via AI for Fruit

This commit is contained in:
Backend IM Bot 2025-04-11 20:26:34 +00:00
parent fc8eacdef3
commit 244bfcaed1
5 changed files with 211 additions and 0 deletions

View File

@ -0,0 +1,29 @@
"""create fruits table
Revision ID: 2a8c4f9e3b1d
Revises: 0001
Create Date: 2024-01-18 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
import uuid
# revision identifiers, used by Alembic.
revision = '2a8c4f9e3b1d'
down_revision = '0001'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'fruits',
sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True, default=uuid.uuid4),
sa.Column('name', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now(), onupdate=sa.func.now())
)
op.create_index('ix_fruits_name', 'fruits', ['name'], unique=True)
def downgrade():
op.drop_index('ix_fruits_name')
op.drop_table('fruits')

View File

@ -0,0 +1,13 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from typing import List
from core.database import get_db
from helpers.fruit_helpers import get_all_fruit_names
router = APIRouter()
@router.post("/names", status_code=200, response_model=List[str])
async def get_fruit_names(db: Session = Depends(get_db)):
"""Get all fruit names"""
names = get_all_fruit_names(db)
return names

127
helpers/fruit_helpers.py Normal file
View File

@ -0,0 +1,127 @@
from typing import List, Optional
from uuid import UUID
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from datetime import datetime
from models.fruit import Fruit
from schemas.fruit import FruitCreate, FruitUpdate
def get_all_fruits(db: Session) -> List[Fruit]:
"""
Retrieves all fruits from the database.
Args:
db (Session): The database session.
Returns:
List[Fruit]: A list of all fruit objects.
"""
return db.query(Fruit).all()
def get_fruit_by_id(db: Session, fruit_id: UUID) -> Optional[Fruit]:
"""
Retrieves a single fruit by its ID.
Args:
db (Session): The database session.
fruit_id (UUID): The ID of the fruit to retrieve.
Returns:
Optional[Fruit]: The fruit object if found, otherwise None.
"""
return db.query(Fruit).filter(Fruit.id == fruit_id).first()
def get_fruit_by_name(db: Session, name: str) -> Optional[Fruit]:
"""
Retrieves a single fruit by its name.
Args:
db (Session): The database session.
name (str): The name of the fruit to retrieve.
Returns:
Optional[Fruit]: The fruit object if found, otherwise None.
"""
return db.query(Fruit).filter(Fruit.name == name).first()
def get_all_fruit_names(db: Session) -> List[str]:
"""
Retrieves a list of all fruit names.
Args:
db (Session): The database session.
Returns:
List[str]: A list of fruit names.
"""
fruits = db.query(Fruit.name).all()
return [fruit[0] for fruit in fruits]
def create_fruit(db: Session, fruit_data: FruitCreate) -> Optional[Fruit]:
"""
Creates a new fruit in the database.
Args:
db (Session): The database session.
fruit_data (FruitCreate): The data for the fruit to create.
Returns:
Optional[Fruit]: The newly created fruit object, or None if creation fails.
"""
try:
db_fruit = Fruit(**fruit_data.dict())
db.add(db_fruit)
db.commit()
db.refresh(db_fruit)
return db_fruit
except IntegrityError:
db.rollback()
return None
def update_fruit(db: Session, fruit_id: UUID, fruit_data: FruitUpdate) -> Optional[Fruit]:
"""
Updates an existing fruit in the database.
Args:
db (Session): The database session.
fruit_id (UUID): The ID of the fruit to update.
fruit_data (FruitUpdate): The update data for the fruit.
Returns:
Optional[Fruit]: The updated fruit object if found and updated, otherwise None.
"""
db_fruit = get_fruit_by_id(db, fruit_id)
if not db_fruit:
return None
try:
update_data = fruit_data.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_fruit, key, value)
db_fruit.updated_at = datetime.utcnow()
db.commit()
db.refresh(db_fruit)
return db_fruit
except IntegrityError:
db.rollback()
return None
def delete_fruit(db: Session, fruit_id: UUID) -> bool:
"""
Deletes a fruit from the database.
Args:
db (Session): The database session.
fruit_id (UUID): The ID of the fruit to delete.
Returns:
bool: True if the fruit was deleted, False if not found.
"""
db_fruit = get_fruit_by_id(db, fruit_id)
if not db_fruit:
return False
db.delete(db_fruit)
db.commit()
return True

13
models/fruit.py Normal file
View File

@ -0,0 +1,13 @@
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 Fruit(Base):
__tablename__ = "fruits"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String, unique=True, nullable=False, index=True)
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

29
schemas/fruit.py Normal file
View File

@ -0,0 +1,29 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
from uuid import UUID
class FruitBase(BaseModel):
name: str = Field(..., min_length=1, description="Fruit name")
class FruitCreate(FruitBase):
pass
class FruitUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, description="Fruit name")
class FruitSchema(FruitBase):
id: UUID
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
schema_extra = {
"example": {
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"name": "Apple",
"created_at": "2023-01-01T12:00:00",
"updated_at": "2023-01-01T12:00:00"
}
}