python-asyncio TypeError: object dict can't be used in 'await' expression

后端 未结 3 1663
谎友^
谎友^ 2020-12-29 04:44

I am using a third party module to retrieve data from an API. I simply would like to asynchronously await the module to return the data which occasionally takes several seco

3条回答
  •  孤城傲影
    2020-12-29 05:17

    As thirdPartyAPIWrapper.data() is a normal sync function you should call it in another thread.

    There is a helper function for that in a asgiref library.
    Assume we've got a blocking function with an argument:

    import asyncio
    import time
    
    from asgiref.sync import sync_to_async
    
    
    def blocking_function(seconds: int) -> str:
        time.sleep(seconds)
        return f"Finished in {seconds} seconds"
    
    async def main():
        seconds_to_sleep = 5
        function_message = await sync_to_async(blocking_function)(seconds_to_sleep)
        print(function_message)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
    

    There is also an async_to_sync helper function in that library.

提交回复
热议问题