-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
Open
Labels
bugSomething isn't workingSomething isn't working
Description
Discussed in #11107
Originally posted by FeeeeK February 7, 2024
First Check
- I added a very descriptive title here.
- I used the GitHub search to find a similar question and didn't find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google "How to X in FastAPI" and didn't find any information.
- I already read and followed all the tutorial in the docs and didn't find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
from fastapi import Depends, FastAPI, Request
app = FastAPI()
class Session:
def __init__(self):
print("creating session")
async def __aenter__(self):
print("opening session")
return self
async def __aexit__(self, exc_type, exc, tb):
print("closing session")
async def commit(self):
print("committing session")
async def rollback(self):
print("rolling back session")
@app.middleware("http")
async def commit_session(request: Request, call_next):
# minimalistic middleware for example, my code uses ASGI middleware
response = await call_next(request)
db_session = request.scope.get("db_session")
if not db_session:
return response
if response.status_code // 200 != 1:
await db_session.rollback()
else:
await db_session.commit()
return response
async def get_db_session(request: Request):
async with Session() as session:
request.scope["db_session"] = session
yield session
@app.get("/")
async def root(session: Session = Depends(get_db_session)):
return {"message": "Hello World"}
# Pre 0.106 behaviour:
# creating session
# opening session
# committing session
# closing session
# Post 0.106 behaviour:
# creating session
# opening session
# closing session
# committing session
# The session is not committed, because it's closed before the middleware is called.
Description
Before 0.106
, Depends execution after yield was after middlewares, which allowed to access resources created for a route (e.g. sessions) and do something with them depending on the response (which cannot be done with Depends), but after 0.106, the behavior has changed and this feature is no longer available. The documentation only talks about background tasks, but not a word about middlewares. Was this behavior change intentional?
Operating System
Windows
Operating System Details
No response
FastAPI Version
0.109.2
Pydantic Version
2.4.2
Python Version
3.11.1
Additional Context
No response
esatormi, binbjz, subsumer, ac130kz, brian-goo and 23 more
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't working