python-trio / trio-websocket

WebSocket client and server implementation for Python Trio
MIT License
70 stars 25 forks source link

Support JSON/`dict` payloads for sending and receiving. #170

Open i0bs opened 1 year ago

i0bs commented 1 year ago

Right now, a developer must manually serialise and deserialise packets from or to a serialised JSON str of s. This leads towards writing unnecessary boilerplate such as this. I would very much appreciate the additional layer of abstraction being requested here if I could simply have send_message() taken dict as an acceptable type for its needed argument, and a way to specify receive_message(content_type=dict).

Instead, I have to resort to these utility methods. Courtesy of the retux repository.

    async def _send(self, payload: _GatewayPayload):
        """
        Sends a payload to the Gateway.
        Parameters
        ----------
        payload : `_GatewayPayload`
            The payload to send.
        """

        try:
            # Please note that asdict() is an attrs-specific method. dumps() is from the json dep.
            json = dumps(asdict(payload))
            resp = await self._conn.send_message(json)  # noqa
        except ConnectionClosed:
            logger.warning("The connection to Discord's Gateway has closed.")
            await self._conn.aclose()
            await self.reconnect()

    async def _receive(self) -> _GatewayPayload:
        """
        Receives the next incoming payload from the Gateway.
        Returns
        -------
        `_GatewayPayload`
            A class of the payload data.
        """

        try:
            resp = await self._conn.get_message()
            json = loads(resp)
            # structure_attrs_fromdict() is from the cattrs dep but
            # essentially acts as _GatewayPayload(**json)
            return structure_attrs_fromdict(json, _GatewayPayload)
        except ConnectionClosed:
            logger.warning("The connection to Discord's Gateway has closed.")
            self._closed = True
            await self.reconnect()