Skip to content

Conversation

@tiangolo
Copy link
Member

@tiangolo tiangolo commented Dec 25, 2023

✨ Add support for raising exceptions (including HTTPException) in dependencies with yield in the exit code, do not support them in background tasks.

This moves the AsyncExitStack from 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 with yield with 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.

@tiangolo tiangolo added the feature New feature or request label Dec 25, 2023
@tiangolo
Copy link
Member Author

📝 Docs preview for commit 01b1fe0 at: https://48e522da.fastapitiangolo.pages.dev

@tiangolo
Copy link
Member Author

📝 Docs preview for commit c239211 at: https://775033af.fastapitiangolo.pages.dev

@tiangolo tiangolo marked this pull request as ready for review December 25, 2023 17:57
@tiangolo tiangolo merged commit a4aa79e into master Dec 25, 2023
@tiangolo tiangolo deleted the dependencies-refactor-end-before-response branch December 25, 2023 17:57
nilslindemann pushed a commit to nilslindemann/fastapi that referenced this pull request Dec 26, 2023
tiangolo added a commit that referenced this pull request Sep 21, 2025
…tion`) in dependencies with `yield` in the exit code, do not support them in background tasks (#10831)"

This reverts commit a4aa79e.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants