Response scoped dependency finalises after response is sent, unless there is an exception then it finalises early. #15021
Replies: 2 comments 2 replies
-
|
Hey! This is actually expected behavior due to how Starlette handles dependencies and exceptions. The
The first option is simpler for per-route cleanup. The second works globally. Also note that your test prints from middleware are affected by where you place the middleware relative to exception handling. The middleware Hope this clarifies! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
Per the documents this code should close the db after the response is sent.
However when I make use of similar code (above), on the happy path (200 response), then the finally happens after the response has been processed as expected.
When there is an exception, then the finally happens at the point of the exception, not after the exception has been handled and the response has been sent to the client.
This seems to directly contradict the documentation (and spirit) of this feature.
I don't want the clean up to happen during the request (successful or otherwise).
Running the example code and calling the happy and nothappy paths, you see:
The finalise happens after the 200 response, but before the 500 response.
Operating System
macOS
Operating System Details
No response
FastAPI Version
0.128.0
Pydantic Version
2.12.5
Python Version
3.12.12
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions