【问题标题】:Validating a JSON post request coming into a python flask app验证进入 python 烧瓶应用程序的 JSON 发布请求
【发布时间】:2023-03-08 01:45:01
【问题描述】:

我有一个简单的烧瓶应用程序

@app.route("/endpoint/", methods=['POST'])
def mypostmethod():

    if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':

        post_data = request.json

        req_data = request.get_json()

        content = req_data['content']

        return content

我卷曲如下:

curl -X POST "localhost:8080/endpoint/" -H "Content-Type: application/json" -d '{'content': 'Blah'}'

我收到以下错误:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Failed to decode JSON object: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)</p>

这是因为,cURL 中的 json 正文使用单引号,当我使用双引号时它可以工作。

我想知道,如何在我的烧瓶应用程序中添加一些代码来检查此错误并返回自定义响应代码和一些响应消息?在哪里添加 try 块?能否请您以我的代码为例。

【问题讨论】:

    标签: python json curl flask


    【解决方案1】:

    我对 JSON 不是很有经验,但我会尝试这样的事情:

    你得到的数据(我猜)在request.json。

    因为这是您遇到的错误 - Failed to decode JSON object: Expecting property name enclosed in double quotes,我可能会这样做

    include json
    
    try:
     json.dumps(request.json)
    except JSONDecodeError as e:
     return("wrong request data")
    

    JSONDecodeError 在json 库文档here 中被提及

    【讨论】:

    • AttributeError: 模块 'json' 没有属性 'encode'
    • 我的错误,意思是json.dumps :)
    【解决方案2】:

    在你的 json 中使用双引号:

    curl -X POST "localhost:8080/endpoint/" -H "Content-Type: application/json" -d '{"content": "Blah"}'
    

    【讨论】:

    • 嗨,我知道。我的问题是如何将代码添加到烧瓶应用程序以捕获此问题并返回自定义响应错误/代码。
    【解决方案3】:

    这根本不是 cURL 中 -d 选项的有效参数。您需要将参数中的单引号替换为双引号,并用单引号将其括起来。

    wrong: '{'content': 'Blah'}'
    ok:    '{"content": "Blah"}'
    

    【讨论】:

    • 嗨,我知道。我的问题是如何将代码添加到烧瓶应用程序以捕获此问题并返回自定义响应错误/代码。
    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 2021-12-30
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 2015-03-10
    相关资源
    最近更新 更多