Python websockets, subscribe to multiple channels

断了今生、忘了曾经 提交于 2020-01-13 07:03:14

问题


I am trying to connect to multiple channels concurrently and receive messages from a push API through the python websocket library.

Considering the following code below, how would you connect to multiple channels? this code was obtained and slightly modified from here: https://pypi.python.org/pypi/websocket-client

What confuses me is the second last line: ws.on_open = on_open. on_open is defined as a function above and takes 1 argument but no argument is passed when calling the function, I don't recall encountering this before in python code, so I'm unsure what is really going on in this line.

How can I modify this code so that I can pass a variable that contains a string to the function on_open so that I can specify the name of the Chanel that I want to subscribe to? My main goal is to be able to use the multiprocessing library to pass multiple channels to subscribe to concurrently.

Would I accomplish this by creating multiple ws objects or, one ws object and calling on_open multiple times with different channels as arguments?

import websocket
import thread
import time
import json

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):   
        ws.send(json.dumps({'channel':'channel1'}))  
        while True:
            time.sleep(1)
        ws.close()
        print("thread terminating...")

    thread.start_new_thread(run, ())

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://random.example.com",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

回答1:


Use partial to pass in additional arguments

from functools import partial

def on_open(ws, channel_name):
    """
    Notice the channel_name parameter
    """

# create a new function with the predefined variable
chan1 = partial(on_open, channel_name='channel 1')
# set the new function as the on_open callback
ws1.on_open = chan1

# do the same for the rest
chan2 = partial(on_open, channel_name='channel 2')
ws2.on_open = chan2

As a side note, consider using Tornado or Crossbar.io (aka autobahn). Those are proper asynchronous frameworks and make websocket development simpler as opposed to threads and multiprocessing.



来源:https://stackoverflow.com/questions/45645865/python-websockets-subscribe-to-multiple-channels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!