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

后端 未结 4 559
南笙
南笙 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:19

    You can use a decorator to wrap the sync version to an async version.

    import time
    from functools import wraps, partial
    
    
    def wrap(func):
        @wraps(func)
        async def run(*args, loop=None, executor=None, **kwargs):
            if loop is None:
                loop = asyncio.get_event_loop()
            pfunc = partial(func, *args, **kwargs)
            return await loop.run_in_executor(executor, pfunc)
        return run
    
    @wrap
    def sleep_async(delay):
        time.sleep(delay)
        return 'I slept asynchronously'
    

    or use the aioify library

    % pip install aioify
    

    then

    @aioify
    def sleep_async(delay):
        pass
    

提交回复
热议问题