首页 > 解决方案 > 如何访问 Python 中 websocket 返回的数据?

问题描述

这个问题仍然引起我的注意。我对其进行了一些编辑,以吸引更多的问题解决者;)

我目前正在尝试建立一个 websocket 连接以从第三方获取数据。连接已建立并运行良好。

但是,我最终无法访问和使用返回的数据......我该怎么做?

我的代码:

# Websocket Endpoint
socket = 'wss://data.alpaca.markets/stream'

# Websocket authentication dictionary
socket_login_message = {
    "action": "authenticate",
    "data": {
        "key_id": key,
        "secret_key": secret_key
    }
}

# Open Connection
ws = create_connection("wss://data.alpaca.markets/stream")

# Convert dictionary to str -> bytes object to transfer it via websocket
sck_login_credentials = json.dumps(socket_login_message).encode('utf-8')

# Send the credentials over the socket
ws.send(sck_login_credentials)

# Check if connected
result = ws.recv()
print(result)

# Define Stocks to listen
listen_stocks = {
    "action": "listen",
    "data": {
        "streams": ["Q.AAPl", "Q.CMRE", "Q.PLOW"]
    }
}

# Convert dictionary to str -> bytes object to transfer it via websocket
sck_listen_quotes = json.dumps(listen_stocks).encode('utf-8')

# Initialize Listen Process
ws.send(sck_listen_quotes)

# grab response
quotes_response = ws.recv()

# Decode bytes object again
response_str = json.loads(quotes_response)

print(type(quotes_response))
# Prints <class 'str'>

print(type(response_str))
# Prints <class 'dict'>

print(response_str)
# Prints {'stream': 'listening', 'data': {'streams': ['Q.AAPl', 'Q.CMRE', 'Q.PLOW']}}

# Now how to get the data of each stock in streams dict?!

根据第三方的文档,每个流的传输结构如下:

{
  "ev": "Q",
  "T": "APPL",
  "x": 17,
  "p": 283.35,
  "s": 1,
  "X": 17,
  "P": 283.4,
  "S": 1,
  "c": [
    1
  ],
  "t": 1587407015152775000
}

那么如何将例如分配给每个项目T的变量?symbolstreams

标签: pythonwebsocket

解决方案


使用 json.loads()

# to load the JSON and convert it to a Python dictionary which you can access
response_ = json.loads(str(quotes_response))  # note the str(...), not 
                                              # sure which type this var 
                                              # is but most times str() 
                                              # works

# e.g you want to print out the value of "stream"
print(response_['stream'])   # output: listening

请注意,quotes_response如果您这样做,重要的是它是一个字符串json.loads(quotes_response)


推荐阅读