关于python:Flask – 错误请求浏览器(或代理)发送了此服务器无法理解的请求

Flask - Bad Request The browser (or proxy) sent a request that this server could not understand

本问题已经有最佳答案,请猛点这里访问。

我正在尝试上传文件,并使用flask将数据任务输入MongoDB但我在填写表格和上传图片时出错:

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

我的HTML代码

1
2
3
4
5
6
7
8
9
10
11
    <form class="form-check form-control" method="post" enctype="multipart/form-data" action="{{ url_for('index') }}">      
          <label>Full Name*</label></td>
          <input name="u_name" type="text" class="text-info my-input" required="required" />
          <label>Email*</label>
          <input name="u_email" type="email" class="text-info my-input" required="required" />
          <label>Password*</label>
          <input name="u_pass" type="password" class="text-info my-input" required="required" />
          <label>Your Image*</label>
          <input name="u_img" type="file" class="text-info" required="required" /></td>
          <input name="btn_submit" type="submit" class="btn-info" />
    </form>

&我的python代码(amp;M):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from flask import Flask, render_template, request, url_for
from flask_pymongo import PyMongo
import os
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'flask_assignment'
app.config['MONGO_URI'] = 'mongodb://<user>:<pass>@<host>:<port>/<database>'
mongo = PyMongo(app)
app_root = os.path.dirname(os.path.abspath(__file__))


@app.route('/', methods=['GET', 'POST'])
def index():
    target = os.path.join(app_root, 'static/img/')
    if not os.path.isdir(target):
        os.mkdir(target)
    if request.method == 'POST':
        name = request.form['u_name']
        password = request.form['u_pass']
        email = request.form['u_email']
        file_name = ''
        for file in request.form['u_img']:
            file_name = file.filename
            destination = '/'.join([target, file_name])
            file.save(destination)
        mongo.db.employee_entry.insert({'name': name, 'password': password, 'email': email, 'img_name': file_name})
        return render_template('index.html')
    else:
        return render_template('index.html')

app.run(debug=True)


由于访问了request.form中不存在的密钥而导致的BadRequestKeyError错误。

1
2
ipdb> request.form['u_img']
*** BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

上传的文件在request.files下键入,而不是在request.form字典下键入。另外,您需要丢失循环,因为在u_img下键入的值是FileStorage的一个实例,不可重复。

1
2
3
4
5
6
7
8
9
10
11
12
13
@app.route('/', methods=['GET', 'POST'])
def index():
    target = os.path.join(app_root, 'static/img/')
    if not os.path.isdir(target):
        os.makedirs(target)
    if request.method == 'POST':
        ...
        file = request.files['u_img']
        file_name = file.filename or ''
        destination = '/'.join([target, file_name])
        file.save(destination)
        ...
    return render_template('index.html')