返回JSON数组Websockets数据馈送

时间:2018-04-05 22:19:10

标签: python python-3.x websocket

我正在尝试获取正在返回的消息,显然它更像是

<function on_message at 0x00000138D6488F28>

如何让它返回json消息而不是上面的消息?

以下是我的代码。

from websocket import WebSocketApp
from json import dumps, loads
from pprint import pprint

URL = "wss://ws-feed.gdax.com"

def on_message(_, message):
    pprint(loads(message))
    print

def on_open(socket):
    params = {
        "type": "subscribe",
        "channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]
    }
    socket.send(dumps(params))

def main():
    ws = WebSocketApp(URL, on_open=on_open, on_message=on_message)
    while True:
        print(ws.on_message)
        time.sleep(1)

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

def on_message(_, message): # this will be called everytime a message is recieved
    pprint(loads(message))
    print

def main():
    ws = WebSocketApp(URL, on_open=on_open, on_message=on_message)
    ws.run_forever() # this will run the ws main_loop that is builtin and listen for the connection and messages

ps这是一项很酷的服务......我总是喜欢寻找新的公共服务

答案 1 :(得分:1)

好吧,它打印function,因为你确实打印出了函数,而不是调用它。但是这个函数并不是由你调用的,但当你实际收到一条消息并且有人连接到你的套接字时,WebSocketApp会调用它。

但是,如果您真的想要打电话,可以通过将print(ws.on_message)更改为ws.on_message(None, 'your message')来实现。