简体   繁体   English

编写用于 AWS Lambda 的异步代码的正确方法是什么?

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

I wrote the following code:我写了以下代码:


import asyncio

loop = 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))

I was trying to accomplish the following but faster.我试图完成以下但速度更快。


def lambda_handler(event, context):
    # TODO implement
    return {'msg':'Hello World'}

What was the correct way to write this in an AWS Lambda environment?在 AWS Lambda 环境中编写此代码的正确方法是什么?

Works for me... You need to choose Runtime "Python 3.6" or "Python 3.7".对我有用...您需要选择运行时“Python 3.6”或“Python 3.7”。

import asyncio

loop = 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))

在此处输入图像描述

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:对于 Python 3.7+,您可以使用asyncio.run()来执行协程:

import asyncio

# The AWS Lambda handler
def 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以下是如何在 AWS Lambda 上使用 asyncio、aiohttp 和 aiobotocore 开发、测试和部署异步 Python 函数的完整示例: https ://github.com/geeogi/async-python-lambda-template

Need to install aioboto3 locally as a part of deployment zip package `需要在本地安装 aioboto3 作为部署 zip 包的一部分`

import asyncio
import aioboto3



async def list_s3_objs (bucket):
    async with aioboto3.client("s3") as s3_client:
        objs = await s3_client.list_objects(Bucket=bucket)
    return objs['Contents']

def lambda_handler(event, context):
    loop = asyncio.get_event_loop()
    loop.run_until_complete(list_s3_objs('bucket_name'))

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM