简体   繁体   English

返回python字符串作为HTTP响应的主体

[英]Return python string as the body of HTTP response

I am using AWS Lambda with python-2.7 replying back to AWS Api Gateway . 我正在将AWS Lambdapython-2.7回复AWS Api Gateway My lambda function should return a response looking like following, but I am strugling with putting the proper form of body in the JSON response: 我的lambda函数应该返回如下所示的响应,但是我正在努力将正确的body形式放入JSON响应中:

    return_value = {
        "statusCode": 200,
        "isBase64Encoded": 'false',
        "headers": {"Content-Type": "application/json"},
        "body": {payload['note']}
    }

the type of payload['note'] is unicode , so I don't know what exactly to put in the brackets opposite to body , as I am new to python and tried a lot without being able to figure it out. payload['note']的类型是unicode ,所以我不知道在body对面的括号中到底放什么,因为我是python的新手,并且尝试了很多却无法弄清楚。 I tried to convert it to string using: 我试图使用以下方法将其转换为字符串:

unicodedata.normalize('NFKD', payload['note']).encode('ascii', 'ignore')

But it didn't work either. 但这也不起作用。

First, I believe it is a good idea to convert the unicode string to a python string before, since I dont know if the rest of your code can handles unicode in json. 首先,我认为将unicode字符串转换为python字符串是一个好主意,因为我不知道您的其余代码是否可以处理json中的unicode。

I think your problem is related to json formatting. 我认为您的问题与json格式有关。 As JSON, the body field should contain key-value pairs. 作为JSON,主体字段应包含键值对。

Try with : 尝试:

return_value = {
    "statusCode": 200,
    "isBase64Encoded": 'false',
    "headers": {"Content-Type": "application/json"},
    "body": {"note": payload['note']}
}

It's probably best to build it using standard objects first, then convert it to JSON as you return it. 最好先使用标准对象进行构建,然后在返回时将其转换为JSON。 For example: 例如:

# coding=utf-8

import json

def aws_message(payload):
  message = dict(statusCode=200,
                 isBase64Encoded=False,
                 headers={"Content-Type": "application/json"},
                 body=payload['note'])
  return json.dumps(message)


if __name__=="__main__":
    payload = dict(note='something')
    print(aws_message(payload))

Unfortunately you'll notice I switched from the long-form dict() creation to the short-hand when building the headers inside the message (it was a quick 'n dirty example). 不幸的是,您会在构建消息内的标头时从长格式的dict()创建切换为简写形式(这是一个快速的'n肮脏示例)。 Here is the output: 这是输出:

C:\Python37\python.exe C:/dev/scratches/scratch_17.py
{"statusCode": 200, "isBase64Encoded": false, "headers": {"Content-Type": "application/json"}, "body": "something"}

As you can see, it's quite straight-forward to build the object in a fashion that is easy to understand, and then let the json library do all the conversion into a correctly-formatted response. 如您所见,以一种易于理解的方式构建对象,然后让json库将所有转换全部转换为格式正确的响应是非常简单的。 I hope this helps. 我希望这有帮助。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM