ORIONIS API REFERENCE

THE ORIONIS API

Build with clarity.

Explore the building blocks of an async-first Python framework. Every module, class, and method — connected, searchable, and ready to build with.

class documentation

Serve concurrent requests within one worker event loop.

Async Method __asgiResponse Send ASGI HTTP response through transport adapter.
Async Method __bodyLengthResponse Reject invalid framing and declared oversized bodies before reading.
Async Method __callFallback Invoke the registered fallback handler and return its response.
Async Method __callHandler Dispatch the route handler and validate direct schema results.
Async Method __callWebSocketHandler Invoke a preloaded connection handler through the scoped container.
Async Method __closeWebSocket Close a connection while retaining the failure already escaping its owner.
Method __defaultMiddleware Initialize default HTTP middleware stack.
Async Method __exceptionResponse Apply endpoint policies and application handling to an ordinary error.
Async Method __globalMiddleware Execute global middleware and serve packaged default-page assets.
Async Method __handleException Translate a caught exception into an HTTP response.
Async Method __handleWebSocket Dispatch a bounded connection inside a dedicated lifetime scope.
Method __init__ Initialize the HTTP kernel with application and failure handler.
Async Method __isExpectedFailure Classify an error while observing failures of a custom classifier.
Async Method __preloadEndpointPolicy Bind one validated policy instance to a static HTTP endpoint.
Async Method __preloadHandlers Import route handlers and prepare their dependency metadata at boot time.
Async Method __preloadMiddleware Pre-build middleware instances for all routes at boot time.
Async Method __processRequest Build the HTTP response for this request.
Async Method __processWebSocket Validate a handshake and run its connection middleware and handler.
Async Method __requestLayer Execute route-level middleware for the resolved route.
Async Method __routeLayer Establish the web or API context before running route middleware.
Method __routeResolve Initialize route resolver with loaded routes.
Async Method __rsgiResponse Send an RSGI HTTP response through the transport adapter.
Async Method __runWebSocket Run an admitted connection and observe errors before transport cleanup.
Async Method __shutdownWebSockets Cancel connection lifetimes within the existing shutdown lifecycle.
Method __websocketOriginAllowed Check browser origins before allowing an application handshake.
Async Method __webTerminal Run the route pipeline and translate validation failures for the web.
Async Method boot Boot the HTTP kernel by initializing all core components.
Method disconnectPaths Expose compiled endpoint opt-ins to the application transport wrapper.
Async Method handleASGI Handle an incoming ASGI HTTP request end-to-end.
Async Method handleRSGI Handle an incoming RSGI HTTP request end-to-end.
Class Variable __slots__ Declare the instance attribute slots reserved by this class.
Instance Variable __api_middleware API identity resolution uses Bearer credentials without starting a session.
Instance Variable __app Application instance providing configuration and DI container.
Instance Variable __asgi_adapter Adapter translating ASGI request events into framework operations.
Instance Variable __body_limits Body limits produced by HTTPBodyLimits.
Instance Variable __boot Boot flag used by KernelHTTP.
Instance Variable __catch Failure handler used to format unhandled exceptions.
Instance Variable __cls_dispatch Cls dispatch supplied through cls_dispatch.
Instance Variable __cors Cors produced by CORSMiddleware.
Instance Variable __default_responses Build the default response factory for common HTTP error responses.
Instance Variable __endpoint_policies Compiled policies associated with each dispatched endpoint.
Instance Variable __fallback Handler or route selected when no ordinary route matches.
Instance Variable __fn_dispatch Fn dispatch supplied through fn_dispatch.
Instance Variable __health_path Health path produced by self.__app.routeHealthCheck.rstrip.
Instance Variable __hub_dispatch Hub dispatch supplied through hub_dispatch.
Instance Variable __middleware_cache Associate each route middleware stack with its instances.
Instance Variable __printer_enabled Record whether requests should be timed and logged.
Instance Variable __proxies Proxies produced by ProxiesMiddleware.
Instance Variable __rate_limit Rate limit produced by RateLimitMiddleware.
Instance Variable __rate_limit_enabled Record whether rate limiting is active.
Instance Variable __request_printer Request logger; only active when the application runs in debug mode.
Instance Variable __request_slots Request slots obtained from self.__body_limits.max_concurrent_requests.
Instance Variable __routes Build the resolver with compiled routes and a fixed hot-cache budget.
Instance Variable __rsgi_adapter Protocol-level response adapters for RSGI and ASGI transports.
Instance Variable __security Security produced by SecurityMiddleware.
Instance Variable __under_maintenance Value supplied for under_maintenance.
Instance Variable __view_dispatch View dispatch supplied through view_dispatch.
Instance Variable __web_middleware Resolve web identities only after session restoration and CSRF checks.
Instance Variable __websocket_config Websocket config produced by HTTPWebSocket.
Instance Variable __websocket_slots Synchronization primitive controlling access to websocket slots.
Instance Variable __websocket_tasks Websocket tasks produced by set.
async def __asgiResponse(self, adapter: TransportAdapter, response: Response, receive: object, send: object, policy: IHttpEndpointPolicy | None = None): (source)

