11

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()
Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
Sagnol
  • 131
  • 1
  • 6
  • Without knowing more about which gcloud functionality you want to invoke, it's hard to say. You won't be able to just `await blob.download('file')` for instance, because blob.download is not an asynchronous function. – Chris Ivan Feb 05 '20 at 10:22

1 Answers1

13

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())
Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
  • 2
    @Robino The last function here (`test`) is a Google Cloud Function. This example demonstrates how to use asyncio with a Cloud Function, just like the OP asked... – Dustin Ingram Sep 30 '20 at 17:06
  • 1
    @Robino I'm not sure you understand what a Google Cloud Function is. See https://cloud.google.com/functions – Dustin Ingram Oct 01 '20 at 18:18
  • I'm talking nonsense. Sorry for wasting your time. I shall delete my comments. – Robino Oct 14 '20 at 16:02
  • 1
    Hi @DustinIngram I am facing timeout issue when running the asyncio as you suggested. Can you please look at this questuion? https://stackoverflow.com/questions/66095735/asyncio-not-working-on-google-cloud-functions Thanks in advanced – Mo Huss Feb 08 '21 at 09:02
  • Tertiary question, what happens / what are the downsides of not using async/await when creating python function in Google Cloud Functions? Ie. why do one vs the other? – lampShadesDrifter Dec 09 '22 at 06:27
  • Not a good solution! It works but it wont run on event-loop as in async-native clouds like Azure and Yandex! – Kamyar Apr 19 '23 at 05:19