AWS Lambda用Python启动一个异步进程(不等待返回)



我应该首先说,我对AWS、Lambda一无所知,甚至对Python也知之甚少,所以低级错误的可能性很高。

我正在尝试创建一个系统,其中用户post一个东西,处理程序快速将它们传递回jobID,然后用户可以稍后重新访问以检查进程/获取结果。

基本上:

def long_function(jobID, stuff): //dont know how to define this to be called asychronously
//slow-running code
//stuff the result in dynamoDB
return
def lambda_handler(event, context):
jobID = uuid.uuid4.hex
stuff = event['stuff']
long_function(jobID, stuff) //dont know how to write this call
return jobID //should run before long_function completes

我的理解是,一般的python异步的东西(我也不熟悉)不会工作,我需要做一个特定的Lambda调用。我没有找到一个清晰而简单的方法来做到这一点(特别是与python语法)

你是对的,lambda函数一旦返回,就完成了,这是没有办法的。

可以做的,也正如您所预测的,是从第一个函数(或批处理作业,或对此调用EC2实例)中启动另一个lambda函数。

您将需要boto3(它在所有lambda Python环境中默认存在),并且您将需要为lambda函数提供调用另一个lambda函数所需的IAM权限。

您可以调用原始lambda函数或其他函数。下面的代码假设它正在调用同一个函数。

代码本身相当简单:

import json
import boto3
def long_function(jobID, stuff):
"""Do something that takes a long time."""
...
def lambda_handler(event, context):
# Unpack the event
stuff = event["stuff"]
is_long_func = event.get("is_long_func", False)
# Route to the desired action.
if not is_long_func:
# Create a new job ID
jobID = uuid.uuid4.hex
# This is where the real business happens: invoke this
# same lambda function with a different event.
lam = boto3.client('lambda')
lam.invoke_async(
FunctionName="this-lambda-function-name",
InvokeArgs=json.dumps({
'jobID': jobID,
'stuff': stuff,
'is_long_func': True
}).encode('utf-8')
)
return jobID
else:
# Run the long function.
jobID = event["jobID"]
long_function(jobID, stuff)
return "OK"

如果需要函数的结果,可以将函数的结果保存到s3或类似的地方,并通过对lambda函数的额外调用来检索内容。

单个Lambda调用不可能生成作业ID并返回它,然后继续处理。

您将需要一个Lambda函数生成一个作业ID,异步调用另一个Lambda函数(使用event调用类型,因此它不会等待第二个Lambda函数完成),然后返回作业ID。

相关内容

最新更新