Skip to content

Commit d623544

Browse files
authored
🐛 Fix support for background tasks and headers from dependencies in app.frontend() (#16105)
1 parent 1d211b9 commit d623544

3 files changed

Lines changed: 52 additions & 6 deletions

File tree

‎docs/en/docs/tutorial/frontend.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,8 @@ Frontend responses run inside the normal **FastAPI** application, so HTTP middle
136136

137137
Dependencies from the app, from an `APIRouter`, and from `include_router()` also apply to frontend responses. This can be useful for protecting a frontend with cookie authentication or similar.
138138

139+
Dependencies can also modify response headers and add background tasks, as with normal *path operations*.
140+
139141
## Static Build Output Only { #static-build-output-only }
140142

141143
`app.frontend()` serves files already generated by your frontend build.

‎fastapi/routing.py‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
_is_gen_callable,
5757
)
5858
from fastapi.dependencies.utils import (
59+
SolvedDependency,
5960
_get_body_field,
6061
_get_flat_body_params,
6162
_should_embed_body_fields,
@@ -1936,6 +1937,12 @@ def get_path(self, scope: Scope) -> str:
19361937
assert isinstance(path, str)
19371938
return os.path.normpath(os.path.join(*path.split("/")))
19381939

1940+
async def get_response_for_scope(self, scope: Scope) -> Response:
1941+
if not self.config_checked:
1942+
await self.check_config()
1943+
self.config_checked = True
1944+
return await self.get_response(self.get_path(scope), scope)
1945+
19391946
async def get_response(self, path: str, scope: Scope) -> Response:
19401947
if scope["method"] not in ("GET", "HEAD"):
19411948
if await self._lookup_static_resource(path) is not None:
@@ -2086,7 +2093,8 @@ def _get_frontend_path(self, path: str, route_path: str) -> str | None:
20862093
return None
20872094

20882095
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
2089-
await self.app(scope, receive, send)
2096+
response = await self.app.get_response_for_scope(scope)
2097+
await response(scope, receive, send)
20902098

20912099
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
20922100
raise NoMatchFound(name, path_params)
@@ -2189,8 +2197,12 @@ async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
21892197
dependant=dependant,
21902198
dependency_overrides_provider=dependency_overrides_provider,
21912199
embed_body_fields=embed_body_fields,
2192-
):
2193-
await route.handle(scope, receive, send)
2200+
) as solved_result:
2201+
response = await route.app.get_response_for_scope(scope)
2202+
if response.background is None:
2203+
response.background = solved_result.background_tasks
2204+
response.headers.raw.extend(solved_result.response.headers.raw)
2205+
await response(scope, receive, send)
21942206
return
21952207
await route.handle(scope, receive, send)
21962208

@@ -2210,7 +2222,7 @@ async def _solve_dependencies(
22102222
dependant: Dependant,
22112223
dependency_overrides_provider: Any | None,
22122224
embed_body_fields: bool,
2213-
) -> AsyncIterator[None]:
2225+
) -> AsyncIterator[SolvedDependency]:
22142226
request = Request(scope, receive, send)
22152227
previous_inner_astack = scope.get("fastapi_inner_astack", _SCOPE_MISSING)
22162228
previous_function_astack = scope.get("fastapi_function_astack", _SCOPE_MISSING)
@@ -2228,7 +2240,7 @@ async def _solve_dependencies(
22282240
)
22292241
if solved_result.errors:
22302242
raise RequestValidationError(solved_result.errors)
2231-
yield
2243+
yield solved_result
22322244
finally:
22332245
if previous_inner_astack is _SCOPE_MISSING:
22342246
scope.pop("fastapi_inner_astack", None)

‎tests/test_frontend.py‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,15 @@
77

88
import anyio
99
import pytest
10-
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, WebSocket
10+
from fastapi import (
11+
APIRouter,
12+
BackgroundTasks,
13+
Depends,
14+
FastAPI,
15+
HTTPException,
16+
Request,
17+
WebSocket,
18+
)
1119
from fastapi.testclient import TestClient
1220
from starlette.exceptions import HTTPException as StarletteHTTPException
1321
from starlette.responses import PlainTextResponse, Response
@@ -491,6 +499,30 @@ async def record_middleware(request: Request, call_next):
491499
assert calls == ["middleware-before", "dependency", "middleware-after"]
492500

493501

502+
def test_frontend_dependency_response_headers_and_background_tasks(tmp_path: Path):
503+
calls: list[str] = []
504+
505+
def frontend_dependency(
506+
response: Response, background_tasks: BackgroundTasks
507+
) -> None:
508+
response.headers["X-Frontend-Dependency"] = "applied"
509+
response.set_cookie("frontend", "dependency")
510+
background_tasks.add_task(calls.append, "background")
511+
512+
dist = tmp_path / "dist"
513+
write_file(dist / "index.html", "app")
514+
app = FastAPI(dependencies=[Depends(frontend_dependency)])
515+
app.frontend("/", directory=dist)
516+
517+
response = TestClient(app).get("/")
518+
519+
assert response.status_code == 200
520+
assert response.text == "app"
521+
assert response.headers["X-Frontend-Dependency"] == "applied"
522+
assert response.cookies["frontend"] == "dependency"
523+
assert calls == ["background"]
524+
525+
494526
def test_frontend_dependency_validation_errors_return_422(tmp_path: Path):
495527
def require_token(token: str) -> None:
496528
pass # pragma: no cover

0 commit comments

Comments
 (0)