如何使 lambda 函数作为目标在 ALB 后面工作?

how to make a lambda function work behind ALB as a target?

我在 ALB 后面有一个 lambda 函数 (python 3.7)。此函数接受 2 个参数(长度和宽度)来计算矩形的面积。在正常情况下,lamda 将从 event(event['length'], event['bredth']) 获取这些值,我们可以通过将参数发送为 {"length": 5,"bredth" : 10} 来自控制台。

现在,当我将此 lambda 函数作为目标放在 ALB 后面(路径为 /example1)时,如何将这些参数传递给 lambda 函数?我尝试了“area = event['multiValueQueryStringParameters']['length'] * event['multiValueQueryStringParameters']['bredth']”,但没有用。当我将端点作为 https://example.com/example1?length=10&bredth=10 时,它会抛出 502。如果我将函数内部区域的值硬编码并将端点作为 https:// example.com/example1,这工作正常,returns 响应为 json 字符串。下面是代码。另外,在这种情况下,如何从控制台测试lambda?

import json
  def lambda_handler(event, context):    response = {    "statusCode": 200,    "statusDescription": "200 OK",       "isBase64Encoded": False,    "headers": {    "Content-Type":    "text/json; charset=utf-8"    }
   }    #area = event['length'] * event['bredth']    area = event['multiValueQueryStringParameters']['length'] *    event['multiValueQueryStringParameters']['bredth']    #area = 50       response['body'] = json.dumps({"area of the rectangle is": area})
  return response

错误是由于数据类型不正确造成的。纠正后,它工作正常! 下面是完整代码(带注释的代码用于调试)

import json

def lambda_handler(event, context):
response = {
"statusCode": 200,
"statusDescription": "200 OK",
"isBase64Encoded": False,
"headers": {
"Content-Type": "json; charset=utf-8"
}
     }

keydata1 = int(event['queryStringParameters']['length'])
keydata2 = int(event['queryStringParameters']['bredth'])
area = int(keydata1 * keydata2)
if event['httpMethod']=='GET':
    #response['body'] = json.dumps(event) # I'm just printing the request body as the whole event
    #response['body'] = "this is from GET" # this also works as text in the response
    #response['body'] = json.dumps({"area of the circle is": "this response is json formatted"}) # this also works as json output
    #response['body'] = json.dumps({"area of the circle is": 50}) # this also works as json output
    #response['body'] = json.dumps({"area of the circle is": keydata2}) # this also works as json output
    response['body'] = json.dumps({"area of the circle is": area})
else:
    response['body'] = json.dumps(event)
#response['body'] = json.dumps(event)

return response

下面是我如何在 ALB 后面调用我的 lambda 函数:

获取示例。com/example1?length=50&bredth=25