如何解决从 Flask 服务器捕获 RequestEntityTooLarge
令人惊讶的是,我无法了解其他人遇到同样问题的信息。
To my understanding,每当文件超过 MAX_CONTENT_LENGTH
时,它会自动抛出 413。问题是我如何捕捉它?
出于某种奇怪的原因,我可以在客户端捕获 415 状态代码和自定义 413 消息(尚未使用其他状态代码进行测试),但我无法从 RequestEntityTooLarge 中专门捕获。
我将最大尺寸设置为:app.config["MAX_CONTENT_LENGTH"] = 5242880
我的烧瓶代码:
def convert():
try:
data = request.form
fileUpload = request.files["fileUpload"]
# maybe some other code
except RequestEntityTooLarge as e:
print ("- File too large!")
# I can never catch this
return jsonify("large_file"),413
if file not in valid_formats:
# this is always caught on client,even if I change this status code to 413
# return jsonify("bad_format"),413
return jsonify("bad_format"),415
客户端(vanilla JS,带有 Fetch API)
fetch("/api/convert",{
method: "POST",body: formData
}).then(response => {
console.log(response.status);
// do whatever based on status
// here,i can catch 415 and custom 413 messages
return response.json();
}).then(data => {
// do some stuff
}).catch(error => {
console.log(error);
})
在浏览器的网络选项卡中,我可以看到如果我发送自定义 413 消息(return jsonify("bad_format"),413
,它显示它收到了状态代码 413。
但是,当我在捕获 RequestEntityTooLarge 时尝试发送 413 消息时,没有状态代码......?
我在 Firefox 和 Chrome 中尝试过,同时使用 Flask 生产服务器和 Gunicorn 服务器。这种奇怪的行为我不明白!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。