Open hamzaahmad-io opened 3 years ago
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class BaseModel(Base):
__abstract__ = True
id = Column(Integer, primary_key=True)
# Other common fields
from typing import List, Type, Optional
from sqlalchemy.orm import Session
from fastapi import Depends
class CRUDBase:
def __init__(self, model: Type[BaseModel]):
self.model = model
def get_one(self, db: Session, id: int) -> Optional[BaseModel]:
return db.query(self.model).filter(self.model.id == id).first()
def get_many(self, db: Session) -> List[BaseModel]:
return db.query(self.model).all()
# Other CRUD methods
from fastapi import FastAPI, Depends, HTTPException, status
from sqlalchemy.orm import Session
app = FastAPI()
def get_db():
db = ... # create a database session
try:
yield db
finally:
db.close()
class User(BaseModel):
__tablename__ = 'users'
first_name = Column(String(20))
last_name = Column(String(20))
user_crud = CRUDBase(User)
@app.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
user = user_crud.get_one(db, user_id)
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
return user
In this example, the CRUDBase
class is created to define common CRUD operations. You can inject the SQLAlchemy Session
using FastAPI's Depends
dependency mechanism. The read_user
route demonstrates how to use the CRUDBase
class to retrieve a user by ID from the database.
Please adjust the code according to your specific needs and integrate it into your FastAPI application.
Can the methods defined in the base CRUD class be "safely" moved to the base SQLAlchemy class? What am I missing by combining the two classes/components? Yes I understand that
CRUDBase
currently has a dependency of the SQLAlchemy model classGeneric[ModelType]
when being defined. Does that dependency really need to be there?This is my first time using FastAPI. Here's an example of how I have previously defined the components in another framework, Flask:
Once
CRUDMixin
is defined with all CRUD functionalities, it can be inherited by the SQLAlchemy model classes:An example of how the SQLAlchemy model can then be directly used within the API routes: