2017-08-12 97 views
0

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

考虑下面的代码,你将如何连接到多个通道?这段代码是从这里获得的,稍作修改: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() 

回答

1

使用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 

通作为一个侧面说明,请考虑使用TornadoCrossbar.io(又名autobahn)。这些都是合适的异步框架,并且使websocket开发更简单,而不是线程和多处理。