feat: Generated endpoint endpoints/create-fruits.post.py via AI for Fruit with auto lint fixes

This commit is contained in:
Backend IM Bot 2025-04-15 13:46:31 +00:00
parent 3a2e6ed40f
commit 9f0ba74e1b
5 changed files with 202 additions and 0 deletions

View File

@ -0,0 +1,33 @@
"""create table for fruits
Revision ID: 1a2b3c4d5e6f
Revises: 0001
Create Date: 2023-05-24 12:00:00
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import func
# revision identifiers, used by Alembic.
revision = '1a2b3c4d5e6f'
down_revision = '0001'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'fruits',
sa.Column('id', sa.String(36), primary_key=True, default=func.uuid_func()),
sa.Column('name', sa.String(), nullable=False, unique=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('price', sa.Integer(), nullable=False),
sa.Column('quantity', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), server_default=func.now()),
sa.Column('updated_at', sa.DateTime(), server_default=func.now(), onupdate=func.now())
)
op.create_index(op.f('ix_fruits_name'), 'fruits', ['name'], unique=True)
def downgrade():
op.drop_index(op.f('ix_fruits_name'), table_name='fruits')
op.drop_table('fruits')

View File

@ -0,0 +1,16 @@
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from core.database import get_db
from schemas.fruit import FruitSchema, FruitCreate
from helpers.fruit_helpers import create_fruit
router = APIRouter()
@router.post("/create-fruits", status_code=status.HTTP_201_CREATED, response_model=FruitSchema)
async def create_new_fruit(
fruit: FruitCreate,
db: Session = Depends(get_db)
):
"""Create a new fruit"""
new_fruit = create_fruit(db=db, fruit_data=fruit)
return new_fruit

110
helpers/fruit_helpers.py Normal file
View File

@ -0,0 +1,110 @@
from typing import List, Optional
import uuid
from sqlalchemy.orm import Session
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.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 create_fruit(db: Session, fruit_data: FruitCreate) -> 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:
Fruit: The newly created fruit object.
"""
db_fruit = Fruit(**fruit_data.dict())
db.add(db_fruit)
db.commit()
db.refresh(db_fruit)
return db_fruit
def update_fruit(db: Session, fruit_id: uuid.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 updated data for the fruit.
Returns:
Optional[Fruit]: The updated fruit object if found, otherwise None.
"""
db_fruit = db.query(Fruit).filter(Fruit.id == fruit_id).first()
if not db_fruit:
return None
update_data = fruit_data.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_fruit, key, value)
db.add(db_fruit)
db.commit()
db.refresh(db_fruit)
return db_fruit
def delete_fruit(db: Session, fruit_id: uuid.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 otherwise.
"""
db_fruit = db.query(Fruit).filter(Fruit.id == fruit_id).first()
if not db_fruit:
return False
db.delete(db_fruit)
db.commit()
return True
def search_fruits(db: Session, name: Optional[str] = None, description: Optional[str] = None) -> List[Fruit]:
"""
Searches for fruits based on name and/or description.
Args:
db (Session): The database session.
name (Optional[str]): The name of the fruit to search for.
description (Optional[str]): The description of the fruit to search for.
Returns:
List[Fruit]: A list of fruit objects matching the search criteria.
"""
query = db.query(Fruit)
if name:
query = query.filter(Fruit.name.ilike(f"%{name}%"))
if description:
query = query.filter(Fruit.description.ilike(f"%{description}%"))
return query.all()

16
models/fruit.py Normal file
View File

@ -0,0 +1,16 @@
from sqlalchemy import Column, String, Integer, 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, nullable=False, unique=True, index=True)
description = Column(String, nullable=True)
price = Column(Integer, nullable=False)
quantity = Column(Integer, nullable=False)
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

27
schemas/fruit.py Normal file
View File

@ -0,0 +1,27 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
import uuid
class FruitBase(BaseModel):
name: str = Field(..., description="Name of the fruit")
description: Optional[str] = Field(None, description="Description of the fruit")
price: int = Field(..., gt=0, description="Price of the fruit")
quantity: int = Field(..., gt=0, description="Quantity of the fruit")
class FruitCreate(FruitBase):
pass
class FruitUpdate(FruitBase):
name: Optional[str] = Field(None, description="Name of the fruit")
description: Optional[str] = Field(None, description="Description of the fruit")
price: Optional[int] = Field(None, gt=0, description="Price of the fruit")
quantity: Optional[int] = Field(None, gt=0, description="Quantity of the fruit")
class FruitSchema(FruitBase):
id: uuid.UUID
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True