使派生类异步的方法

问题描述 投票:2回答:1

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

python-3.x python-asyncio
1个回答
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())
© www.soinside.com 2019 - 2024. All rights reserved.