首页 > 解决方案 > 多个 uri 的请求 (asyncio)

问题描述

如何使用发送多个请求到交换 websocket acyncio
交换 websockets 文档
事实上,如果你知道如何通过requestslibrary usingasyncio而不是websocketslibrary 发送多个请求,那也很好


我想使用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

标签: pythonasynchronouswebsocketrequestpython-asyncio

解决方案


这很有趣,呵呵:我在第二个 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'


推荐阅读