feat: Generated endpoint endpoints/bunny.get.py via AI for Car with auto lint fixes

This commit is contained in:
Backend IM Bot 2025-04-16 10:43:46 +00:00
parent ac5706f29d
commit 156c96981e
5 changed files with 274 additions and 0 deletions

View File

@ -0,0 +1,35 @@
"""create car table
Revision ID: 0002
Revises: 0001
Create Date: 2024-01-30 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '0002'
down_revision = '0001'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'cars',
sa.Column('id', sa.String(36), primary_key=True),
sa.Column('brand', sa.String(), nullable=False),
sa.Column('model', sa.String(), nullable=False),
sa.Column('year', sa.Integer(), nullable=False),
sa.Column('color', sa.String(), nullable=True),
sa.Column('vin', sa.String(), nullable=False),
sa.Column('price', sa.Integer(), nullable=False),
sa.Column('is_available', sa.Boolean(), server_default='1'),
sa.Column('mileage', sa.Integer(), server_default='0'),
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now())
)
op.create_index(op.f('ix_cars_brand'), 'cars', ['brand'], unique=False)
op.create_index(op.f('ix_cars_vin'), 'cars', ['vin'], unique=True)
def downgrade():
op.drop_index(op.f('ix_cars_vin'), table_name='cars')
op.drop_index(op.f('ix_cars_brand'), table_name='cars')
op.drop_table('cars')

View File

@ -0,0 +1,19 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from core.database import get_db
from schemas.car import CarSchema
from helpers.car_helpers import get_available_german_cars
router = APIRouter()
@router.get("/bunny", response_model=List[CarSchema], status_code=200)
async def get_german_cars(
brand: str = None,
db: Session = Depends(get_db)
):
try:
cars = get_available_german_cars(db=db, brand=brand)
return cars
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))

148
helpers/car_helpers.py Normal file
View File

@ -0,0 +1,148 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy import and_
from uuid import UUID
import random
import string
from models.car import Car
from schemas.car import CarCreate
def generate_german_cars(db: Session, count: int = 10) -> List[Car]:
"""
Generates and stores a list of German cars in the database.
Args:
db (Session): The database session
count (int): Number of cars to generate (default: 10)
Returns:
List[Car]: List of generated car objects
"""
german_brands = ['BMW', 'Mercedes-Benz', 'Audi', 'Porsche', 'Volkswagen']
models = {
'BMW': ['M3', 'M5', 'X5', '7 Series', 'i8'],
'Mercedes-Benz': ['C-Class', 'E-Class', 'S-Class', 'GLE', 'AMG GT'],
'Audi': ['A4', 'A6', 'Q7', 'RS6', 'e-tron'],
'Porsche': ['911', 'Cayenne', 'Panamera', 'Taycan', 'Macan'],
'Volkswagen': ['Golf', 'Passat', 'Tiguan', 'Touareg', 'ID.4']
}
colors = ['Black', 'White', 'Silver', 'Blue', 'Red', 'Grey']
generated_cars = []
for _ in range(count):
brand = random.choice(german_brands)
model = random.choice(models[brand])
vin = ''.join(random.choices(string.ascii_uppercase + string.digits, k=17))
car_data = CarCreate(
brand=brand,
model=model,
year=random.randint(2020, 2024),
color=random.choice(colors),
vin=vin,
price=random.randint(35000, 150000),
is_available=True,
mileage=random.randint(0, 5000)
)
db_car = Car(**car_data.dict())
db.add(db_car)
generated_cars.append(db_car)
db.commit()
return generated_cars
def get_available_german_cars(db: Session, brand: Optional[str] = None) -> List[Car]:
"""
Retrieves available German cars, optionally filtered by brand.
Args:
db (Session): The database session
brand (Optional[str]): Specific German brand to filter by
Returns:
List[Car]: List of available German cars
"""
german_brands = ['BMW', 'Mercedes-Benz', 'Audi', 'Porsche', 'Volkswagen']
query = db.query(Car).filter(Car.is_available)
if brand:
if brand not in german_brands:
raise ValueError("Invalid German car brand")
query = query.filter(Car.brand == brand)
else:
query = query.filter(Car.brand.in_(german_brands))
return query.all()
def update_car_price_and_availability(
db: Session,
car_id: UUID,
new_price: Optional[int] = None,
is_available: Optional[bool] = None
) -> Optional[Car]:
"""
Updates a car's price and availability status.
Args:
db (Session): The database session
car_id (UUID): The ID of the car to update
new_price (Optional[int]): New price for the car
is_available (Optional[bool]): New availability status
Returns:
Optional[Car]: Updated car object if found, None otherwise
"""
car = db.query(Car).filter(Car.id == car_id).first()
if not car:
return None
if new_price is not None:
car.price = new_price
if is_available is not None:
car.is_available = is_available
db.commit()
db.refresh(car)
return car
def get_cars_by_price_range(
db: Session,
min_price: int,
max_price: int,
brand: Optional[str] = None
) -> List[Car]:
"""
Retrieves cars within a specified price range, optionally filtered by brand.
Args:
db (Session): The database session
min_price (int): Minimum price
max_price (int): Maximum price
brand (Optional[str]): Specific brand to filter by
Returns:
List[Car]: List of cars matching the criteria
"""
query = db.query(Car).filter(
and_(
Car.price >= min_price,
Car.price <= max_price
)
)
if brand:
query = query.filter(Car.brand == brand)
return query.all()
def generate_vin() -> str:
"""
Generates a random VIN number.
Returns:
str: Generated VIN number
"""
# VIN format: 17 characters (letters and numbers)
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=17))

22
models/car.py Normal file
View File

@ -0,0 +1,22 @@
from sqlalchemy import Column, String, DateTime, Boolean, Integer
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from core.database import Base
import uuid
class Car(Base):
__tablename__ = "cars"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
brand = Column(String, nullable=False, index=True)
model = Column(String, nullable=False)
year = Column(Integer, nullable=False)
color = Column(String, nullable=True)
vin = Column(String, unique=True, nullable=False)
price = Column(Integer, nullable=False)
is_available = Column(Boolean, default=True)
mileage = Column(Integer, default=0)
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

50
schemas/car.py Normal file
View File

@ -0,0 +1,50 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
from uuid import UUID
class CarBase(BaseModel):
brand: str = Field(..., description="Car brand")
model: str = Field(..., description="Car model")
year: int = Field(..., description="Manufacturing year")
color: Optional[str] = Field(None, description="Car color")
vin: str = Field(..., description="Vehicle Identification Number")
price: int = Field(..., description="Car price")
is_available: bool = Field(True, description="Availability status")
mileage: int = Field(0, description="Current mileage")
class CarCreate(CarBase):
pass
class CarUpdate(BaseModel):
brand: Optional[str] = Field(None, description="Car brand")
model: Optional[str] = Field(None, description="Car model")
year: Optional[int] = Field(None, description="Manufacturing year")
color: Optional[str] = Field(None, description="Car color")
vin: Optional[str] = Field(None, description="Vehicle Identification Number")
price: Optional[int] = Field(None, description="Car price")
is_available: Optional[bool] = Field(None, description="Availability status")
mileage: Optional[int] = Field(None, description="Current mileage")
class CarSchema(CarBase):
id: UUID
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
schema_extra = {
"example": {
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"brand": "BMW",
"model": "M3",
"year": 2023,
"color": "Black",
"vin": "1HGCM82633A123456",
"price": 85000,
"is_available": True,
"mileage": 0,
"created_at": "2023-01-01T12:00:00",
"updated_at": "2023-01-01T12:00:00"
}
}