✨ Add support for raising exceptions (including HTTPException) in dependencies with yield in the exit code, do not support them in background tasks
#10831
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
✨ Add support for raising exceptions (including
HTTPException) in dependencies withyieldin the exit code, do not support them in background tasks.This moves the
AsyncExitStackfrom a middleware that would run the exit code after the response is sent and background tasks are executed to inside of the dependencies logic, after creating the response but before sending it.So, now dependencies with yield are nicely wrapped by exception handlers, middleware, and the request-response cycle.
Before they would be executed after background tasks finished. The intention was to allow sharing the same database connection, but this would mean holding a resource (e.g. DB connection) until after the request travels through the network, it would prevent supporting raising exceptions after
yield, and allowed dangerously coupling logic related to resources from dependencies withyieldwith background tasks (e.g. hard to test).This will also enable several new features and changes, including upgrades to the recent versions of Starlette, and/or making background tasks independent of the request-response lifecycle, etc.