【问题标题】:How to validate a request body is a valid JSON coming into a python flask application如何验证请求正文是进入 python 烧瓶应用程序的有效 JSON
【发布时间】:2020-06-23 12:03:16
【问题描述】:

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

1 @app.route("/endpoint/", methods=['POST'])
2 def mypostmethod():
3
4    if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':
5        if request.is_json:
6            req_data = request.get_json()
7            try:
8                test_json = json.loads(req_data)
9                return req_data
10           except ValueError as e:
11               return Response('invalid json', status='400')
12        else:
13            return Response('response is not json', status='400')
14
15
16       if 'content' not in req_data:
17           return Response("No content received in request", status='400')
18
19       content = req_data['content']
20       return content

我卷曲如下:

我想知道如何输入一些代码来确保我们验证 第 6 行 使其成为有效的 json?

如果例如以下是传入的,应该可以的

'{"content": "Blah"}'

但如果出现以下情况,那么它应该返回 400 ERROR 并带有自定义响应消息

'{'content': '废话'}'

我尝试了一些过去/旧帖子,但无法成功?任何想法:)

【问题讨论】:

    标签: python json http flask


    【解决方案1】:

    下面有一个简单的测试方法,或者您可以查看flask-validate-json,但看起来您可以使用request object methods 解决此问题。此外,401 响应意味着未经授权,似乎 400 响应更合适? HTTP status responses

    当您将 json 加载到 json 模块中时,它会检查它是否有效,如果不是则引发 ValueError。

    您可以使用flash 向用户提供反馈,该反馈将在您的错误模板中提供。你可能想看看custom error handling。

    # Standard library implementation
    
    # See if request is in fact json
    if request.is_json:
        data = request.get_json()
        try:
            # Check if it is valid by loading it into json module
            test_json = json.loads(data)
            return data
        except ValueError as e:
            # Return invalid json
            flash('invalid json')
            return render_template('error.html'), 400
    else:
        # only accepts json data
        flash('data is not json')
        return render_template('error.html'), 400
    
    
    # error.html
    {% with messages = get_flashed_messages() %}
       {% if messages %}
          {% for message in messages %}
             {{ message }}
          {% endfor %}
       {% endif %}
    {% endwith %}
    

    【讨论】:

    • 我尝试了你的建议......请检查我更新的问题,但它没有返回我想要的?我希望它不会中止
    • 您必须尝试将 json 加载到 json 模块中,因为它会检查它是否有效。查看烧瓶文档后,我更新了答案。您可以将中止更改为您需要的任何内容。
    • 在您的示例中,您从未将其加载到 json 模块中。导入 json test_json = json.loads(req_data)
    • 我喜欢你的回答,只有 1 个问题。如果我按照你说的做(再次更新我的问题)它说第 16 行和第 17 行无法访问。此外,似乎无法让它打印我的自定义错误响应。我得到了通用的“错误请求 400”
    • 查看更新的答案——使用自定义错误模板。如果您需要这种类型的功能,我会考虑使用自定义错误处理程序。
    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 2012-06-13
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多