Consumers

Core consumer classes for handling WebSocket connections and defining application logic.

Base Consumer

class fast_channels.consumer.AsyncConsumer

Bases: object

Base consumer class. Implements the ASGI application spec, and adds on channel layer management and routing of events to named methods based on their type.

classmethod as_asgi(**initkwargs: Any) Any

Return an ASGI v3 single callable that instantiates a consumer instance per scope. Similar in purpose to Django’s as_view().

Parameters:

**initkwargs – Keyword arguments used to instantiate the consumer instance.

Returns:

An ASGI application protocol wrapper that creates consumer instances.

base_send: Callable[[Mapping[str, Any]], Awaitable[None]]
channel_layer: BaseChannelLayer | None
channel_layer_alias: str | None = None
channel_name: str
channel_receive: Callable[[], Awaitable[Mapping[str, Any]]]
async dispatch(message: Mapping[str, Any]) None

Works out what to do with a message.

Parameters:

message – The channel message to dispatch to appropriate handler.

Raises:

ValueError – If no handler exists for the message type.

scope: MutableMapping[str, Any]
async send(message: Mapping[str, Any]) None

Overrideable/callable-by-subclasses send method.

Parameters:

message – The channel message to send.

HTTP Consumers

class fast_channels.consumer.AsyncHttpConsumer(*args: Any, **kwargs: Any)

Bases: AsyncConsumer

Async HTTP consumer. Provides basic primitives for building asynchronous HTTP endpoints.

async disconnect() None

Overrideable place to run disconnect handling. Do not send anything from here.

async handle(body: bytes) None

Receives the request body as a bytestring. Response may be composed using the self.send* methods; the return value of this method is thrown away.

Parameters:

body – The complete request body as bytes.

Raises:

NotImplementedError – Always raised as subclasses must implement this method.

async http_disconnect(message: HttpDisconnectEvent) None

Let the user do their cleanup and close the consumer.

Parameters:

message – HTTP disconnect event.

async http_request(message: HttpRequestEvent) None

Async entrypoint - concatenates body fragments and hands off control to self.handle when the body has been completely received.

Parameters:

message – HTTP request event containing body fragment.

async send_body(body: bytes, *, more_body: bool = False) None

Sends a response body to the client. The method expects a bytestring.

Set more_body=True if you want to send more body content later. The default behavior closes the response, and further messages on the channel will be ignored.

Parameters:
  • body – Response body as bytes.

  • more_body – Whether more body content will be sent (default: False).

Raises:

AssertionError – If body is not bytes.

async send_headers(*, status: int = 200, headers: list[tuple[bytes, bytes]] | None = None) None

Sets the HTTP response status and headers. Headers may be provided as a list of tuples or as a dictionary.

Note that the ASGI spec requires that the protocol server only starts sending the response to the client after self.send_body has been called the first time.

Parameters:
  • status – HTTP status code (default: 200).

  • headers – Optional list of header tuples (name, value) as bytes.

async send_response(status: int, body: bytes, *, headers: list[tuple[bytes, bytes]] | None = None) None

Sends a response to the client. This is a thin wrapper over self.send_headers and self.send_body, and everything said above applies here as well. This method may only be called once.

Parameters:
  • status – HTTP status code.

  • body – Response body as bytes.

  • headers – Optional list of header tuples (name, value) as bytes.

WebSocket Consumers

class fast_channels.consumer.AsyncWebsocketConsumer(*args: Any, **kwargs: Any)

Bases: AsyncConsumer

Base WebSocket consumer, async version. Provides a general encapsulation for the WebSocket handling model that other applications can build on.

async accept(subprotocol: str | None = None, headers: Iterable[tuple[bytes, bytes]] | None = None) None

Accepts an incoming socket

Parameters:
  • subprotocol – Optional WebSocket subprotocol to use.

  • headers – Optional headers to send with the accept message.

async close(code: int | bool | None = None, reason: str | None = None) None

Closes the WebSocket from the server end

Parameters:
  • code – Close code (defaults to 1000) or boolean for legacy support.

  • reason – Optional reason for closing the connection.

async connect() None

Handle WebSocket connection establishment.

Override this method to customize connection handling. By default, automatically accepts the connection.

async disconnect(code: int) None

Called when a WebSocket connection is closed.

Parameters:

code – The WebSocket close code.

groups: list[str]
async receive(text_data: str | None = None, bytes_data: bytes | None = None) None

Called with a decoded WebSocket frame.

Parameters:
  • text_data – Text data from the WebSocket frame, if any.

  • bytes_data – Binary data from the WebSocket frame, if any.

async send(text_data: str | None = None, bytes_data: bytes | None = None, close: bool = False) None

Sends a reply back down the WebSocket

Parameters:
  • text_data – Text data to send, if any.

  • bytes_data – Binary data to send, if any.

  • close – Whether to close the connection after sending.

Raises:

ValueError – If neither text_data nor bytes_data is provided.

async websocket_connect(message: WebSocketConnectEvent) None

Called when a WebSocket connection is opened.

Parameters:

message – WebSocket connect event containing connection details.

async websocket_disconnect(message: WebSocketDisconnectEvent) None

Called when a WebSocket connection is closed. Base level so you don’t need to call super() all the time.

Parameters:

message – WebSocket disconnect event containing disconnect details.

async websocket_receive(message: WebSocketReceiveEvent) None

Called when a WebSocket frame is received. Decodes it and passes it to receive().

Parameters:

message – WebSocket receive event containing the frame data.

class fast_channels.consumer.AsyncJsonWebsocketConsumer(*args: Any, **kwargs: Any)

Bases: AsyncWebsocketConsumer

Variant of AsyncWebsocketConsumer that automatically JSON-encodes and decodes messages as they come in and go out. Expects everything to be text; will error on binary data.

async classmethod decode_json(text_data: str) Any

Decode JSON from text data.

Parameters:

text_data – JSON string to decode.

Returns:

The decoded JSON object.

async classmethod encode_json(content: Any) str

Encode content as JSON string.

Parameters:

content – Object to encode as JSON.

Returns:

JSON string representation.

async receive(text_data: str | None = None, bytes_data: bytes | None = None, **kwargs: Any) None

Handle incoming WebSocket frames and decode JSON content.

Parameters:
  • text_data – Text data from the WebSocket frame.

  • bytes_data – Bytes data from the WebSocket frame (not supported).

  • **kwargs – Additional keyword arguments.

Raises:

ValueError – If no text data is provided or bytes data is received.

async receive_json(content: Any, **kwargs: Any) None

Called with decoded JSON content.

Parameters:
  • content – The decoded JSON content.

  • **kwargs – Additional keyword arguments.

async send_json(content: Any, close: bool = False) None

Encode the given content as JSON and send it to the client.

Parameters:
  • content – The content to encode and send as JSON.

  • close – Whether to close the connection after sending.