Browse Source
Add a warning to the "Return a Response Directly" docs page explaining that returning a Response with a background parameter silently overrides any BackgroundTasks added via dependency injection. Closes #11215pull/15217/head
2 changed files with 40 additions and 0 deletions
@ -0,0 +1,26 @@ |
|||
from fastapi import BackgroundTasks, FastAPI |
|||
from starlette.responses import JSONResponse |
|||
|
|||
app = FastAPI() |
|||
|
|||
|
|||
def write_log(message: str): |
|||
with open("log.txt", mode="a") as log: |
|||
log.write(message) |
|||
|
|||
|
|||
# Correct: use only BackgroundTasks (no background= on Response) |
|||
@app.get("/correct") |
|||
async def send_notification(background_tasks: BackgroundTasks): |
|||
background_tasks.add_task(write_log, "Notification sent") |
|||
return JSONResponse(content={"message": "done"}) |
|||
|
|||
|
|||
# Wrong: background= on Response silently overrides BackgroundTasks |
|||
@app.get("/wrong") |
|||
async def send_notification_wrong(background_tasks: BackgroundTasks): |
|||
background_tasks.add_task(write_log, "This task will NOT run") |
|||
return JSONResponse( |
|||
content={"message": "done"}, |
|||
background=None, # If this were a BackgroundTask, it would override the line above |
|||
) |
|||
Loading…
Reference in new issue