1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| from typing import Type, TypeVar, Generic, List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from pydantic import BaseModel from app.crud.base import CRUDBase from app.db.session import SessionLocal
ModelType = TypeVar("ModelType", bound=BaseModel) CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDRouter(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): def __init__(self, crud: CRUDBase[ModelType, CreateSchemaType, UpdateSchemaType]): self.crud = crud self.router = APIRouter()
self.router.post("/", response_model=ModelType)(self.create_item) self.router.get("/{item_id}", response_model=ModelType)(self.read_item) self.router.put("/{item_id}", response_model=ModelType)(self.update_item) self.router.delete("/{item_id}", response_model=ModelType)(self.delete_item) self.router.get("/", response_model=List[ModelType])(self.read_items)
def get_db(self): db = SessionLocal() try: yield db finally: db.close()
async def create_item(self, item_in: CreateSchemaType, db: Session = Depends(self.get_db)): db_item = self.crud.create(db=db, obj_in=item_in) return db_item
async def read_item(self, item_id: int, db: Session = Depends(self.get_db)): db_item = self.crud.get(db=db, id=item_id) if not db_item: raise HTTPException(status_code=404, detail="Item not found") return db_item
async def update_item(self, item_id: int, item_in: UpdateSchemaType, db: Session = Depends(self.get_db)): db_item = self.crud.get(db=db, id=item_id) if not db_item: raise HTTPException(status_code=404, detail="Item not found") return self.crud.update(db=db, db_obj=db_item, obj_in=item_in)
async def delete_item(self, item_id: int, db: Session = Depends(self.get_db)): db_item = self.crud.get(db=db, id=item_id) if not db_item: raise HTTPException(status_code=404, detail="Item not found") return self.crud.remove(db=db, id=item_id)
async def read_items(self, skip: int = 0, limit: int = 10, db: Session = Depends(self.get_db)): items = self.crud.get_multi(db=db, skip=skip, limit=limit) return items
|