python - 如何访问 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
的变量?symbol
streams
解决方案
使用 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)
推荐阅读
- javascript - 光标 - 动画 javascript
- c# - 如何将 d 的索引返回到其错误消息
- angular - 如何在函数 gleich 中使用变量 rechenoperator2?
- javascript - 如果数组包含重复项,则将两个值合并为一个
- entity-framework-core - 使用 GROUP BY 检索组中的最新行
- google-bigquery - 来自以太坊的 BigQuery 数据中可用的指标
- javascript - 错误时的javascript axios控制台日志响应
- java - 没有可用的“com.milkdairy.dao.userRepository”类型的合格 bean:预计至少有 1 个有资格作为自动装配候选者的 bean
- macros - 从 Enter 确认 Atom 解除绑定更正
- python - 为什么 Python XLSWRITER 单元格公式不能以编程方式工作?