MiddlewareStack — Aquilia Documentation
Comprehensive guide and documentation for MiddlewareStack in the Aquilia framework. View API reference, examples, and implementation patterns.
MIDDLEWARE / STACK & COMPOSITION Middleware Stack The MiddlewareStack manages middleware registration, verifies structural contracts at startup, and compiles the execution pipelines. Startup Contract Validation When you register middleware using .middleware() or direct stack.add(), Aquilia performs four rigorous inspection checks using Python's reflection APIs before running the server: 1. Inheritance Check Class instances must inherit from the Middleware base class. Raw functions bypass this check if they are directly callable. 2. Callability Check The registered object must be callable (i.e. possess an active __call__ method or be a routine). 3. Parameter Count Check Signature inspection (via inspect.signature) enforces exactly three parameters: (request, ctx, next_handler). Binds are verified at registration. 4. Async Coroutine Check The entrypoint MUST be a coroutine function (async def). Sync callables trigger a runtime TypeError at boot. Middleware Hooks The Middleware base class (now located in aquilia.middleware.core.base) provides a rich hook-based API for intercepting requests and managing lifespan: async def handle(self, request, ctx, next_handler) The primary hook for wrapping the request. Call await next_handler(request, ctx) to continue the chain. async def before(self, request, ctx) -> Response | None Runs before the request is passed to the next handler. Return a Response to short-circuit. async def after(self, request, ctx, response) -> Response Runs after the request returns from the downstream chain. Allows modifying the outgoing response. async def should_run(self, request, ctx) -> bool Opt-in conditional execution. If returns False, the middleware is skipped for this request. async def setup(self, app) / async def teardown(self, app) Lifespan hooks for initializing or cleaning up resources (e.g. database pools) on application startup and shutdown. Priority Collision Detection When adding middleware via stack.add(), Aquilia will check for priority collisions. If two middlewares share the exact same scope and priority, a warning is emitted. If the app is configured with strict_priorities=True, this will instead raise a MiddlewarePriorityCollisionFault (from aquilia.middleware.stack.errors). Manipulating the Stack from aquilia.middleware.stack.registry import MiddlewareStack from my_middlewares import SecurityMiddleware, LoggingMiddleware, Handler stack = MiddlewareStack() # 1. Register with scopes and priority stack.add(SecurityMiddleware(), scope="global", priority=10, name="security") stack.add(LoggingMiddleware(), scope="global", priority=90, name="logging") # 2. Build normal handler (executes: Security -> Logging -> Handler) handler = stack.build_handler(final_handler=Handler) # 3. Build fast handler (executes: Security -> Handler; skips Logging) # build_fast_handler has been removed in v1.4.0b2 Priority Reference (aquilia.middleware.core.priority.Priority) These are the exact priority numbers AquiliaServer assigns when it wires each built-in middleware — not the fictional numbers you'll find in older docs. Lower number = wraps closer to the outside = runs first on the way in. Priority Constant Value Middleware EXCEPTION 1 ExceptionMiddleware FAULTS 2 FaultMiddleware PROXY_FIX 3 ProxyFixMiddleware HTTPS_REDIRECT 4 HTTPSRedirectMiddleware REQUEST_SCOPE 5 ServerRequestScopeMiddleware VERSIONING 5 VersionMiddleware STATIC 6 StaticMiddleware SECURITY_HEADERS 7 SecurityHeadersMiddleware HSTS 8 HSTSMiddleware CSP 9 CSPMiddleware REQUEST_ID 10 RequestIdMiddleware CORS 11 CORSMiddleware RATE_LIMIT_ANON 12 RateLimitMiddleware INSPECTOR 13 InspectorMiddleware INSPECTOR_TOOLBAR 14 ToolbarInjectionMiddleware AUTH 15 AquilAuthMiddleware RATE_LIMIT_IDENTITY 16 RateLimitMiddleware (Identity) CSRF 20 CSRFMiddleware I18N 24 I18nMiddleware TEMPLATES 25 TemplateMiddleware CACHE 26 CacheMiddleware APPLICATION_DEFAULT 50 Application User Middlewares Source: aquilia.middleware.core.priority.Priority Overview Built-in Middleware )
Go to Homepage