Python websockets,订阅多个频道

Python websockets, subscribe to multiple channels

我正在尝试同时连接到多个频道,并通过 python websocket 库从推送 API 接收消息。

考虑下面的代码,您将如何连接到多个频道?此代码是从此处获取并稍作修改的:https://pypi.python.org/pypi/websocket-client

让我困惑的是倒数第二行:ws.on_open = on_open。 on_open 被定义为上面的函数并接受 1 个参数但在调用函数时没有传递参数,我不记得之前在 python 代码中遇到过这个,所以我不确定到底发生了什么在这条线上。

如何修改这段代码,以便将包含字符串的变量传递给函数 on_open,以便指定我要订阅的 Chanel 的名称?我的主要目标是能够使用多处理库传递多个频道以同时订阅。

我是否可以通过创建多个 ws 对象或一个 ws 对象并使用不同的通道作为参数多次调用 on_open 来实现这一点?

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()

使用partial传递额外的参数

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

作为旁注,请考虑使用 Tornado or Crossbar.io(又名 autobahn)。这些是适当的异步框架,与线程和多处理相比,使 websocket 开发更简单。