What is the correct way to write asyncio code for use with AWS Lambda? What is the correct way to write asyncio code for use with AWS Lambda? python-3.x python-3.x

What is the correct way to write asyncio code for use with AWS Lambda?


Works for me... You need to choose Runtime "Python 3.6" or "Python 3.7".

import asyncioloop = asyncio.get_event_loop()async def get_urls(event):    return {'msg':'Hello World'}def lambda_handler(event, context):    return loop.run_until_complete(get_urls(event))

enter image description here


Asynchronous execution does many things at the same time. You're only doing one thing. You can't do one thing faster than the time it takes to do one thing. Asynchronous execution allows you to perform independent tasks that would normally execute one after another(synchronously) at the same time and then return the result of all the tasks. Inherently, you have to be performing more than one operation.


For Python 3.7+ you can use asyncio.run() to execute your coroutines:

import asyncio# The AWS Lambda handlerdef handler(event, context):    asyncio.run(main())async def main():    # Here you can await any awaitable    await asyncio.sleep(1)    await asyncio.gather([coroutine_1, coroutine_2])

Here's a full example of how to develop, test and deploy an asynchronous Python function using asyncio, aiohttp and aiobotocore on AWS Lambda: https://github.com/geeogi/async-python-lambda-template