Can or How to use Python asyncio on Google Cloud Functions?

Question:

Is it possible to use Python’s asyncio on Google Cloud Functions?

async def handle_someting():
    # do something
    some = await aiofunc()

# Do I need the code below?
loop = asyncio.get_event_loop()
loop.run_until_complete(handle_someting())
loop.close()
Asked By: Sagnol

||

Answers:

Sure, you just need to run the async functions from your main deployed function (here, you would deploy the test function):

import asyncio

async def foo():
    return 'Asynchronicity!'

async def bar():
    return await foo()

def test(request):
    return asyncio.run(bar())
Answered By: Dustin Ingram

Yes, it’s possible to run async code in Google Cloud Functions.

To achieve that, you need to manually create new event loop and then call it from entry-point method that receives the request. Code example:

import asyncio

eventLoop = asyncio.new_event_loop()
asyncio.set_event_loop(eventLoop)

async def processJson(rawRequest: dict) -> None:
    """Processes received request JSON."""
    print(rawRequest)
    <some logic here>


async def wrapper(request):
    """Async wrapper."""

    if request.method != "POST":
        return "not POST"

    rawRequest: dict = request.get_json(silent=True)

    await processJson(rawRequest)

    return "OK"

def entryPoint(request) -> str:
    """Entry-point that is triggered by cloud function URL."""

    return eventLoop.run_until_complete(wrapper(request))

Deploying this code and doing GET request to your google cloud function will return you "not POST".
Sending it as POST request will trigger any logics you’ve wrote inside processJson() and return "OK".

Answered By: An Se