Potential footgun when using custom Response(background=<Task()>)
in conjunction with injected BackgroundTasks
- the custom response overwrites the tasks
#11214
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, BackgroundTasks
from starlette.responses import Response, BackgroundTask
import uvicorn
app = FastAPI()
@app.get("/")
async def endpoint(tasks: BackgroundTasks):
tasks.add_task(lambda: print("This won't be printed"))
return Response(content="Custom response", background=BackgroundTask(lambda: print("Only this will be printed")))
uvicorn.run(app) DescriptionHey! Thanks for the best framework in Python and generally ❤️ Basically, passing a background task to a custom response overwrites any other tasks added to the injected I'm not sure this is considered a bug, but I think it's confusing and can at least be clarified in the Return a Response Directly docs, for example. Other solutions can be actually changing this behavior (I guess that's a breaking change), or printing a warning/throwing [throwing is also a breaking change] if both mechanisms are used at once. But I can't imagine a user desiring this behavior. To be clear, this tripped us up when we couldn't figure out why some of our tasks were being swallowed. I'd be happy to work on either solution, obviously adding a docs pr would be the easiest first step. Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.97.0 Pydantic Version1.10.7 Python Version3.9 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Thanks 👍 |
Beta Was this translation helpful? Give feedback.
Thanks 👍