简体   繁体   English

使用API​​网关尝试AWS Python Lambda函数中的访问参数时出错

[英]Error when trying access parameters in AWS Python Lambda function using API Gateway

I have this python lambda function 我有这个python lambda函数

import json

def lambda_handler(event, context):

    post_user = ""
    post_user = event["user"]
    print(post_user)        

    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": True
        }

This works as expected when I run a test within the lambda IDE. 当我在Lambda IDE中运行测试时,这可以按预期工作。 The test is configured to pass: 测试配置为通过:

{ "user": "JOHN", "pwd": "pwd1" } {“ user”:“ JOHN”,“ pwd”:“ pwd1”}

but when I run a test using the API Gateway, I get this error: 但是当我使用API​​网关运行测试时,出现此错误:

Mon Mar 25 20:47:29 UTC 2019 : Endpoint response body before transformations: {"errorMessage": "'user'", "errorType": "KeyError", "stackTrace": [" File \\"/var/task/lambda_function.py\\", line 6, in lambda_handler\\n post_user = event[\\"user\\"]\\n"]} Mon Mar 25 20:47:29 UTC 2019 : Lambda execution failed with status 200 due to customer function error: 'user'. Mon Mar 25 20:47:29 UTC 2019:转换前的端点响应主体:{“ errorMessage”:“'用户'”,“ errorType”:“ KeyError”,“ stackTrace”:[“文件\\” / var / task / lambda_function.py \\“,第6行,位于lambda_handler \\ n中post_user = event [\\” user \\“] \\ n”]}星期一3月25日20:47:29 UTC 2019:由于客户功能错误,Lambda执行失败,状态为200 :“用户”。 Lambda request id: f7955f74-e608-4b10-b216-4e4acf682307 Mon Mar 25 20:47:29 UTC 2019 : Method completed with status: 502 Lambda请求ID:f7955f74-e608-4b10-b216-4e4acf682307 Mon Mar 25 20:47:29 UTC 2019:方法已完成,状态为:502

I have defined the API gateway test as follows: 我定义了API网关测试,如下所示: 在此处输入图片说明

This is because when the event object comes from API Gateway, it has some extra information on it. 这是因为event对象来自API网关时,它具有一些额外的信息。 It's not as simple as the JSON you use to test from the console. 它不像您用来从控制台进行测试的JSON那样简单。

You need to first access the body object and then finally your JSON object. 您需要先访问body对象,然后再访问JSON对象。

Here's how an event from API Gateway looks like: 来自API网关的事件如下所示:

{
    "path": "/test/hello",
    "headers": {
      "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Accept-Encoding": "gzip, deflate, lzma, sdch, br",
      "Accept-Language": "en-US,en;q=0.8",
      "CloudFront-Forwarded-Proto": "https",
      "CloudFront-Is-Desktop-Viewer": "true",
      "CloudFront-Is-Mobile-Viewer": "false",
      "CloudFront-Is-SmartTV-Viewer": "false",
      "CloudFront-Is-Tablet-Viewer": "false",
      "CloudFront-Viewer-Country": "US",
      "Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
      "Upgrade-Insecure-Requests": "1",
      "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
      "Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
      "X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
      "X-Forwarded-For": "192.168.100.1, 192.168.1.1",
      "X-Forwarded-Port": "443",
      "X-Forwarded-Proto": "https"
    },
    "pathParameters": {
      "proxy": "hello"
    },
    "requestContext": {
      "accountId": "123456789012",
      "resourceId": "us4z18",
      "stage": "test",
      "requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
      "identity": {
        "cognitoIdentityPoolId": "",
        "accountId": "",
        "cognitoIdentityId": "",
        "caller": "",
        "apiKey": "",
        "sourceIp": "192.168.100.1",
        "cognitoAuthenticationType": "",
        "cognitoAuthenticationProvider": "",
        "userArn": "",
        "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
        "user": ""
      },
      "resourcePath": "/{proxy+}",
      "httpMethod": "GET",
      "apiId": "wt6mne2s9k"
    },
    "resource": "/{proxy+}",
    "httpMethod": "GET",
    "queryStringParameters": {
      "name": "me"
    },
    "stageVariables": {
      "stageVarName": "stageVarValue"
    },
    "body": "'{\"user\":\"john\",\"pwd\":\"pwd1\"}'"
  }

