How to use dependencies with yield in FastApi

755 Views Asked by At

I am using FastApi and I would like to know if I am using the dependencies correctly.

First, I have a function that yields the database session.

class ContextManager:
     def __init__(self):
         self.db = DBSession()
  
     def __enter__(self):
         return self.db

     def __exit__(self):
         self.db.close()

def get_db():
         with ContextManager() as db:
          yield db

I would like to use that function in another function:

def validate(db=Depends(get_db)):

  is_valid = verify(db)
  
  if not is is_valid:
     raise HTTPException(status_code=400)

  yield db

Finally, I would like to use the last functions as a dependency on the routes:

@router.get('/')
def get_data(db=Depends(validate)):

  data = db.query(...)

  return data

I am using this code and it seems to work, but I would like to know if it is the most appropiate way to use dependencies. Especially, I am not sure if I have to use 'yield db' inside the function validate or it would be better to use return. I would appreciate your help. Thanks a lot

0

There are 0 best solutions below