State Management (How-to)

Updated Dec 08, 2025

Goal: keep per-connection data mutable yet replaceable.

  • Default: self.state is an in-memory dict shared across nested resources.
  • External store: Provide state via get_child_context() to replace the proxy with your own mapping or adapter.
  • Pattern: Use lightweight objects that implement the MutableMapping protocol so resources remain agnostic to the backing store.
class Parent(WebSocketResource):
    def get_child_context(self):
        return {"state": redis_state_proxy(connection_id=self.scope["id"])}
  • Hooks are a good place to pre-fill state (e.g., authenticated user, transaction IDs).
  • Tests can assert state transitions via WebSocketSimulator or WebSocketTestClient.