簡體   English   中英

AWS API 網關 Lambda 失敗,狀態為 200

[英]AWS API Gateway Lambda failed with status 200

我正在編寫一個微服務,我的 lambda 處理程序在請求正文中采用 JSON 並構建一個 Jinja2 模板。 My Lambda function is working properly and returns a status code of 200, but when I call the function through my API Gateway I get a 502 response.

def lambda_handler(event, context):
    try:
        file_object = s3.get_object(Bucket= 'bucket_name', Key='object_name')
        file_content = file_object["Body"].read().decode('utf-8')
        template = Template(file_content)
        rendered_template = template.render(resume = request_body)
        # Do some logic to place render in s3 and get path
        response = {
            'statusCode': 200,
            'header': {'Content-Type': 'application/json'},
            'body': 'path to file'
        }
        return response
    except Exception as e:
        print(e)
        raise e

我使用的請求正文類似於:

{
  "username": "john-doe",
  "location": "US",
  .
  .
  .
}

我收到的響應錯誤是:

{
  "errorMessage": "'str object' has no attribute 'lastName'",
  "errorType": "UndefinedError",
  "stackTrace": [
    "  File \"/var/task/resume_service.py\", line 39, in lambda_handler\n    raise e\n",
    "  File \"/var/task/resume_service.py\", line 25, in lambda_handler\n    generate = template.render(resume=request_body)\n",
    "  File \"/var/task/jinja2/asyncsupport.py\", line 76, in render\n    return original_render(self, *args, **kwargs)\n",
    "  File \"/var/task/jinja2/environment.py\", line 1008, in render\n    return self.environment.handle_exception(exc_info, True)\n",
    "  File \"/var/task/jinja2/environment.py\", line 780, in handle_exception\n    reraise(exc_type, exc_value, tb)\n",
    "  File \"/var/task/jinja2/_compat.py\", line 37, in reraise\n    raise value.with_traceback(tb)\n",
    "  File \"<template>\", line 28, in top-level template code\n",
    "  File \"/var/task/jinja2/environment.py\", line 411, in getitem\n    return obj[argument]\n"
  ]
}

為什么Lambda function自己調用成功,通過API網關調用失敗?

將 API 網關與 Lambda 代理集成一起使用時,API 網關期望從 Z04A7DA3C5B04CAD85DA1EEBB9231B 中列出特定格式返回的數據。 您還需要在返回的響應中添加isBase64Encoded標志。

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... },
    "body": "..."
}

瀏覽代碼,看起來這僅適用於 function 成功返回,但如果出現任何錯誤,它將引發異常 - 這是 API 網關不期望的; 因此 502 Malformed 代理。

為了更清楚地說明這一點,請檢查這兩個請求之間的區別 - 來自控制台和來自 API 網關。 由於我們必須設置一個特定的 JSON 有效負載來從控制台(或任何調用服務)調用 function,我將在處理程序之后打印出事件以檢查 ZDB9742387 的事件結構是什么,並在測試來自該網關的請求時使用該控制台看看是否仍然有效。 我猜這樣做,它不會起作用,因為錯誤聲稱'str object' has no attribute 'lastName'

If this works with API Gateway payload from the console, I would check the full request/response logs from API Gateway and Lambda function logs (with event printed) to get more clarity between the two requests.

問題恰好出在 Jinja2 上。 Jinja2 具有多個創建函數,用於渲染具有給定參數的模板。

渲染([上下文]):“此方法接受與 dict 構造函數相同的 arguments”

generate([context]): "對於非常大的模板,它不會一次渲染整個模板,而是一個接一個地評估每個語句。

由於我的模板的大小,它無法通過更改來渲染()整個模板

rendered_template = Template.render(resume = request_body)到: rendered_template = Template.generate(resume = request_body)

問題已解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM