Using a websocket client as a class in python

前端 未结 8 1042
名媛妹妹
名媛妹妹 2021-02-04 13:19

I\'m trying access some data using websockets, but I cannot really get around the examples given in the websockets documentation.

I have this code (https://pypi.org/proj

8条回答
  •  爱一瞬间的悲伤
    2021-02-04 13:48

    Package the call inside an anonymous lambda function to achieve a proper call with the correct self:

    class Client:
        def __init__(self, db, symbols):
            self.ws = websocket.WebSocketApp("wss://the.server.com/api",
                        on_message = lambda ws,msg: self.on_message(ws, msg),
                        on_error   = lambda ws,msg: self.on_error(ws, msg),
                        on_close   = lambda ws:     self.on_close(ws),
                        on_open    = lambda ws:     self.on_open(ws))
    
        def on_message(self, ws, message):
                msg = json.loads(message)
                print(msg)
        ...
    

提交回复
热议问题