无服务器框架Python Lambda可以直接返回JSON

6
我想知道如何使用Serverless Framework直接返回JSON响应。此函数在AWS上使用Lambda代理集成。所有默认设置。目标是从Python Lambda函数直接获取HTTP响应客户端的JSON对象,而不是JSON的字符串序列化。
该Python处理程序非常简单。
    def handle(event, context):
        log.info("Hello Wold")
        log.info(json.dumps(event, indent=2))
        return {
            "statusCode": 200,
            "body": {"foo": "bar"},
            "headers": {
                "Content-Type": "application/json"
            }
        }

该函数的形式如下:
    functions:
      report:
        handler: handler.handle
        events:
          - http:
              path: api/mypath
              method: post
              authorizer: aws_iam

有了这些配置,我在Postman中得到的响应主体是:

    {
        "statusCode": 200,
        "body": {
            "foo": "bar"
        },
        "headers": {
            "Content-Type": "application/json"
        }
    }

这很奇怪,为什么我收到的都是完整的内容?该怎样正确配置才能只获取“真正”的内容?

2个回答

6

第一种方法

使用json.dumps()将JSON转换为字符串。

import json
def handle(event, context):
    log.info("Hello Wold")
    log.info(json.dumps(event, indent=2))
    return {
        "statusCode": 200,
        "body": json.dumps({"foo": "bar"}),
        "headers": {
            "Content-Type": "application/json"
        }
    }

方案 #2

使用 Lambda 集成并避免使用 json.dumps()。但这会将您的输出转换为:

{ foo = bar}

4

当与API网关一起使用时,需要将正文字符串化。

实现这个功能的“Python风格”是将JSON正文传递给json.dumps函数。

def handle(event, context):
  log.info("Hello Wold")
  log.info(json.dumps(event, indent=2))
  return {
      "statusCode": 200,
      "body": json.dumps({"foo": "bar"}),
      "headers": {
          "Content-Type": "application/json"
      }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接