. Advertisement .
..3..
. Advertisement .
..4..
I get the error message:
Bad Request The browser (or proxy) sent a request that this server could not understand
Has anyone ever faced this problem? How to troubleshoot the “bad request the browser (or proxy) sent a request that this server could not understand..” The problem appears when I try to operate the following program:
<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>
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)
The cause:
This error happened due to
BadRequestKeyError
accessed to a key which did not exist withinrequest.form
.Solution:
You have to key uploaded files under
request.files
dictionary but not underrequest.form
. You also have to delete the loop as the value keyed under u_img is an instance iterable.