From 184de532e6a206ea31f8acc76100f42aed4df2ad Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Wed, 18 May 2022 22:13:37 +0200 Subject: [PATCH 1/2] Document `BaseHTTPMiddleware` bugs --- docs/middleware.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/middleware.md b/docs/middleware.md index b21914291..ca41b0219 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -215,7 +215,6 @@ class CustomHeaderMiddleware(BaseHTTPMiddleware): return response - middleware = [ Middleware(CustomHeaderMiddleware, header_value='Customized') ] @@ -227,6 +226,12 @@ Middleware classes should not modify their state outside of the `__init__` metho Instead you should keep any state local to the `dispatch` method, or pass it around explicitly, rather than mutating the middleware instance. +!!! bug + Currently, the `BaseHTTPMiddleware` has two known issues: + + - It's not possible to use multiple `BaseHTTPMiddleware` based middlewares. + - It's not possible to use `BackgroundTasks` with `BaseHTTPMiddleware`. + ## Using middleware in other frameworks To wrap ASGI middleware around other ASGI applications, you should use the From 35138dab7ac22773cb09abb7fb8b7c5046f679b0 Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Thu, 19 May 2022 05:57:00 +0200 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> --- docs/middleware.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/middleware.md b/docs/middleware.md index ca41b0219..817f63662 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -227,10 +227,11 @@ Instead you should keep any state local to the `dispatch` method, or pass it around explicitly, rather than mutating the middleware instance. !!! bug - Currently, the `BaseHTTPMiddleware` has two known issues: + Currently, the `BaseHTTPMiddleware` has some known issues: - It's not possible to use multiple `BaseHTTPMiddleware` based middlewares. - It's not possible to use `BackgroundTasks` with `BaseHTTPMiddleware`. + - Using `BaseHTTPMiddleware` will prevent changes to `contextlib.ContextVar`s from propagating upwards. That is, if you set a value for a `ContextVar` in your endpoint and try to read it from a middleware you will find that the value is not the same value you set in your endpoint (see [this test](https://github.com/encode/starlette/blob/621abc747a6604825190b93467918a0ec6456a24/tests/middleware/test_base.py#L192-L223) for an example of this behavior). ## Using middleware in other frameworks