-
-
Notifications
You must be signed in to change notification settings - Fork 301
Closed
Description
Hi, @downdawn
I've looked at the class view implementation of fastapi_utils in general, but I'm not very interested
# End Setup
app = FastAPI()
router = InferringRouter() # Step 1: Create a router
@cbv(router) # Step 2: Create and decorate a class to hold the endpoints
class ItemCBV:
# Step 3: Add dependencies as class attributes
session: Session = Depends(get_db)
user_id: UserID = Depends(get_jwt_user)
@router.post("/item")
def create_item(self, item: ItemCreate) -> ItemInDB:
# Step 4: Use `self.<dependency_name>` to access shared dependencies
item_orm = ItemORM(name=item.name, owner=self.user_id)
self.session.add(item_orm)
self.session.commit()
return ItemInDB.from_orm(item_orm)For session, since we're using SQLAlchemy-2.0, we'll use async_db_session.begin() directly, this seems to make more sense
from functools import wraps
def session_decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
async with async_db_session.begin() as db:
return await func(db, *args, **kwargs)
return wrapper
class ApiService:
@staticmethod
@session_decorator
async def get_api_list(db):
return await paginate(db, ApiDao.get_all_apis())For Depends(get_jwt_user), we need to make FastAPI >= 0.95.0, then use the Annotated feature, and call it globally, E.g:
CurrentUser = Annotated[User, Depends(get_current_user)]Like in the fastapi documentation: Share Annotated dependencies
Metadata
Metadata
Assignees
Labels
No labels