|
2 | 2 |
|
3 | 3 | import re
|
4 | 4 | from http.client import HTTP_PORT, HTTPS_PORT
|
5 |
| -from typing import Callable, List, Tuple |
| 5 | +from typing import List, Tuple |
6 | 6 |
|
7 |
| -from fastapi import APIRouter, FastAPI |
8 |
| -from starlette.middleware.base import BaseHTTPMiddleware |
9 |
| -from starlette.requests import Request |
10 |
| -from starlette.routing import Match |
11 | 7 | from starlette.types import ASGIApp, Receive, Scope, Send
|
12 | 8 |
|
13 | 9 |
|
14 |
| -def router_middleware(app: FastAPI, router: APIRouter): |
15 |
| - """Add middleware to a specific router, assumes no router prefix.""" |
16 |
| - |
17 |
| - def deco(func: Callable) -> Callable: |
18 |
| - async def _middleware(request: Request, call_next): |
19 |
| - # Check if scopes match |
20 |
| - matches = any( |
21 |
| - [ |
22 |
| - route.matches(request.scope)[0] == Match.FULL |
23 |
| - for route in router.routes |
24 |
| - ] |
25 |
| - ) |
26 |
| - if matches: # Run the middleware if they do |
27 |
| - return await func(request, call_next) |
28 |
| - else: # Otherwise skip the middleware |
29 |
| - return await call_next(request) |
30 |
| - |
31 |
| - app.add_middleware(BaseHTTPMiddleware, dispatch=_middleware) |
32 |
| - return func |
33 |
| - |
34 |
| - return deco |
35 |
| - |
36 |
| - |
37 | 10 | class ProxyHeaderMiddleware:
|
38 | 11 | """
|
39 | 12 | Account for forwarding headers when deriving base URL.
|
|
0 commit comments