dmontagu / fastapi-utils

Reusable utilities for FastAPI
MIT License
1.89k stars 165 forks source link

[BUG] Cannot use get_db as a dependency with repeated task #253

Open rafaluk opened 3 years ago

rafaluk commented 3 years ago

While using fastapi-utils scheduler, passing Depends(get_db) as a parameter to the function doesn't work.

This is how it works within FastAPI endpoint:

@app.post("/sample_test")
async def sample_test(db: Session = Depends(get_db)):
    return db.query(models.User.height).all()

This is how it doesn't work with FastAPI utils:

@app.on_event("startup")
@repeat_every(seconds=10)
async def sample_test(db: Session = Depends(get_db)):
    return db.query(models.User.height).all()

(note that the functions are the same, only decorators have changed)

There is no error, but the query is not being called (I think the session is not created?). It just gets stuck.

The get_db() function differs a little bit between those two, but under the hood it does the same for both.

Environment:

tintinthong commented 2 years ago

Yup. I face the same issue here

shakthifuture commented 2 years ago

I am also facing the same issue, any solution?

hussainsajib commented 2 years ago

The reason it doesn't work in repeat_task is because Depends can't be used in our own functions. It has to be in FastAPI function. Refer to this: https://github.com/tiangolo/fastapi/issues/1693#issuecomment-665833384

However, I also trying to access Session from a repeated_task function and is unable. Did anyone found any workaround?

julienV commented 2 years ago

well, you can always get your objects without the dependency injection mechanism... Not great for testing though

from app.db import SessionLocal
....
@app.on_event("startup")
@repeat_every(seconds=60)
async def do_something() -> None:
    db = SessionLocal()
   ....