Skip to content

Commit cb3a4c2

Browse files
authored
Replace BaseHTTPMiddleware with pure ASGI middleware
1 parent bd57964 commit cb3a4c2

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

backend/middleware.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,35 @@
55
from starlette.middleware.base import BaseHTTPMiddleware
66
from starlette.requests import Request
77
from starlette.responses import JSONResponse, Response
8+
from starlette.types import ASGIApp, Scope, Receive, Send
89

910
from backend.constants import DATABASE_URL, DOCS_PASSWORD, MONGO_DATABASE
1011

1112

12-
class DatabaseMiddleware(BaseHTTPMiddleware):
13-
async def dispatch(self, request: Request, call_next: t.Callable) -> Response:
13+
class DatabaseMiddleware:
14+
15+
def __init__(self, app: ASGIApp) -> None:
16+
self._app = app
17+
18+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
1419
client: AsyncIOMotorClient = AsyncIOMotorClient(
1520
DATABASE_URL,
1621
ssl_cert_reqs=ssl.CERT_NONE
1722
)
1823
db = client[MONGO_DATABASE]
19-
request.state.db = db
20-
response = await call_next(request)
21-
return response
24+
scope["state"].db = db
25+
await self._app(scope, send, receive)
26+
2227

28+
class ProtectedDocsMiddleware:
2329

24-
class ProtectedDocsMiddleware(BaseHTTPMiddleware):
25-
async def dispatch(self, request: Request, call_next: t.Callable) -> Response:
30+
def __init__(self, app: ASGIApp) -> None:
31+
self._app = app
32+
33+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
34+
request = Request(scope)
2635
if DOCS_PASSWORD and request.url.path.startswith("/docs"):
2736
if request.cookies.get("docs_password") != DOCS_PASSWORD:
28-
return JSONResponse({"status": "unauthorized"}, status_code=403)
29-
30-
resp = await call_next(request)
31-
return resp
37+
await JSONResponse({"status": "unauthorized"}, status_code=403)(scope, receive, send)
38+
return
39+
await self._app(scope, receive, send)

0 commit comments

Comments
 (0)