python - How can I wrap a synchronous function in an async coroutine? -


i'm using aiohttp build api server sends tcp requests off seperate server. module sends tcp requests synchronous , black box purposes. problem these requests blocking entire api. need way wrap module requests in asynchronous coroutine won't block rest of api.

so, using sleep simple example, there way somehow wrap time-consuming synchronous code in non-blocking coroutine, this:

async def sleep_async(delay):     # after calling sleep, loop should released until sleep done     yield sleep(delay)     return 'i slept asynchronously' 

eventually found answer in this thread. method looking run_in_executor. allows synchronous function run asynchronously without blocking event loop.

in sleep example posted above, might this:

import asyncio time import sleep concurrent.futures import processpoolexecutor  async def sleep_async(loop, delay):     # can set executor none if default has been set loop     await loop.run_in_executor(processpoolexecutor(), sleep, delay)     return 'i slept asynchronously' 

Comments