Send ASGI HTTP response through transport adapter.

Apply CORS post-processing headers, log request details, and send the response back to the client via ASGI protocol adapter.

Parameters
adapter:orionis.http.adapters.request.contracts.transport.TransportAdapterTransport adapter encapsulating the HTTP request.
response:orionis.http.ResponseHTTP response object to send to client.
receive:objectASGI receive callable for reading request body.
send:objectASGI send callable for sending response.
policy:orionis.http.contracts.endpoint_policy.IHttpEndpointPolicy | NoneValue supplied for policy.
Returns
NoneSend ASGI HTTP response through transport adapter.
async def __bodyLengthResponse(self, adapter: TransportAdapter) -> Response | None: (source)

Reject invalid framing and declared oversized bodies before reading.

Parameters
adapter:orionis.http.adapters.request.contracts.transport.TransportAdapterIncoming transport metadata.
Returns
orionis.http.Response | NoneA 400 or 413 response for rejected framing, otherwise None. Stream byte counting remains authoritative when length is absent or false.
async def __callFallback(self, fallback: tuple) -> Response: (source)

Invoke the registered fallback handler and return its response.

Parameters
fallback:tuplePair of (handler_class_or_callable, method_name_or_function).
Returns
orionis.http.ResponseHTTP response produced by the fallback handler.
Raises
TypeErrorIf the fallback does not return a Response object.
async def __callHandler(self, resolved_route: ResolvedRoute, request: Request) -> Response: (source)

Dispatch the route handler and validate direct schema results.

Reuse boot-time dispatch tables and serialize structured results. Return explicit responses unchanged.

Parameters
resolved_route:orionis.http.routes.entities.resolved_route.ResolvedRouteResolved route descriptor with handler reference and path params.
request:orionis.http.RequestRequest-local parameters, including middleware changes.
Returns
orionis.http.ResponseHandler response or JSON response containing the handler result.
Raises
TypeErrorIf the handler does not return a Response, dict, or msgspec.Struct.
orionis.http.exceptions.response_validation.ResponseValidationExceptionIf a returned Orionis schema violates its output contract.
async def __callWebSocketHandler(self, resolved_route: ResolvedRoute, socket: WebSocket): (source)

Invoke a preloaded connection handler through the scoped container.

Parameters
resolved_route:orionis.http.routes.entities.resolved_route.ResolvedRouteCompiled route with converted parameters.
socket:orionis.http.WebSocketScoped connection injected into application handlers.
Returns
NoneRun the handler for the lifetime of the connection.
Raises
TypeErrorIf the handler returns an HTTP response or another value.
async def __closeWebSocket(self, socket: WebSocket, *, code: int = 1000, primary: BaseException | None = None): (source)

Close a connection while retaining the failure already escaping its owner.

Parameters
socket:WebSocketAccepted connection or pending handshake owned by the HTTP kernel.
code:int, optionalProtocol close status selected by the connection owner.
primary:BaseException | None, optionalFailure escaping this connection, not an unrelated caller exception.
Returns
NoneComplete closure and observe any secondary operational error.
Raises
ExceptionIf closing fails without an existing primary error or cancellation.
def __defaultMiddleware(self, http_config: dict, default_responses: IDefaultResponses, *, under_maintenance: bool = False): (source)

Initialize default HTTP middleware stack.

Configure and instantiate the default middleware chain including proxies, security, CORS, and rate limiting middleware.

Parameters
http_config:dictHTTP configuration dictionary with middleware settings.
default_responses:orionis.http.default.contracts.responses.IDefaultResponsesDefault response handler for middleware rejections.
under_maintenance:boolValue supplied for under_maintenance.
Returns
NoneInitialize default HTTP middleware stack.
async def __exceptionResponse(self, exc: Exception, request: object, policy: IHttpEndpointPolicy | None) -> Response: (source)

Apply endpoint policies and application handling to an ordinary error.

Parameters
exc:ExceptionError to report or translate.
request:objectTyped request or the adapter used before routing.
policy:orionis.http.contracts.endpoint_policy.IHttpEndpointPolicy | NoneOptional endpoint-specific failure policy.
Returns
orionis.http.ResponseResponse produced by ordinary failure handling.
async def __globalMiddleware(self, adapter: TransportAdapter) -> Response | None: (source)

Execute global middleware and serve packaged default-page assets.

Process request through middleware pipeline: proxies detection, security validation, and CORS negotiation. Framework assets remain available during maintenance and after rate-limit rejections.

Parameters
adapter:orionis.http.adapters.request.contracts.transport.TransportAdapterTransport adapter encapsulating the HTTP request.
Returns
orionis.http.Response | NoneHTTP response if middleware rejects request, None if request passes all middleware checks.
async def __handleException(self, exc: Exception, request: object, policy: IHttpEndpointPolicy | None = None) -> Response: (source)

Translate a caught exception into an HTTP response.

Parameters
exc:ExceptionThe exception raised during request processing.
request:objectCurrent request object (may be the raw transport adapter for pre-routing errors).
policy:orionis.http.contracts.endpoint_policy.IHttpEndpointPolicy | NoneValue supplied for policy.
Returns
orionis.http.ResponseAppropriate HTTP response for the given exception type.
async def __handleWebSocket(self, interface: Interface, adapter: TransportAdapter, receive_or_protocol: object, send: object = None): (source)

Dispatch a bounded connection inside a dedicated lifetime scope.

Parameters
interface:orionis.http.enums.InterfaceServer protocol identifier.
adapter:orionis.http.adapters.request.contracts.transport.TransportAdapterHandshake request metadata.
receive_or_protocol:objectASGI receive callback or Granian WebsocketProtocol.
send:object, optionalASGI send callback, omitted for RSGI.
Returns
NoneComplete connection handling and release acquired admission.
def __init__(self, app: IApplication, catch: ICatch): (source)

Initialize the HTTP kernel with application and failure handler.

Parameters
app:orionis.IApplicationApplication instance providing configuration and DI container.
catch:orionis.failure.contracts.ICatchFailure handler used to format unhandled exceptions.
Returns
NoneInitialize the HTTP kernel with application and failure handler.
async def __isExpectedFailure(self, exc: Exception, policy: IHttpEndpointPolicy | None) -> bool: (source)

Classify an error while observing failures of a custom classifier.

Parameters
exc:ExceptionOriginal error whose ownership must be preserved.
policy:orionis.http.contracts.endpoint_policy.IHttpEndpointPolicy | NoneOptional endpoint-specific failure policy.
Returns
boolWhether the original error is expected.
async def __preloadEndpointPolicy(self, controller: type, route: CompiledRoute, policy_instances: dict[type[IHttpEndpointPolicy], IHttpEndpointPolicy]): (source)

Bind one validated policy instance to a static HTTP endpoint.

Parameters
controller:typeController declaring an optional HTTP protocol policy.
route:orionis.http.routes.entities.compiled_route.CompiledRouteCompiled route associated with the controller.
policy_instances:dict[type[IHttpEndpointPolicy], IHttpEndpointPolicy]Policy instances already constructed during this kernel boot.
Returns
NoneThe endpoint uses the shared policy instance for its policy type.
Raises
TypeErrorIf a policy is not a policy class or the route is dynamic.
async def __preloadHandlers(self): (source)

Import route handlers and prepare their dependency metadata at boot time.

Populates two int-keyed dispatch tables using route object identity, eliminating per-request module imports, attribute lookups, and tuple key construction from the handler invocation hot path. View routes are stored in a third table holding only their template name. Ordinary constructor and action plans are prepared without resolving services or creating controller instances. Custom descriptors remain lazy.

Returns
NoneImport route handlers and prepare their dependency metadata at boot time.
async def __preloadMiddleware(self): (source)

Pre-build middleware instances for all routes at boot time.

Iterate every compiled route and eagerly resolve each middleware class through the container. Results are stored keyed by the immutable stack tuple so identical stacks share the same instances.

Returns
NonePre-build middleware instances for all routes at boot time.
async def __processRequest(self, interface: Interface, adapter: TransportAdapter, receive_or_protocol: object, request_context: ScopeManager, policy: IHttpEndpointPolicy | None = None) -> Response: (source)

Build the HTTP response for this request.

Runs global middleware, rate limiting, route resolution, and the handler pipeline. Debug dumps interrupt only this request with an HTML response; ordinary errors are delegated to __handleException.

Parameters
interface:orionis.http.enums.InterfaceTransport interface type used to construct the BodyStream.
adapter:orionis.http.adapters.request.contracts.transport.TransportAdapterProtocol adapter carrying request metadata.
receive_or_protocol:objectASGI receive callable or RSGI HTTPProtocol instance.
request_context:orionis.container.context.manager.ScopeManagerActive DI request scope for per-request bindings.
policy:orionis.http.contracts.endpoint_policy.IHttpEndpointPolicy | NoneValue supplied for policy.
Returns
orionis.http.ResponseThe fully constructed HTTP response.
async def __processWebSocket(self, adapter: TransportAdapter, socket: WebSocket): (source)

Validate a handshake and run its connection middleware and handler.

Parameters
adapter:orionis.http.adapters.request.contracts.transport.TransportAdapterHandshake metadata for global guards and route matching.
socket:orionis.http.WebSocketConnection already bound to the active application scope.
Returns
NoneReject the handshake or await the application connection lifetime.
Raises
TypeErrorIf middleware returns a value instead of None.
async def __requestLayer(self, request: Request, resolved_route: ResolvedRoute) -> Response: (source)

Execute route-level middleware for the resolved route.

Parameters
request:orionis.http.RequestIncoming HTTP request.
resolved_route:orionis.http.routes.entities.resolved_route.ResolvedRouteResolved route with matched handler and path parameters.
Returns
orionis.http.ResponseHTTP response produced by the pipeline or the handler.
async def __routeLayer(self, request: Request, resolved_route: ResolvedRoute) -> Response: (source)

Establish the web or API context before running route middleware.

Web routes restore the session, validate CSRF, and resolve the session identity. API routes resolve only the token identity. Both allow guests; access restrictions belong to the application's route middleware.

Parameters
request:orionis.http.RequestIncoming HTTP request.
resolved_route:orionis.http.routes.entities.resolved_route.ResolvedRouteResolved route metadata.
Returns
orionis.http.ResponseHTTP response produced by the middleware pipeline.
def __routeResolve(self, route_loader: IRouteLoader): (source)

Initialize route resolver with loaded routes.

Build a route resolver instance configured with routes loaded from the provided route loader and cache settings.

Parameters
route_loader:orionis.http.routes.contracts.loader.IRouteLoaderRoute loader instance to discover and load routes.
Returns
NoneInitialize route resolver with loaded routes.
async def __rsgiResponse(self, adapter: RSGITransportAdapter, response: Response, protocol: HTTPProtocol, policy: IHttpEndpointPolicy | None = None): (source)

Send an RSGI HTTP response through the transport adapter.

Apply CORS post-processing headers, log request details, and send the response back to the client via the RSGI protocol adapter.

Parameters
adapter:orionis.http.adapters.request.rsgi.RSGITransportAdapterRSGI transport adapter with HTTP scope and client connection.
response:orionis.http.ResponseHTTP response object to send to client.
protocol:granian.rsgi.HTTPProtocolRSGI HTTP protocol version indicator.
policy:orionis.http.contracts.endpoint_policy.IHttpEndpointPolicy | NoneValue supplied for policy.
Returns
NoneSend an RSGI HTTP response through the transport adapter.
async def __runWebSocket(self, adapter: TransportAdapter, socket: WebSocket, interface: Interface): (source)

Run an admitted connection and observe errors before transport cleanup.

Parameters
adapter:TransportAdapterAdapter used to resolve the connection endpoint.
socket:WebSocketAdmitted socket whose closure this boundary owns.
interface:InterfaceServer protocol attached to failure metadata.
Returns
NoneFinish handling and attempt closure without replacing an escaping error.
async def __shutdownWebSockets(self): (source)

Cancel connection lifetimes within the existing shutdown lifecycle.

Returns
NoneAwait cooperative cleanup for at most five seconds.
def __websocketOriginAllowed(self, adapter: TransportAdapter) -> bool: (source)

Check browser origins before allowing an application handshake.

Parameters
adapter:orionis.http.adapters.request.contracts.transport.TransportAdapterProxy-normalized handshake metadata.
Returns
boolTrue for missing Origin, same origin, or an explicit allowed origin.
async def __webTerminal(self, request: Request, resolved_route: ResolvedRoute) -> Response: (source)

Run the route pipeline and translate validation failures for the web.

Validation errors are caught here, inside the session middleware, so the resulting redirect still gets its flash bag persisted.

Parameters
request:orionis.http.RequestIncoming HTTP request.
resolved_route:orionis.http.routes.entities.resolved_route.ResolvedRouteResolved route metadata.
Returns
orionis.http.ResponseHandler response, or a redirect back carrying the errors.
async def boot(self): (source)

Boot the HTTP kernel by initializing all core components.

Returns
NoneBoot the HTTP kernel by initializing all core components.
def disconnectPaths(self) -> frozenset[str]: (source)

Expose compiled endpoint opt-ins to the application transport wrapper.

Returns
frozenset[str]Result of the operation described above.
async def handleASGI(self, scope: dict, receive: object, send: object): (source)

Handle an incoming ASGI HTTP request end-to-end.

Parameters
scope:dictASGI connection scope dict with request metadata.
receive:objectASGI receive callable for reading request body.
send:objectASGI send callable for writing response messages.
Returns
NoneHandle an incoming ASGI HTTP request end-to-end.
async def handleRSGI(self, scope: Scope, protocol: HTTPProtocol | WebsocketProtocol) -> object | None: (source)

Handle an incoming RSGI HTTP request end-to-end.

Parameters
scope:granian.rsgi.ScopeGranian RSGI scope with connection metadata.
protocol:granian.rsgi.HTTPProtocolRSGI protocol object for writing the response.
Returns
object | NoneResult of sending the RSGI response, or None on error.
__slots__: tuple[str, ...] = (source)

Declare the instance attribute slots reserved by this class.

__api_middleware: tuple = (source)

API identity resolution uses Bearer credentials without starting a session.

Application instance providing configuration and DI container.

__asgi_adapter = (source)

Adapter translating ASGI request events into framework operations.

__body_limits = (source)

Body limits produced by HTTPBodyLimits.

Boot flag used by KernelHTTP.

__catch: ICatch = (source)

Failure handler used to format unhandled exceptions.

__cls_dispatch: dict[int, tuple[type, str]] = (source)

Cls dispatch supplied through cls_dispatch.

Cors produced by CORSMiddleware.

__default_responses: IDefaultResponses = (source)

Build the default response factory for common HTTP error responses.

__endpoint_policies: dict[str, IHttpEndpointPolicy] = (source)

Compiled policies associated with each dispatched endpoint.

__fallback: tuple | None = (source)

Handler or route selected when no ordinary route matches.

__fn_dispatch: dict[int, object] = (source)

Fn dispatch supplied through fn_dispatch.

__health_path = (source)

Health path produced by self.__app.routeHealthCheck.rstrip.

__hub_dispatch = (source)

Hub dispatch supplied through hub_dispatch.

__middleware_cache: dict[tuple, tuple] = (source)

Associate each route middleware stack with its instances.

__printer_enabled: bool = (source)

Record whether requests should be timed and logged.

__proxies = (source)

Proxies produced by ProxiesMiddleware.

__rate_limit = (source)

Rate limit produced by RateLimitMiddleware.

__rate_limit_enabled = (source)

Record whether rate limiting is active.

__request_printer = (source)

Request logger; only active when the application runs in debug mode.

__request_slots = (source)

Request slots obtained from self.__body_limits.max_concurrent_requests.

__routes = (source)

Build the resolver with compiled routes and a fixed hot-cache budget.

__rsgi_adapter = (source)

Protocol-level response adapters for RSGI and ASGI transports.

__security = (source)

Security produced by SecurityMiddleware.

__under_maintenance = (source)

Value supplied for under_maintenance.

__view_dispatch: dict[int, str] = (source)

View dispatch supplied through view_dispatch.

__web_middleware: tuple = (source)

Resolve web identities only after session restoration and CSRF checks.

__websocket_config = (source)

Websocket config produced by HTTPWebSocket.

__websocket_slots = (source)

Synchronization primitive controlling access to websocket slots.

__websocket_tasks: set[asyncio.Task] = (source)

Websocket tasks produced by set.