pythonpython-asyncioaiohttp

How can I call an async function without await?


I have a controller action in aiohttp application.

async def handler_message(request):

    try:
        content = await request.json()
        perform_message(x,y,z)
    except (RuntimeError):
        print("error in perform fb message")
    finally:
        return web.Response(text="Done")

perform_message is async function. Now, when I call action I want that my action return as soon as possible and perform_message put in event loop.

In this way, perform_message isn't executed


Solution

  • One way would be to use create_task function:

    import asyncio
    
    async def handler_message(request):
        ...
        loop = asyncio.get_event_loop()
        loop.create_task(perform_message(x,y,z))
        ...
    

    As per the loop documentation, starting Python 3.10, asyncio.get_event_loop() is deprecated. If you're trying to get a loop instance from a coroutine/callback, you should use asyncio.get_running_loop() instead. This method will not work if called from the main thread, in which case a new loop must be instantiated:

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.create_task(perform_message(x, y, z))
    loop.run_forever()
    

    Furthermore, if the call is only made once throughout your program's runtime and no other loop needs to be is instantiated (unlikely), you may use:

    asyncio.run(perform_message(x, y, z))
    

    This function creates an event loop and terminates it once the coroutine ends, therefore should only be used in the aforementioned scenario.