python - 多个 uri 的请求 (asyncio)
问题描述
如何使用发送多个请求到交换 websocket acyncio
?
交换 websockets 文档
事实上,如果你知道如何通过requests
library usingasyncio
而不是websockets
library 发送多个请求,那也很好。
我想使用asyncio
库异步发送多个请求到多个 websocket(示例中为两个)。一切都对我有用,只有一个请求:
import asyncio
import websockets
from autobahn.asyncio.websocket import WebSocketClientProtocol
from typing import List
async def logging_message(_websocket: WebSocketClientProtocol) -> None:
async for message in _websocket:
data = json.loads(message)['data']
print(data)
async def websockets_connect(_websocket_uris: List) -> None:
async with websockets.connect(_websocket_uris[0]) as websocket: ## !!! HERE I use bad thing: _websocket_uris[0]
await logging_message(websocket)
websocket_uris = [
'wss://stream.binance.com:9443/stream?streams=btcusdt@kline_1m/ethusdt@kline_1m/ethbtc@kline_1m/bnbbtc@kline_1m'
] # The list is only of length 1, everything works
asyncio.get_event_loop().run_until_complete(websockets_connect(websocket_uris))
但是我不能在单个请求中使用这样的代码,因为交换对一个 uri ( _websocket_uris[0]
) 的长度有限制,所以我需要发送多个具有不同 uri 的请求。像这样的东西:
async def websockets_connect(_websocket_uri: str) -> None:
async with websockets.connect(_websocket_uri) as websocket:
await logging_message(websocket)
async def main():
await asyncio.gather(*[
websockets_connect(websocket_uri) for websocket_uri in websocket_uris
])
websocket_uris = [
'wss://stream.binance.com:9443/stream?streams=btcusdt@kline_1m/ethusdt@kline_1m',
'wss://stream.binance.com:9443/stream?streams=/ethbtc@kline_1m/bnbbtc@kline_1m'
] # list of length 2, nothing works
asyncio.get_event_loop().run_until_complete(main())
它不起作用(错误请求):
websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 400
解决方案
这很有趣,呵呵:我在第二个 uri
'wss://stream.binance.com:9443/stream?streams=/ethbtc@kline_1m/bnbbtc@kline_1m'
中有一个错字'wss://stream.binance.com:9443/stream?streams=ethbtc@kline_1m/bnbbtc@kline_1m'
推荐阅读
- php - 删除 laravel 视图文件中值的重复条目
- python - Python请求不更新get的标头
- python - 哪个 requirements.txt 相当于在 pip 上使用`-f url`?
- mapbox - 如何检测地图视图mapbox iOS SDK上的单击
- php - lumen,怎么不能显示同名?
- amazon-web-services - Step Functions 调用部署在 ECS 中的 Fargate 服务的操作/API
- php - CyberPanel 中 WordPress 站点建立数据库连接时出错
- python - Python df.to_sql 导致挂起和暂停
- python - 遍历数据框行并替换特定列中的字符串元素
- apache-spark - zeppelin 无法获取 sparkcontext