API¶
WebSocket Endpoint¶
The WebSocket Endpoint
- class socketsundso.endpoints.HandlingEndpointMeta(*args: str, **kwargs: Any)¶
Bases:
typeMetaclass for
WebSocketHandlingEndpointAll this does is put every
Handlerinside ofWebSocketHandlingEndpointintoWebSocketHandlingEndpoint.handlers
- class socketsundso.endpoints.WebSocketHandlingEndpoint(scope: MutableMapping[str, Any], receive: Callable[[], Awaitable[MutableMapping[str, Any]]], send: Callable[[MutableMapping[str, Any]], Awaitable[None]])¶
Bases:
objectThe WebSocketHandlingEndpoint is a class for the creation of a simple JSON-based WebSocket API
This class is based on
starlette.endpoints.WebSocketEndpointIncoming messages have to be based onWebSocketEventMessagedispatch()will call handlers based on the incomingWebSocketEventMessage.type. If the handler returns something it will be send to the client.To register a method as handler decorate it with
socketsundso.handler.on_event()oron_event().You can override
on_connect()andon_disconnect()to change what happens when clients connect or disconnect.- async dispatch() None¶
Handles the lifecycle of a
WebSocketconnection and callson_connect(), theon_receive()andon_disconnect()repectively.Note
This method will be called by
starlette. You shouldn’t need to think about it.If the client sends a JSON payload that can’t be validated by
WebSocketEventMessageoron_receive()raises anValidationErrororjson.decoder.JSONDecodeErrorthe errors will be send to the client viasend_exception().
- handlers: Dict[str, socketsundso.handler.Handler] = {}¶
- async on_connect() None¶
Override to handle an incoming websocket connection
Note
Don’t forget to call
self.websocket.accept()to accept the connection.
- async on_disconnect(close_code: int) None¶
Override to handle a disconnecting websocket
- classmethod on_event(*args: Any, **kwargs: Any) Callable¶
See also
Same arguments as
socketsundso.handler.on_event().
- async on_receive(message: socketsundso.models.WebSocketEventMessage) None¶
Called by
dispatch()whenever a message arrives.Calls the
Handler.handle()for the event and callssend_json()with the response.
- async send_exception(exc: Exception) None¶
Formats the
excand sends it to the client (viasend_json())Override if you don’t wnat to send any Exceptions to the client or want to format them differently.
- async send_json(response: Any) None¶
Calls
fastapi.encoders.jsonable_encoder()and passes result tostarlette.websockets.WebSocket.send_json().Override to handle outgoing messages differently. For example you could handle handler response differently based on their type.
- websocket¶
WebSocketinstance
Handler¶
Handler and related methods
- class socketsundso.handler.Handler(event: str, method: Callable, response_model: Optional[Type[pydantic.main.BaseModel]] = None)¶
Bases:
objectClass representation of a handler. It holds information about the handler, e.g.
model(based onpydantic.BaseModel),event, etc- Parameters
event (str) – name of the event this handler is for
method (Callable) – method this handler will call
response_model (pydantic.BaseModel) –
handle()will parse the return value ofmethodinto this model. If no model is given a default response model will be created.
- async handle(msg: socketsundso.models.WebSocketEventMessage) pydantic.main.BaseModel | None¶
Will be called by
WebSocketHandlingEndpoint.on_receive()- Parameters
msg (WebSocketEventMessage) – will be validated against
model- Returns
response_model- Return type
- model¶
Based on
WebSocketEventMessagewith fields for the parameters ofmethod. Will be used for input validation.
- socketsundso.handler.on_event(event: Callable) Callable¶
- socketsundso.handler.on_event(event: str | None = None, response_model: Optional[Type[pydantic.main.BaseModel]] = None) Callable
Turns a
typing.Callableinto aHandlerDecorator to be used in subclasses ofWebSocketHandlingEndpointDeclares a method as handler foreventTakes the same parameters as
HandlerTechnical Note: Since it’s impossible to get the class of an unbound function this decorator just sets some attributes on the function. The registration as handler happens in
HandlingEndpointMeta__new__()
Models¶
pydantic models used in this project
- class socketsundso.models.WebSocketEventMessage(*, type: str, **extra_data: Any)¶
Bases:
pydantic.main.BaseModelBaseModel of an incoming WebSocketEvent
All other arguments of a handler will be added dynamically.
Note
When validating incoming messages, type will be replaced with a
typing.Literalfor all registered event types. So basically this whole class is kind of pointless.- type: str¶