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

后端 未结 4 597
南笙
南笙 2021-01-30 08:28

I\'m using aiohttp to build an API server that sends TCP requests off to a seperate server. The module that sends the TCP requests is synchronous and a black box for my purposes

4条回答
  •  没有蜡笔的小新
    2021-01-30 09:26

    Eventually I found an answer in this thread. The method I was looking for is run_in_executor. This allows a synchronous function to be run asynchronously without blocking an event loop.

    In the sleep example I posted above, it might look like this:

    import asyncio
    from time import sleep
    
    async def sleep_async(loop, delay):
        # None uses the default executor (ThreadPoolExecutor)
        await loop.run_in_executor(None, sleep, delay)
        return 'I slept asynchronously'
    

    Also see the following answer -> How do we call a normal function where a coroutine is expected?

提交回复
热议问题