【问题标题】:What is HTTP 400 Bad Request in Flask什么是 Flask 中的 HTTP 400 错误请求
【发布时间】:2018-03-02 18:27:59
【问题描述】:

什么是 Http 400 错误请求以及导致它发生的原因?

我可以使用什么方法来了解request.form[key] 中的哪个key 导致了错误的请求以及如何防止它?

更新

正如 Gerand 在他的评论中提到的:

当您通过 http 请求文件时会发生此错误 不存在[....]

为了更清楚,这里是导致Bad Request的示例代码:

hello.py

# -*- coding: utf-8 -*-
from flask import *
import re

app = Flask(__name__)


@app.route('/', methods=['GET','POST'])
def checkName():

    return render_template('hello.html')

@app.route('/hello',methods=['GET','POST'])
def printName():
    if request.method=='POST':
        username = request.form['username']
        bad_key = request.form['bad_key'] # this key is not exist
        
        return "Hello, ",username

if __name__ == '__main__':

    app.run(debug=True)

hello.html

<form class="form-horizontal" action='/hello' method='POST' name="frm_submit">
  <div class="form-group">
    <label for="username" class="col-sm-2 control-label">User Name:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="username" name="username" placeholder="username">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Submit</button>
    </div>
  </div>
</form>

从上面的代码中,浏览器返回 Bad Request - The browser (or proxy) sent a request that this server could not understand. 却不知道是哪个键导致了这个错误。

因此,我可以使用哪种方法来了解导致此错误的key,以及如何防止它?

谢谢。

【问题讨论】:

  • 你想做什么?您正在使用哪些库...请澄清您的具体问题或添加其他详细信息以准确突出您需要什么。正如目前所写的那样,很难准确地说出你在问什么。请参阅“如何提问”页面以获得澄清此问题的帮助。
  • @KaustubhKallianpur,我想知道python中Error 400 Bad Request的原因是什么?我怎样才能知道原因并防止这种情况发生?谢谢。
  • 当您通过 http 请求不存在的文件时会发生此错误。与python无关。
  • @Gerard 这不是“404 - 未找到”吗? 400 指一个损坏的请求
  • @lausek 完全正确,我有点脑残。通常发生在我身上

标签: python flask werkzeug


【解决方案1】:

Flask 使用 werkzeug 库的 MultiDict 数据结构来保存 POST 数据。

如果查看MultiDict.__getitem__implementation,可以看到如果没有找到某个键​​,它将以键的名称作为参数引发BadRequestKeyError。因此,您可以检查异常的 args 属性以获取坏键的名称:

from werkzeug.exceptions import BadRequestKeyError

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    if request.method == 'POST':
        username = request.form['username']
        try:
            bad_key = request.form['bad_key']
        except BadRequestKeyError as ex: 
            return 'Unknown key: "{}"'.format(ex.args[0]), 500 

注意,虽然BadRequestKeyErrors 字符串表示

400 Bad Request:浏览器(或代理)发送了此服务器无法理解的请求。

响应的状态其实是

500 内部服务器错误

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 2017-07-21
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多