middleware request transaction handling with deferred callable return for refresh of orm #8036
-
Is your feature request related to a problem? Please describe. This is difficult to do at a request level, because In the fastapi documentation on sql databases, the commit happens within the create statement, which makes sense in order to return the user with the id. However, this doesn't allow for request level global transaction handling, which is really what is desired.
Describe the solution you'd like It seems like you would want the route that's handling the request to return a function instead of a response. This function would get called after the commit with the db session (post commit) and could refresh objects. That function would handle translating the orm model to the pydantic model, and should return the Response with the pydantic model as the response object. So if the middleware returned the result of the function, it would work. Something like:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Is there a reason you can't just create a transaction in the middleware, and (if desired) a nested transaction inside the endpoint? Having your routes return functions instead of responses is a major deviation from what starlette expects, and is likely to cause fragility. In particular, the suggested implementation would force you to return a response_func from all endpoints, even if they have no interaction with the sqlalchemy session. |
Beta Was this translation helpful? Give feedback.
-
That's what I ended up doing. Thanks. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help @dmontagu ! 🚀 And thanks @jim-obrien-orig for reporting back and closing the issue 🎉 |
Beta Was this translation helpful? Give feedback.
Is there a reason you can't just create a transaction in the middleware, and (if desired) a nested transaction inside the endpoint?
Having your routes return functions instead of responses is a major deviation from what starlette expects, and is likely to cause fragility. In particular, the suggested implementation would force you to return a response_func from all endpoints, even if they have no interaction with the sqlalchemy session.