Keep in mind that the body from API Gateway always comes stringified, so if you want to access it, you first need to parse this JSON string using json.loads(event["body"]) . 请记住,API Gateway的body始终是字符串化的,因此,如果要访问它,则首先需要使用json.loads(event["body"])解析此JSON字符串。

Remember that the body of your response must be Stringified when returning to API Gateway, as we discussed on this answer . 请记住,如我们在此答案上所讨论的,返回到API网关时, 响应的主体必须为String。

You can see the event sent from API Gateway in the docs 您可以在文档中查看从API网关发送的事件

@Thales Minussi led me to this answer but the key I'm getting from the response is different than he suggested but his suggestion is what helped me so I'm accepting it as the answer @Thales Minussi使我得到了这个答案,但是我从响应中得到的关键与他的建议不同,但是他的建议对我有所帮助,因此我接受它作为答案

I was getting this response. 我得到了这个回应。 The body key is coming as null . body密钥即将为null but there were queryStringParameters 但是有queryStringParameters

{
  "resource": "/match_creds",
  "path": "/match_creds",
  "httpMethod": "GET",
  "headers": null,
  "multiValueHeaders": null,
  "queryStringParameters": {
    "pwd": "pwd1",
    "user": "JOHN"
  },
  "multiValueQueryStringParameters": {
    "pwd": [
      "pwd1"
    ],
    "user": [
      "JOHN"
    ]
  },
  "pathParameters": null,
  "stageVariables": null,
  "requestContext": {
    "path": "/match_creds",
    "accountId": "",
    "resourceId": "",
    "stage": "test-invoke-stage",
    "domainPrefix": "testPrefix",
    "requestId": "",
    "identity": {
      "cognitoIdentityPoolId": null,
      "cognitoIdentityId": null,
      "apiKey": "test-invoke-api-key",
      "cognitoAuthenticationType": null,
      "userArn": "",
      "apiKeyId": "test-invoke-api-key-id",
      "userAgent": "",
      "accountId": "",
      "caller": "",
      "sourceIp": "test-invoke-source-ip",
      "accessKey": "",
      "cognitoAuthenticationProvider": null,
      "user": ""
    },
    "domainName": "testPrefix.testDomainName",
    "resourcePath": "/match_creds",
    "httpMethod": "GET",
    "extendedRequestId": "",
    "apiId": ""
  },
  "body": null,
  "isBase64Encoded": false
}

I changed my function to 我将功能更改为

import json

    def lambda_handler(event, context):

        json_data = event["queryStringParameters"] 
        user = json_data["user"]

        return {
            "statusCode": 200,
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps(user)
            }

您需要激活“集成请求”下的“使用Lambda代理集成”设置。

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

相关问题 使用AWS Lambda和api-gateway创建API时出错(python) - Error when creating API using AWS Lambda and api-gateway (python) 将查询字符串从 AWS API 网关导入 Lambda Python Z86408593C34AF77FDD1Z60DF932F8B52 - Import Query String from AWS API Gateway into Lambda Python Function AWS Lambda(Python + Flask)基本功能无法使用 API 网关 - AWS Lambda (Python + Flask) basic functionality not working using API Gateway 在没有 API 网关的 Python 中将参数传递给 AWS Lamda function - Pass parameters to AWS Lamda function in Python without API Gateway 无法使用 API Gateway 运行 AWS Lambda 函数 - Unable to run AWS Lambda function with API Gateway JSON 有效负载,AWS Lambda(Python),API 网关 - JSON Payload, AWS Lambda (Python), API Gateway AWS API Gateway 和 Python Lambda 返回 HTML - AWS API Gateway and Python Lambda returning HTML AWS API Gateway Lambda错误正则表达式 - AWS API Gateway Lambda Error Regex 如何使用 multipart/form-data 创建一个将 pdf 文件作为输入的 AWS Lambda/API 网关 python 函数? - How to create an AWS Lambda/API gateway python function that takes a pdf file as input using multipart/form-data? 在 Python 中的 API 网关请求中使用 AWS Cognito 访问令牌 - Using AWS Cognito access token in requests for API gateway in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM