Make method of derived class async

落爺英雄遲暮 提交于 2021-02-10 12:17:43

问题


I have to create and use a class derived from an upstream package (not modifiable) I want/need to add/modify a method in the derived class that should be async because i need to await a websocket send/recv in the method I tried just to add async to the method but i get the message (from the base class method) that my method from derived class RuntimeWarning: coroutine MyCopyProgressHandler.end was never awaited Is there a way to "convert" derived class method to async?


回答1:


When you need to convert sync method to async you have several different options. Second one (run_in_executor) is probably the easiest one.

For example, this is how you can make sync function requests.get to run asynchronously:

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())


来源:https://stackoverflow.com/questions/55470613/make-method-of-derived-class-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!