Advanced Middleware
Adding ASGI Middleware
Section titled “Adding ASGI Middleware”JustAPI supports any ASGI middleware:
from justapi import JustAPIAppfrom starlette.middleware.httpsredirect import HTTPSRedirectMiddlewarefrom starlette.middleware.trustedhost import TrustedHostMiddleware
app = JustAPIApp()
app.add_middleware(HTTPSRedirectMiddleware)Trusted Host Middleware
Section titled “Trusted Host Middleware”Guard against HTTP host header attacks:
app.add_middleware( TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"],)GZip Compression
Section titled “GZip Compression”from starlette.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=500, compresslevel=9)Custom ASGI Middleware
Section titled “Custom ASGI Middleware”Write your own middleware class:
import timefrom starlette.middleware.base import BaseHTTPMiddleware
class TimingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): start = time.time() response = await call_next(request) duration = time.time() - start response.headers["X-Process-Time"] = str(round(duration, 4)) return response
app.add_middleware(TimingMiddleware)See Also
Section titled “See Also”- Middleware — basic middleware usage
- Behind a Proxy — reverse proxy configuration
- Sub Applications — mounting sub-apps