From 6bb573ee7e33af14e7abfbca6a74619f90c02ac5 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci-lite[bot]" <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com> Date: Sun, 8 Feb 2026 01:15:11 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20Auto=20format?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/routing.py | 19 ++++++++++++++----- tests/test_background_tasks_merge.py | 1 + 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index c567fb6241..6bda963e43 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -434,22 +434,31 @@ def get_request_handler( elif solved_result.background_tasks is not None: # Merge background tasks from dependency injection with tasks from Response # The Response's background can be either a BackgroundTask or BackgroundTasks - from starlette.background import BackgroundTask, BackgroundTasks as StarletteBackgroundTasks + from starlette.background import BackgroundTask + from starlette.background import ( + BackgroundTasks as StarletteBackgroundTasks, + ) if isinstance(raw_response.background, StarletteBackgroundTasks): # If Response has BackgroundTasks, prepend the injected tasks - if isinstance(solved_result.background_tasks, StarletteBackgroundTasks): + if isinstance( + solved_result.background_tasks, StarletteBackgroundTasks + ): # Prepend all injected tasks before the response tasks raw_response.background.tasks = ( - solved_result.background_tasks.tasks + raw_response.background.tasks + solved_result.background_tasks.tasks + + raw_response.background.tasks ) elif isinstance(raw_response.background, BackgroundTask): # If Response has a single BackgroundTask, convert to BackgroundTasks response_task = raw_response.background - if isinstance(solved_result.background_tasks, StarletteBackgroundTasks): + if isinstance( + solved_result.background_tasks, StarletteBackgroundTasks + ): # Create new BackgroundTasks with injected tasks + response task raw_response.background = StarletteBackgroundTasks( - tasks=solved_result.background_tasks.tasks + [response_task] + tasks=solved_result.background_tasks.tasks + + [response_task] ) else: # Both are single tasks diff --git a/tests/test_background_tasks_merge.py b/tests/test_background_tasks_merge.py index 266c8e62fa..12e71a64c8 100644 --- a/tests/test_background_tasks_merge.py +++ b/tests/test_background_tasks_merge.py @@ -2,6 +2,7 @@ Test that background tasks from injected BackgroundTasks and Response.background are both executed. Related to issue #11215 """ + from fastapi import BackgroundTasks, FastAPI from fastapi.responses import Response from fastapi.testclient import TestClient