
- Set up FastAPI application with SQLite database - Implement User and Item models with relationships - Add CRUD operations for users and items - Configure Alembic for database migrations - Include API documentation at /docs and /redoc - Add health check endpoint at /health - Enable CORS for all origins - Structure code with proper separation of concerns
52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
|
|
from pydantic import BaseModel
|
|
from sqlalchemy.orm import Session
|
|
from app.db.base import Base
|
|
|
|
ModelType = TypeVar("ModelType", bound=Base)
|
|
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
|
|
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
|
|
|
|
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
|
|
def __init__(self, model: Type[ModelType]):
|
|
self.model = model
|
|
|
|
def get(self, db: Session, id: Any) -> Optional[ModelType]:
|
|
return db.query(self.model).filter(self.model.id == id).first()
|
|
|
|
def get_multi(
|
|
self, db: Session, *, skip: int = 0, limit: int = 100
|
|
) -> List[ModelType]:
|
|
return db.query(self.model).offset(skip).limit(limit).all()
|
|
|
|
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
|
|
obj_in_data = obj_in.dict()
|
|
db_obj = self.model(**obj_in_data)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
def update(
|
|
self,
|
|
db: Session,
|
|
*,
|
|
db_obj: ModelType,
|
|
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
|
|
) -> ModelType:
|
|
if isinstance(obj_in, dict):
|
|
update_data = obj_in
|
|
else:
|
|
update_data = obj_in.dict(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_obj, field, value)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
def remove(self, db: Session, *, id: int) -> ModelType:
|
|
obj = db.query(self.model).get(id)
|
|
db.delete(obj)
|
|
db.commit()
|
|
return obj |