from fastapi import FastAPI, Depends, HTTPException, status, Query, Path from sqlalchemy.orm import Session import crud import models import schemas from database import engine, get_db from typing import List, Optional import uvicorn # Создание таблиц в БД models.Base.metadata.create_all(bind=engine) app = FastAPI(title="AutoBro API", description="API для управления базой данных автомобилей") @app.get("/") def read_root(): return {"message": "AutoBro API"} @app.get("/cars", response_model=schemas.CarsResponse) def get_cars( skip: int = Query(0, description="Количество пропускаемых записей"), limit: int = Query(100, description="Максимальное количество записей"), db: Session = Depends(get_db) ): cars = crud.get_cars(db, skip=skip, limit=limit) total = crud.get_cars_count(db) return {"cars": cars, "total": total} @app.get("/cars/{car_id}", response_model=schemas.CarResponse) def get_car( car_id: int = Path(..., description="ID автомобиля", gt=0), db: Session = Depends(get_db) ): car = crud.get_car(db, car_id=car_id) if car is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Автомобиль не найден" ) return {"car": car} @app.post("/cars", response_model=schemas.CarResponse, status_code=status.HTTP_201_CREATED) def create_car( car: schemas.CarCreate, db: Session = Depends(get_db) ): db_car = crud.create_car(db=db, car=car) return {"car": db_car} @app.put("/cars/{car_id}", response_model=schemas.CarResponse) def update_car( car_id: int = Path(..., description="ID автомобиля", gt=0), car_update: schemas.CarUpdate = ..., db: Session = Depends(get_db) ): updated_car = crud.update_car(db=db, car_id=car_id, car_update=car_update) if updated_car is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Автомобиль не найден" ) return {"car": updated_car} @app.delete("/cars/{car_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_car( car_id: int = Path(..., description="ID автомобиля", gt=0), db: Session = Depends(get_db) ): success = crud.delete_car(db=db, car_id=car_id) if not success: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Автомобиль не найден" ) return None if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=3000)