Built-in Middleware — Aquilia Documentation
Comprehensive guide and documentation for Built-in Middleware in the Aquilia framework. View API reference, examples, and implementation patterns.
MIDDLEWARE / BUILT-IN Built-in Middleware Aquilia packages four highly optimized built-in middlewares covering request identification, error content negotiation, timeouts, and asynchronous compression. RequestIdMiddleware Assigns a unique request ID. To maximize performance, it scans raw ASGI scope headers directly as raw byte arrays, avoiding costly high-level header parsing. Rather than calling slower uuid.uuid4(), it uses os.urandom(16).hex(), executing roughly 4× faster. The ID is stored in both request.state["request_id"] and ctx.request_id, and returned in the response header. from aquilia.middleware import RequestIdMiddleware # Configure on server server.middleware(RequestIdMiddleware(header_name="X-Request-ID")) # Handler usage async def my_handler(request, ctx): request_id = ctx.request_id # accessible directly # or request.state["request_id"] ExceptionMiddleware Intercepts uncaught exceptions and converts them into structured error responses. It uses content negotiation via the client's Accept header: HTML Clients (Accept: text/html) Renders a beautiful debug page in local development (debug=True) detailing local variables, stack frames, and active code slices. Renders a clean production error page when disabled. API Clients (JSON) Enforces security policy ARCH-04: Never leaks stack tracebacks or raw exception strings in JSON bodies. Instead, serialized output follows a strict standard format: ] } } Domain to HTTP Status Code Mapping: SECURITY / auth → 401 / 403 ROUTING / MODEL (Not Found) → 404 VALIDATION (BP200) → 400 IO / STORAGE / CACHE → 502 / 503 SYSTEM / FLOW → 500 TimeoutMiddleware Wraps downstream execution inside a strict time constraint. If execution exceeds the limit, it raises a RequestTimeoutFault which bubbles through the exception middleware, returning a structured 504 Gateway Timeout. from aquilia.middleware import TimeoutMiddleware server.middleware(TimeoutMiddleware(timeout_seconds=15.0)) CompressionMiddleware Compresses response payloads. Because CPU-bound Gzip compression can block Python's single-threaded event loop, this middleware offloads the actual compression call to a background thread pool via asyncio.to_thread. - Skips active streaming and chunked responses. - Emits HTTP header Vary: Accept-Encoding to safeguard cache proxies. from aquilia.middleware import CompressionMiddleware server.middleware(CompressionMiddleware(minimum_size=1024)) # Compress responses >= 1KB MiddlewareStack Static Files )
Go to Homepage