Potential footgun when using custom `Response(background=<Task()>)` in conjunction with injected `BackgroundTasks` - the custom response overwrites the tasks
Discussed in #11214
Originally posted by netanel-haber February 28, 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 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)
Description
Hey! 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 BackgroundTasks.
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 System
macOS
Operating System Details
No response
FastAPI Version
0.97.0
Pydantic Version
1.10.7
Python Version
3.9
Additional Context
No response