Flask中的HTTP 400错误请求是什么 [英] What is HTTP 400 Bad Request in Flask

查看:116
本文介绍了Flask中的HTTP 400错误请求是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is Http 400 Bad Request and what causes it to happen?

我可以使用什么方法来知道 request.form [key] 中的哪个 key 会导致错误的请求,我该如何防止它发生?

What is method I can use to know which key in request.form[key] that cause bad request and how can I prevent it?

已更新

如Gerand在他的评论中所述:

As Gerand mentioned in his comment:

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

This error happens when you are requesting a file through http which doesn't exist [....]

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

To make it clearer, here my sample code that cause 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-浏览器(或代理)发送了该服务器无法理解的请求.,没有给出导致此错误的键的线索.

From code above, the browser return Bad Request - The browser (or proxy) sent a request that this server could not understand. without giving clue that which key that cause this error.

因此,我可以使用哪种方法知道哪个 key 导致此错误,以及如何防止该错误?

Therefore, which method I can use to know which key that cause this error, and how can I prevent it?

谢谢.

推荐答案

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

Flask uses the werkzeug library's MultiDict data structure to hold POST data.

如果您查看实现 MultiDict .__ getitem __ ,您可以看到,如果找不到键,它将引发以键名作为参数的 BadRequestKeyError .因此,您可以检查异常的 args 属性以获取错误密钥的名称:

If you look at the implementation of MultiDict.__getitem__, you can see that if a key is not found, it will raise BadRequestKeyError with the name of the key as an argument. So you can inspect the exception's args attribute to get the name of the bad key:

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 

请注意,虽然 BadRequestKeyError 字符串表示形式

400错误的请求:浏览器(或代理)发送了该服务器无法理解的请求.

400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

响应状态实际上是

500内部服务器错误

500 Internal Server Error

这篇关于Flask中的HTTP 400错误请求是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