You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/middleware.md
+35Lines changed: 35 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -686,6 +686,41 @@ to use the `middleware=<List of Middleware instances>` style, as it will:
686
686
* Ensure that everything remains wrapped in a single outermost `ServerErrorMiddleware`.
687
687
* Preserves the top-level `app` instance.
688
688
689
+
## Applying middleware to `Mount`s
690
+
691
+
Middleware can also be added to `Mount`, which allows you to apply middleware to a single route, a group of routes or any mounted ASGI application:
692
+
693
+
```python
694
+
from starlette.applications import Starlette
695
+
from starlette.middleware import Middleware
696
+
from starlette.middleware.gzip import GZipMiddleware
697
+
from starlette.routing import Mount, Route
698
+
699
+
700
+
routes = [
701
+
Mount(
702
+
"/",
703
+
routes=[
704
+
Route(
705
+
"/example",
706
+
endpoint=...,
707
+
)
708
+
],
709
+
middleware=[Middleware(GZipMiddleware)]
710
+
)
711
+
]
712
+
713
+
app = Starlette(routes=routes)
714
+
```
715
+
716
+
Note that middleware used in this way is *not* wrapped in exception handling middleware like the middleware applied to the `Starlette` application is.
717
+
This is often not a problem because it only applies to middleware that inspect or modify the `Response`, and even then you probably don't want to apply this logic to error responses.
718
+
If you do want to apply the middleware logic to error responses only on some routes you have a couple of options:
719
+
720
+
* Add an `ExceptionMiddleware` onto the `Mount`
721
+
* Add a `try/except` block to your middleware and return an error response from there
722
+
* Split up marking and processing into two middlewares, one that gets put on `Mount` which marks the response as needing processing (for example by setting `scope["log-response"] = True`) and another applied to the `Starlette` application that does the heavy lifting.
0 commit comments