Controller Attributes — Aquilia Documentation
Comprehensive guide and documentation for Controller Attributes in the Aquilia framework. View API reference, examples, and implementation patterns.
Controller Attributes aquilia.controller.attrs — Declarative class-level metadata builder The Attributes class is a fluent, chainable builder used to configure class-level metadata on Controller subclasses. By leveraging Python's descriptor protocol, it guarantees compile-time validation and applies configurations dynamically at class-definition time with zero request-time runtime overhead. Old Style vs. New Style Deprecation Warning Directly overriding class attributes (e.g. prefix = "/users", pipeline = [...]) is now deprecated and scheduled for removal in future releases. All new controller definitions should use the modern Attributes builder assigned to the attr variable. Old Style (Deprecated) Overriding class-level variables directly: New Style (Recommended) Using the chainable Attributes descriptor: Why is the old style deprecated? Deferred Validation: Direct properties are not validated when the class is defined. Any misspelled attribute names or bad types will fail silently or crash later at runtime. Mutable State Leakage: Setting lists (like pipeline or tags) directly exposes them to default mutable value issues where subclasses might share or leak states. Poor Autocomplete Support: IDEs and linters cannot suggest options or provide typings for direct class variables. The fluent builder provides full IDE autocomplete. Design Philosophy & Performance Aquilia prioritizes performance, ensuring that request routing and context setup are as optimized as possible. The Attributes builder achieves this through three key architectural decisions: 1 __slots__ Optimization Using __slots__ eliminates the per-instance dictionary (__dict__). This reduces the memory footprint and speeds up attribute access in the method chain by approximately 40%. 2 __set_name__ Descriptor Protocol Rather than analyzing metadata on every request, the builder implements Python's __set_name__(self, owner, name). This executes exactly once when Python loads the controller class, applying the compiled metadata directly onto the controller type. 3 O(1) Chaining & Zero Allocations Each fluent method call does not clone or instantiate a new builder. Instead, it mutates the existing builder's slot field in O(1) time and returns self, generating zero trash collector allocations beyond list conversions for variadic args. Usage & Examples Assign the builder chain to a class-level variable named attr in any controller subclass. 1. Basic REST Configuration Configuring basic route grouping and OpenAPI tag classifications: Response: return Response.json( )`} /> 2. Advanced Enterprise Configuration Enforcing API versions, pipeline guards, rate limits, timeouts, and structured exception handlers at the class level: Response | None: ctx.state["logger_time"] = ctx.request_id return None async def after(self, ctx: RequestCtx, result: Response) -> Response: # Custom log post-processing return result class BillingController(Controller): attr = ( Attributes() .prefix("/api/billing") .tags("Finance", "Billing") .version(["v1", "v2"]) .instantiation_mode("singleton") .pipeline(JWTGuard) # Run auth guard for all routes .throttle(Throttle(limit=60, window=60)) # Rate limit: 60 req/min .interceptors(TransactionLogger()) # Attach request interceptor .exception_filters(DatabaseExceptionFilter()) # Catch DB exceptions .timeout(10.0) # Terminate route if execution > 10s .max_body_size(1024 * 1024) # Cap request payloads to 1MB ) @GET("/history") async def billing_history(self, ctx: RequestCtx) -> Response: return Response.json( )`} /> Fluent Builder API Reference The following list describes each chainable method exposed by the Attributes class: .prefix(value: str) -> Attributes Configures the base URL path prefix for all endpoints in the controller. Validation: The value must be a string and start with / or be empty (""). .pipeline(*nodes: Any) -> Attributes Accepts variadic positional arguments of guards, hooks, or middleware. They execute sequentially before the request hits the handler method. Validation: The arguments are collected as an iterable sequence. .tags(*tag_values: str) -> Attributes Specifies the OpenAPI documentation categories. All endpoints within the controller inherit these tags. Validation: Each tag item must be a valid string. .instantiation_mode(mode: Literal["per_request", "singleton"]) -> Attributes Controls the controller's lifecycle scope managed by the DI container. per_request: (Default) Instantiates a new controller instance per HTTP request. Supports request-scoped resources. singleton: Shares a single instance across all requests for the application's entire lifespans. Required for startup/shutdown hooks. .version(v: str | list[str]) -> Attributes Binds the controller endpoints to specific API versions (e.g. "v1"). Validation: Must be a string or a list of strings representing version names. .throttle(t: Throttle) -> Attributes Applies rate-limiting metrics at the class level via a Throttle instance. .interceptors(*items: Interceptor) -> Attributes Registers class-wide Interceptor hooks that intercept controller route processing before and after methods run. .exception_filters(*items: ExceptionFilter) -> Attributes Registers class-wide ExceptionFilter instances to convert raised exceptions to clean JSON payloads. .timeout(seconds: float) -> Attributes Sets the handler timeout in seconds. Requests running longer than this will yield a timeout fault. Validation: Must be a non-negative integer or float (>= 0). .max_body_size(bytes_size: int) -> Attributes Restricts request body payload sizes (in bytes) to prevent Denial of Service (DoS) attacks. Validation: Must be a non-negative integer (>= 0). Compile-Time Validation Aquilia prevents configuration errors from going unnoticed until runtime. The _validate engine is executed immediately during class evaluation (via __set_name__). If any parameters violate validation limits, Aquilia raises a ConfigInvalidFault during application startup. Definition-Time Error Surfacing By throwing during definition time, the server will refuse to start if paths are formatted incorrectly (e.g. prefix without /), or if limits are set below zero. This guarantees that route integrity does not depend on request test cases. Overview RequestCtx )
Go to Homepage