Yield dependency doesn't allow to add a background task in its closing code #6871
-
First check
ExampleHere's a self-contained, minimal, reproducible, example with my use case: from fastapi import FastAPI, Request, Depends, BackgroundTasks
app = FastAPI()
async def dep(background: BackgroundTasks):
background.add_task(print, "before yield")
yield "something"
background.add_task(print, "after yield")
@app.get("/")
async def read_root(d: str = Depends(dep)):
return {"Hello": "World", "dependency": d} Description
Environment
Additional contextI know that a task added after a response being sent has no chance to be executed. I guess there should be a warning or error if a user tries to do that, something like: |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
Agreed that it should at least be mentioned in the documentation. Would you be up for adding a note at the end of this section about this behavior and submitting a PR? https://fastapi.tiangolo.com/tutorial/background-tasks/#dependency-injection |
Beta Was this translation helpful? Give feedback.
-
Thanks for the answer @falkben! Sure, it needs to be documented. I'll send a PR soon. Another solution could be extending Starlette's |
Beta Was this translation helpful? Give feedback.
-
Yep, dependencies with yield are closed after background tasks are done. This was to be able to use the same DB session. But I see that in some cases it would make sense to close them before the response is sent. That's something I've been considering and thinking about how to properly implement. All that is documented a bit here, wth a pretty diagram and everything: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception
|
Beta Was this translation helpful? Give feedback.
-
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs. |
Beta Was this translation helpful? Give feedback.
Yep, dependencies with yield are closed after background tasks are done. This was to be able to use the same DB session.
But I see that in some cases it would make sense to close them before the response is sent. That's something I've been considering and thinking about how to properly implement.
All that is documented a bit here, wth a pretty diagram and everything: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception