Resource Lifecycle & State

Updated Dec 08, 2025
  • on_connect(req, ws, **params) -> bool | None
  • Accept/close/inspect headers, seed self.state, return False to stop processing after connect.
  • on_disconnect(req, ws, close_code, **params) -> None
  • Clean up resources; runs even if connection negotiation fails after acceptance.
  • self.state
  • Dict-like proxy shared across all resources in the same connection chain.
  • Override via get_child_context() to supply a custom state store (e.g., Redis-backed proxy).

Nested resources

class Parent(WebSocketResource):
    def __init__(self):
        self.state["parent_ready"] = True
        self.add_subroute("child/{item}", Child)

    def get_child_context(self):
        return {"project": "acme"}  # merged into child kwargs


class Child(WebSocketResource):
    def __init__(self, project: str):
        self.project = project

    async def on_connect(self, req, ws, item: str) -> bool:
        self.state["child_item"] = item
        return False
  • Path params flow into each resource; parent-provided context merges with params for the next child.
  • State defaults to a shared proxy unless overridden in get_child_context().