本文介绍了从python中对AWS lambda的异步调用获取响应结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AWS lambda函数,可以使用以下代码同步调用并返回结果

I have an AWS lambda function which I can call synchronously and get results back alright with below code

response = lambda_client.invoke(
        FunctionName=FUNCTION_NAME,
        InvocationType='RequestResponse',
        LogType='Tail',
        Payload=payload,
        Qualifier=$LATEST
    )

响应有效载荷的类型为< botocore.response.StreamingBody对象,位于0x115fb3160> ,所以我使用下面的代码来提取有效的有效载荷.

The response Payload is of type <botocore.response.StreamingBody object at 0x115fb3160> So I use below code to extract the payload which works fine.

response_body = response['Payload']
response_str = response_body.read().decode('utf-8')
response_dict = eval(response_str)

现在,我需要异步调用我的lambda,因此我可以使用 InvocationType ='Event'

Now, I need to call my lambda asynchronously, so I change the invocation type with InvocationType='Event'

它给了我一个与以前相同类型的有效负载的响应,即 botocore.response.StreamingBody对象,但是我在这一行遇到了错误- response_dict = eval(response_str)

It gives me a response with payload of the same type as before, botocore.response.StreamingBody object but I am getting error with this line - response_dict = eval(response_str)

错误消息显示

    response_dict = eval(response_str)
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

我想念什么?如果响应有效负载与同步调用的类型相同,为什么会出现此解析错误?有什么建议吗?

What am I missing? If the response payload is same type as synchronous call, why is this parsing error? Any suggestion?

编辑

为清楚起见,我理解如果 InvocationType ='Event',那么我们只会得到 invoke 调用的状态,而不是lambda函数结果.但就我而言,我需要两者-启动lambda异步并在完成后返回结果.我怎么做?是将结果写回s3并定期检查唯一的选择吗?

For clarity, I understand that if the InvocationType='Event', then we only get the status of the invoke call, not the lambda function result. In my case though, I need both - launch the lambda async and get the result back when done. How do I do that? Is writing the result back to s3 and periodically checking that the only option?

推荐答案

InvocationType ='Event'意味着您没有得到响应.异步Lambda调用意味着您只想调用函数,而不必等待响应.来自该功能的响应有效负载被服务丢弃.

InvocationType='Event' means you aren't getting a response. An asynchronous Lambda invocation means you just want to invoke the function, not wait for the response. The response payload from the function is discarded by the service.

https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html

请注意,此处提到的 queue 是Lambda服务内部的队列,请勿与Amazon Simple Queue Service(SQS)混淆.

Note that the queue mentioned here is a queue inside the Lambda service, not to be confused with Amazon Simple Queue Service (SQS).

这篇关于从python中对AWS lambda的异步调用获取响应结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:30