aiohttp和asyncio如何以并行方式从http请求和websocket获取响应?

时间:2019-01-18 22:36:23

标签: python-3.x websocket python-asyncio aiohttp

我尝试同时从两个端点接收数据。但是,如果websocket停止发送消息,我将不会收到来自"https://www.blabla.com"的请求中的数据。解决此问题的最佳方法是什么?

import asyncio
import aiohttp

URL = 'wss://www.some_web_socket.io'

async def get_some_data(session):
    url = "https://www.blabla.com"

    async with session.get(url) as response:
        data = await response.text()
    return data

async def ws_handler(url):
    async with aiohttp.ClientSession() as session:
        async with session.ws_connect(url) as ws:
            msg = await ws.receive()

            while True:
                some_data_from_get_request = await get_some_data(session)
                msg_from_websocket = await ws.receive()

                if msg.type == aiohttp.WSMsgType.TEXT:
                    print(stream_data)

                print(some_data_from_get_request)

def _main():
    asyncio.run(ws_handler(URL))


if __name__ == "__main__":
    _main()

1 个答案:

答案 0 :(得分:0)

此代码序列化HTTP和Websocket通信的返回值:

while True:
    some_data_from_get_request = await get_some_data(session)
    msg_from_websocket = await ws.receive()

要能够检测到返回的两个协程中的任何一个,可以使用asyncio.wait(..., return_when=asyncio.FIRST_COMPLETED)

http_fut = asyncio.ensure_future(get_some_data(session))
ws_fut = asyncio.ensure_future(ws.receive())
pending = {http_fut, ws_fut}
while pending:
    _done, pending = asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
    if http_fut.done():
        some_data_from_get_request = http_fut.result()
        ...
    if ws_fut.done():
        msg_from_websocket = ws_fut.result()
        ...
相关问题