0

I have a simple function in Fast API app that gets called by a cron, something like this (note that this is not a get or post Fast API method but a simple function):

def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)

where get_db is:

from database import SessionLocal

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

And database.py is:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "://url-to-db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

Since crud method takes db (object of SessionLocal yielded by get_db) as a param, how do I use it as a dependency injection with my function just like we use in GET or POST as shown in code read_user method above.

Mudasir Zahoor
  • 894
  • 6
  • 18
  • 2
    In that case you should call `get_db` directly; the main point about using `Depends` is that you can have a hierarchy of dependencies resolved dynamically based on the request. See https://github.com/tiangolo/fastapi/issues/1105 – MatsLindh Sep 13 '21 at 07:50
  • 2
    Related https://stackoverflow.com/questions/66558958/fastapi-dependencies-yield-how-to-call-them-manually – alex_noname Sep 13 '21 at 07:58

0 Answers0