如何故意在Python/Flask中导致400 Bad Request?

Mat*_*sen 7 python rest nginx http-status-code-400 postman

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

我的应用程序(Python/Flask)日志似乎没有捕获这个,我的webserver/Nginx也没有记录.

编辑:我想尝试在Flask中导致400个错误请求以进行调试.我怎样才能做到这一点?

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

@app.route('/badrequest400')
def bad_request():
    return abort(400)
Run Code Online (Sandbox Code Playgroud)

当我调用它时,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>
Run Code Online (Sandbox Code Playgroud)

(我不确定为什么它不包括<body>标签.

在我看来,400错误消息有不同的变化.例如,如果我将cookie设置为长度为50,000的值(使用Interceptor with Postman),我将从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>
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ohn 22

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

@app.route('/my400')
def my400():
    code = 400
    msg = 'my message'
    return msg, code
Run Code Online (Sandbox Code Playgroud)

  • 似乎比公认的答案更灵活. (4认同)

小智 12

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

from flask import abort
abort(400, 'My custom message')
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*les 9

为什么不定义一个简单地抛出HTTP/400错误的URL路由?

from flask import abort
@app.route('/badrequest400')
def bad_request():
    abort(400)
Run Code Online (Sandbox Code Playgroud)