无服务器框架Python lambda直接返回JSON [英] Serverless Framework Python lambda return JSON directly
问题描述
我试图找出如何使用无服务器框架直接将响应作为JSON返回.这是具有Lambda代理集成的AWS上的功能.所有默认设置.目标是从python lambda函数中,HTTP响应客户端直接获取的是JSON对象,而不是JSON的字符串序列化.
I'm trying to find out how can I return the response as a JSON directly using Serverless Framework. This is a function on AWS with Lambda Proxy Integration. All default setting. The goal is to from the python lambda function, the HTTP response client gets is directly a JSON object, instead of a string serialization of a JSON.
python处理程序与这个处理程序一样简单
The python handler is as simple as this one
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中得到的响应BODY是:
With these configurations, the response BODY I get in Postman is:
{
"statusCode": 200,
"body": {
"foo": "bar"
},
"headers": {
"Content-Type": "application/json"
}
}
所以这很奇怪,为什么我把一切都当成身体?如何正确配置它以便只获得真实"主体?
So this is strange, why I get everything as body? How do I configure it properly so that I only get the "real" body?
推荐答案
方法#1
使用json.dumps()将JSON转换为字符串.
approach #1
Use json.dumps() to convert JSON to string.
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().但这会将您的输出转换为
approach #2
Use lambda integration and avoid json.dumps(). But this will transform your output as
{ foo = bar}
这篇关于无服务器框架Python lambda直接返回JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!