2017-08-12 94 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開發更簡單,而不是線程和多處理。