派生类的Make方法异步

时间:2019-04-02 08:52:35

标签: python-3.x python-asyncio

我必须创建和使用从上游包派生的类(不可修改) 我想/需要在派生类中添加/修改应该是异步的方法,因为我需要等待方法中的websocket发送/接收 我只是尝试向该方法添加异步,但是我从派生类RuntimeWarning: coroutine MyCopyProgressHandler.end was never awaited收到消息(从基类方法) 有没有一种方法可以将派生的类方法“转换”为异步方法?

1 个答案:

答案 0 :(得分:1)

当您需要将同步方法转换为异步方法时,您将拥有several different options。第二个(run_in_executor)可能是最简单的一个。

例如,这是使同步功能requests.get异步运行的方法:

import asyncio
import requests
from concurrent.futures import ThreadPoolExecutor


executor = ThreadPoolExecutor(10)


async def get(url):
    loop = asyncio.get_running_loop()
    response = await loop.run_in_executor(
        executor, 
        requests.get, 
        url
    )
    return response.text


async def main():
    res = await get('http://httpbin.org/get')
    print(res)


asyncio.run(main())