Replies: 4 comments
-
Also, this breaks everything described here: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#using-context-managers-in-dependencies-with-yield from pathlib import Path
from aiofiles.tempfile import NamedTemporaryFile, TemporaryDirectory
async def temp_dir_and_file(tmp_path: Path):
async with (
TemporaryDirectory(dir=tmp_path) as tmp_dir,
NamedTemporaryFile("w+b", dir=tmp_dir) as f,
):
yield f, tmp_dir |
Beta Was this translation helpful? Give feedback.
-
Unless nothing is going to be changed in the Depends logic, it's at least worth adding some sort of lock for them, aka |
Beta Was this translation helpful? Give feedback.
-
The new behavior also breaks import tempfile
import uvicorn
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
class Resource:
# pretend that the file is a db connection
def __init__(self) -> None:
self.folder = tempfile.TemporaryDirectory()
self.filename = f"{self.folder.name}/file.txt"
with open(self.filename, "w") as f:
for x in range(3000):
f.write(str(x))
def query(self):
# pretend query is getting data from a db in the form of a generator
with open(self.filename, "rb") as f:
yield from f
def close(self):
self.folder.cleanup()
def get_resource():
print("creating session")
obj = Resource()
try:
print("opening session")
yield obj
finally:
print("closing session")
obj.close()
@app.get("/data")
def data(db: Resource = Depends(get_resource)):
return StreamingResponse(db.query()) # this fails in fastapi>=0.106
# return db.query() # this works no matter what |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
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
Beta Was this translation helpful? Give feedback.
All reactions