AWS Lambda python API调用方法没有返回JSON - 不可序列化?

时间:2017-01-20 12:50:46

标签: python-2.7 amazon-web-services aws-lambda restful-architecture

我有一个Lambda函数,它是对API的基本Python GET调用。它在本地工作正常,但是当我上传到Lambda(以及请求库)时,它不会从API调用返回JSON响应。我只是希望它将整个JSON对象返回给调用者。我在这里做了一些根本错误的事情 - 我偶然发现了几篇文章说不支持从Lambda Python函数返回JSON。

以下是代码:

import requests
import json
url = "http://url/api/projects/"
headers = {
   'content-type': "application/json",
   'x-octopus-apikey': "redacted",
   'cache-control': "no-cache"
    }

def lambda_handler(event, context):
    response = requests.request("GET", url, headers=headers)
    return response

我的包中包含请求库和dist,以及json库(我不认为它需要这个)。返回的错误消息是:

    {
  "stackTrace": [
    [
      "/usr/lib64/python2.7/json/__init__.py",
      251,
      "dumps",
      "sort_keys=sort_keys, **kw).encode(obj)"
    ],
    [
      "/usr/lib64/python2.7/json/encoder.py",
      207,
      "encode",
      "chunks = self.iterencode(o, _one_shot=True)"
    ],
    [
      "/usr/lib64/python2.7/json/encoder.py",
      270,
      "iterencode",
      "return _iterencode(o, 0)"
    ],
    [
      "/var/runtime/awslambda/bootstrap.py",
      41,
      "decimal_serializer",
      "raise TypeError(repr(o) + \" is not JSON serializable\")"
    ]
  ],
  "errorType": "TypeError",
  "errorMessage": "<Response [200]> is not JSON serializable"
}

2 个答案:

答案 0 :(得分:5)

我已经解决了这个问题 - 我的Python代码的问题在于它试图返回整个响应,而不仅仅是JSON主体(我本地版本的代码打印& #39; response.text&#39)。另外,我确保响应是JSON格式(而不是原始文本)。更新的代码:

import requests
import json
url = "http://url/api/projects/"
headers = {
   'content-type': "application/json",
   'x-octopus-apikey': "redacted",
   'cache-control': "no-cache"
    }

def lambda_handler(event, context):
    response = requests.request("GET", url, headers=headers)           
    try:
        output = response.json()
    except ValueError:
        output = response.text
    return output

答案 1 :(得分:0)

我也遇到了同样的错误,有一段时间我可以通过更改Lambda python3.6中的响应代码来解决此问题:

更改:将response['Body'].read()更改为response['Body'].read().decode()

通过这种方式,您将获得JSON,尽管在我的情况下,我到处都有/,稍后将其删除。