encode / starlette

The little ASGI framework that shines. 🌟

Home Page:https://www.starlette.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

when is `on_receive` invoked in WebSocketEndpoint?

xdewx opened this issue · comments

commented
class JsonEndpoint(WebSocketEndpoint):
    '''
    @description:完全基于json格式封装协议
    @return {*}
    '''

    encoding = "json"

    async def on_connect(self, websocket: WebSocket):
        await websocket.accept()
        logger.info("connection accepted")

    async def on_receive(self, websocket: WebSocket, data: dict):
        '''
        @description: 对于json来说,这里的data会被上层解析为dict
        @param {*} self
        @param {WebSocket} websocket
        @param {dict} data
        @return {*}
        '''
        logger.e("%s:%s", data, type(data))
        # TODO:为什么这里得到的data不是dict而是str
        if isinstance(data, str):
            data = json.loads(data)
        data = JsonRequest.parse_obj(data)

As code above:

  1. entend WebSocketEndpoint
  2. override on_receive method
  3. set encoding='json'
    then why typeof param data in on_receive is str not dict? It is very strange! it seems that self.decode didnot work.