如何故意在Python/Flask中引起400错误的请求? [英] How to intentionally cause a 400 Bad Request in Python/Flask?
问题描述
我的REST API的使用者说,有时我会返回400 Bad Request
-The request sent by the client was syntactically incorrect.
错误.
A consumer of my REST API says that on occasion I am returning a 400 Bad Request
- The request sent by the client was syntactically incorrect.
error.
我的应用程序(Python/Flask)日志似乎没有捕获到该日志,我的Web服务器/Nginx日志也没有捕获.
My application (Python/Flask) logs don't seem to be capturing this, and neither do my webserver/Nginx logs.
我想尝试在Flask中引起400错误的请求,以进行调试.我该怎么办?
I would like to try to cause a 400 bad request in Flask for debugging purposes. How can I do this?
根据James的建议,我添加了类似于以下内容的内容:
Following James advice, I added something similar to the following:
@app.route('/badrequest400')
def bad_request():
return abort(400)
当我调用此命令时,flask返回以下HTML,该HTML不使用客户端发送的请求在语法上不正确"行:
When I call this, flask returns the following HTML, which doesn't use the "The request sent by the client was syntactically incorrect" line:
<!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>
(我不确定为什么不包括<body>
标签.
(I'm not sure why it isn't including the <body>
tags.
在我看来,400错误消息有不同的变化形式.例如,如果我将Cookie的长度设置为50,000(使用Postcept的Interceptor),则会从Flask收到以下错误消息:
It appears to me that there are different variations of the 400 error message. For example, if I set a cookie to a value of length 50,000 (using Interceptor with Postman), I'll get the following error from Flask instead:
<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个错误的不同变化?
Is there a way to get Flask to through the different variations of 400 errors?
推荐答案
您可以使用abort
通过状态代码引发HTTP错误.
You can use abort
to raise an HTTP error by status code.
from flask import abort
@app.route('/badrequest400')
def bad_request():
abort(400)
这篇关于如何故意在Python/Flask中引起400错误的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!