【问题标题】:How to intentionally cause a 400 Bad Request in Python/Flask?如何在 Python/Flask 中故意导致 400 错误请求?
【发布时间】:2015-11-27 08:01:41
【问题描述】:

我的 REST API 的使用者说我有时会返回 400 Bad Request - The request sent by the client was syntactically incorrect. 错误。

我的应用程序(Python/Flask)日志似乎没有捕捉到这一点,我的网络服务器/Nginx 日志也没有。

编辑:出于调试目的,我想尝试在 Flask 中引发 400 错误请求。我该怎么做?

按照 James 的建议,我添加了类似于以下内容的内容:

@app.route('/badrequest400')
def bad_request():
    return abort(400)

当我调用它时,flask 返回以下 HTML,它没有使用“客户端发送的请求在语法上不正确”这一行:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

(我不确定为什么它不包含&lt;body&gt; 标签。

在我看来,400 错误消息有不同的变体。例如,如果我将 cookie 设置为长度为 50,000 的值(使用带有 Postman 的 Interceptor),我会从 Flask 得到以下错误:

<html>
<head>
    <title>Bad Request</title>
</head>
<body>
    <h1>
        <p>Bad Request</p>
    </h1>
Error parsing headers: 'limit request headers fields size'

</body>
</html>

有没有办法让 Flask 通过 400 错误的不同变体?

【问题讨论】:

    标签: python rest nginx postman http-status-code-400


    【解决方案1】:

    您可以将状态码作为return 的第二个参数返回,请参见下面的示例

    @app.route('/my400')
    def my400():
        code = 400
        msg = 'my message'
        return msg, code
    

    【讨论】:

    • 另外值得注意的是,状态模块包含标准的 HTTP 状态。 from flask_api import status 然后只是 status.HTTP_200_OK
    【解决方案2】:

    您可以使用abort 通过状态码引发 HTTP 错误。

    from flask import abort
    @app.route('/badrequest400')
    def bad_request():
        abort(400)
    

    【讨论】:

    • 嗨詹姆斯,谢谢你的想法。但是,当我这样做时,Flask 默认会在 400 Bad Request 下返回以下描述:The browser (or proxy) sent a request that this server could not understand.。看起来有不同类型的 400 错误消息——例如,如果我创建包含 50000 个字符的添加 cookie,它会失败并显示 400,但描述说它是一个无效的标题。关于如何触发 400 的“语法错误”版本的任何想法?
    • 嗨詹姆斯,你对我的评论和更新的问题有什么想法吗?
    • 希望我也可以返回带有状态码的自定义消息。
    【解决方案3】:

    您也可以使用abort 自定义消息错误:

    from flask import abort
    abort(400, 'My custom message')
    

    https://flask-restplus.readthedocs.io/en/stable/errors.html

    【讨论】:

      【解决方案4】:

      另外,你可以使用 jsonify

      from flask import jsonify
      
      class SomeView(MethodView):
          def post(self, *args, **kwargs):
              if "csv_file" not in request.files:
                  return jsonify({'errors': 'No csv_file key in request.files.'}), 400
      

      【讨论】:

        猜你喜欢
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        • 2019-12-31
        相关资源
        最近更新 更多