feat: Generated endpoint endpoints/toys.post.py via AI for Toy

This commit is contained in:
Backend IM Bot 2025-04-16 12:29:08 +00:00
parent f13ebd2fa9
commit 88f51bd06e
5 changed files with 145 additions and 0 deletions

View File

@ -0,0 +1,31 @@
"""create table for toys
Revision ID: 2f3c6a7d0a2e
Revises: 2a6c9d7ef8b4
Create Date: 2023-05-23 15:21:16.843141
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import func
# revision identifiers, used by Alembic.
revision = '2f3c6a7d0a2e'
down_revision = '2a6c9d7ef8b4'
branch_labels = None
depends_on = None
def upgrade():
table_name = "toys"
op.create_table(
table_name,
sa.Column('id', sa.String(36), primary_key=True, default=func.uuid_generate_v4()),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('price', sa.Integer(), 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())
)
def downgrade():
table_name = "toys"
op.drop_table(table_name)

View File

@ -0,0 +1,25 @@
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from typing import List
from core.database import get_db
from schemas.toy import ToySchema, ToyCreate
from helpers.toy_helpers import get_all_toys, create_toy
router = APIRouter()
@router.post("/toys", status_code=status.HTTP_201_CREATED, response_model=ToySchema)
async def create_new_toy(
toy: ToyCreate,
db: Session = Depends(get_db)
):
"""Create a new toy"""
new_toy = create_toy(db=db, toy_data=toy)
return new_toy
@router.get("/toys", status_code=200, response_model=List[ToySchema])
async def get_toys(
db: Session = Depends(get_db)
):
"""Get all toys"""
toys = get_all_toys(db)
return toys

49
helpers/toy_helpers.py Normal file
View File

@ -0,0 +1,49 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from uuid import UUID
from models.toy import Toy
from schemas.toy import ToyCreate, ToySchema
def get_all_toys(db: Session) -> List[ToySchema]:
"""
Retrieves all toys from the database.
Args:
db (Session): The database session.
Returns:
List[ToySchema]: A list of all toy objects.
"""
toys = db.query(Toy).all()
return [ToySchema.from_orm(toy) for toy in toys]
def create_toy(db: Session, toy_data: ToyCreate) -> ToySchema:
"""
Creates a new toy in the database.
Args:
db (Session): The database session.
toy_data (ToyCreate): The data for the toy to create.
Returns:
ToySchema: The newly created toy object.
"""
db_toy = Toy(**toy_data.dict())
db.add(db_toy)
db.commit()
db.refresh(db_toy)
return ToySchema.from_orm(db_toy)
def get_toy_by_id(db: Session, toy_id: UUID) -> Optional[ToySchema]:
"""
Retrieves a single toy by its ID.
Args:
db (Session): The database session.
toy_id (UUID): The ID of the toy to retrieve.
Returns:
Optional[ToySchema]: The toy object if found, otherwise None.
"""
db_toy = db.query(Toy).filter(Toy.id == toy_id).first()
return ToySchema.from_orm(db_toy) if db_toy else None

15
models/toy.py Normal file
View File

@ -0,0 +1,15 @@
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 Toy(Base):
__tablename__ = "toys"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String, nullable=False)
description = Column(String, nullable=True)
price = Column(Integer, nullable=False)
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

25
schemas/toy.py Normal file
View File

@ -0,0 +1,25 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
import uuid
class ToyBase(BaseModel):
name: str = Field(..., description="Name of the toy")
description: Optional[str] = Field(None, description="Description of the toy")
price: int = Field(..., description="Price of the toy")
class ToyCreate(ToyBase):
pass
class ToyUpdate(ToyBase):
name: Optional[str] = Field(None, description="Name of the toy")
description: Optional[str] = Field(None, description="Description of the toy")
price: Optional[int] = Field(None, description="Price of the toy")
class ToySchema(ToyBase):
id: uuid.UUID
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True