Getting "werkzeug.exceptions.BadRequestKeyError: 400 Bad Request" Upon Creating Form on Python Flask REST API
Getting "werkzeug.exceptions.BadRequestKeyError: 400 Bad Request" Upon Creating Form on Python Flask REST API
我正在学习 Python Flask 并学习这门课程,它教我用它构建 RESTful API。
现在,我正在尝试使用 request.form 通过其“/register”路由向用户请求信息(提交),但是在使用 Postman 测试其 POST 请求时我得到 raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: 浏览器(或代理)发送了该服务器无法理解的请求。
键错误:'email'.
Error as depicted in Postman
POST Request as shown in Postman
我在这里查看了其他看起来有类似问题的帖子,但其中一些也包含 HTML(令人困惑!)或者所提出的解决方案似乎建议使用 .get(),我已经尝试过但是虽然它可以防止 400 发生,但它会绕过任何表单填写(这不是我想要的)。
相关路线如下:
@app.route('/register', methods=['POST'])
def register():
email = request.form['email']
test = User.query.filter_by(email=email).first()
if test:
return jsonify(message='That email already exists.'), 409
else:
first_name = request.form['first_name']
last_name = request.form['last_name']
password = request.form['password']
user = User(first_name=first_name, last_name=last_name, email=email, password=password)
db.session.add(user)
db.session.commit()
return jsonify(message="User created successfully."), 201
以下是此文件中到目前为止使用的所有代码;称为 'app.py'(也有 SQLAlchemy、OS、Flask Marshmallow):
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Float
import os
from flask_marshmallow import Marshmallow
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'planets.db')
db = SQLAlchemy(app)
ma = Marshmallow(app)
@app.cli.command('db_create')
def db_create():
db.create_all()
print('Database created!')
@app.cli.command('db_drop')
def db_drop():
db.drop_all()
print('Database dropped!')
@app.cli.command('db_seed')
def db_seed():
mercury = Planet(planet_name='Mercury',
planet_type='Class D',
home_star='Sol',
mass=2.258e23,
radius=1516,
distance=35.98e6)
venus = Planet(planet_name='Venus',
planet_type='Class K',
home_star='Sol',
mass=4.867e24,
radius=3760,
distance=67.24e6)
earth = Planet(planet_name='Earth',
planet_type='Class M',
home_star='Sol',
mass=5.972e24,
radius=3959,
distance=92.96e6)
db.session.add(mercury)
db.session.add(venus)
db.session.add(earth)
test_user = User(first_name='William',
last_name='Herschel',
email='test@test.com',
password='P@ssw0rd')
db.session.add(test_user)
db.session.commit()
print('Database seeded!')
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/super_simple')
def super_simple():
return jsonify(message='Hello from the Planetary API.'), 200
@app.route('/not_found')
def not_found():
return jsonify(message='That resource was not found'), 404
@app.route('/parameters')
def parameters():
name = request.args.get('name')
age = int(request.args.get('age'))
if age < 18:
return jsonify(message="Sorry " + name + ", you are not old enough."), 401
else:
return jsonify(message="Welcome " + name + ", you are old enough!")
@app.route('/url_variables/<string:name>/<int:age>')
def url_variables(name: str, age: int):
if age < 18:
return jsonify(message="Sorry " + name + ", you are not old enough."), 401
else:
return jsonify(message="Welcome " + name + ", you are old enough!")
@app.route('/planets', methods=['GET'])
def planets():
planets_list = Planet.query.all()
result = planets_schema.dump(planets_list)
return jsonify(result.data)
@app.route('/register', methods=['POST'])
def register():
email = request.form['email']
test = User.query.filter_by(email=email).first()
if test:
return jsonify(message='That email already exists.'), 409
else:
first_name = request.form['first_name']
last_name = request.form['last_name']
password = request.form['password']
user = User(first_name=first_name, last_name=last_name, email=email, password=password)
db.session.add(user)
db.session.commit()
return jsonify(message="User created successfully."), 201
# database models
class User(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
email = Column(String, unique=True)
password = Column(String)
class Planet(db.Model):
__tablename__ = 'planets'
planet_id = Column(Integer, primary_key=True)
planet_name = Column(String)
planet_type = Column(String)
home_star = Column(String)
mass = Column(Float)
radius = Column(Float)
distance = Column(Float)
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'first_name', 'last_name', 'email', 'password')
class PlanetSchema(ma.Schema):
class Meta:
fields = ('planet_id', 'planet_name', 'planet_type', 'home_star', 'mass', 'radius', 'distance')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
planet_schema = PlanetSchema()
planets_schema = PlanetSchema(many=True)
if __name__ == '__main__':
app.run()
任何关于为什么会发生此错误的见解,以及我如何在仍然允许用户输入电子邮件、first_name 等字段的同时修复它,将不胜感激!
提前致谢。
如果您尝试访问请求中的对象或字段,而客户端尚未在请求中发送字段,则会引发 BadRequest
错误。
看来您在邮递员请求中输入错误。还要确保像这样访问它request.form['']
我正在学习 Python Flask 并学习这门课程,它教我用它构建 RESTful API。
现在,我正在尝试使用 request.form 通过其“/register”路由向用户请求信息(提交),但是在使用 Postman 测试其 POST 请求时我得到 raise exceptions.BadRequestKeyError(key) werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: 浏览器(或代理)发送了该服务器无法理解的请求。 键错误:'email'.
Error as depicted in Postman POST Request as shown in Postman
我在这里查看了其他看起来有类似问题的帖子,但其中一些也包含 HTML(令人困惑!)或者所提出的解决方案似乎建议使用 .get(),我已经尝试过但是虽然它可以防止 400 发生,但它会绕过任何表单填写(这不是我想要的)。
相关路线如下:
@app.route('/register', methods=['POST'])
def register():
email = request.form['email']
test = User.query.filter_by(email=email).first()
if test:
return jsonify(message='That email already exists.'), 409
else:
first_name = request.form['first_name']
last_name = request.form['last_name']
password = request.form['password']
user = User(first_name=first_name, last_name=last_name, email=email, password=password)
db.session.add(user)
db.session.commit()
return jsonify(message="User created successfully."), 201
以下是此文件中到目前为止使用的所有代码;称为 'app.py'(也有 SQLAlchemy、OS、Flask Marshmallow):
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Float
import os
from flask_marshmallow import Marshmallow
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'planets.db')
db = SQLAlchemy(app)
ma = Marshmallow(app)
@app.cli.command('db_create')
def db_create():
db.create_all()
print('Database created!')
@app.cli.command('db_drop')
def db_drop():
db.drop_all()
print('Database dropped!')
@app.cli.command('db_seed')
def db_seed():
mercury = Planet(planet_name='Mercury',
planet_type='Class D',
home_star='Sol',
mass=2.258e23,
radius=1516,
distance=35.98e6)
venus = Planet(planet_name='Venus',
planet_type='Class K',
home_star='Sol',
mass=4.867e24,
radius=3760,
distance=67.24e6)
earth = Planet(planet_name='Earth',
planet_type='Class M',
home_star='Sol',
mass=5.972e24,
radius=3959,
distance=92.96e6)
db.session.add(mercury)
db.session.add(venus)
db.session.add(earth)
test_user = User(first_name='William',
last_name='Herschel',
email='test@test.com',
password='P@ssw0rd')
db.session.add(test_user)
db.session.commit()
print('Database seeded!')
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/super_simple')
def super_simple():
return jsonify(message='Hello from the Planetary API.'), 200
@app.route('/not_found')
def not_found():
return jsonify(message='That resource was not found'), 404
@app.route('/parameters')
def parameters():
name = request.args.get('name')
age = int(request.args.get('age'))
if age < 18:
return jsonify(message="Sorry " + name + ", you are not old enough."), 401
else:
return jsonify(message="Welcome " + name + ", you are old enough!")
@app.route('/url_variables/<string:name>/<int:age>')
def url_variables(name: str, age: int):
if age < 18:
return jsonify(message="Sorry " + name + ", you are not old enough."), 401
else:
return jsonify(message="Welcome " + name + ", you are old enough!")
@app.route('/planets', methods=['GET'])
def planets():
planets_list = Planet.query.all()
result = planets_schema.dump(planets_list)
return jsonify(result.data)
@app.route('/register', methods=['POST'])
def register():
email = request.form['email']
test = User.query.filter_by(email=email).first()
if test:
return jsonify(message='That email already exists.'), 409
else:
first_name = request.form['first_name']
last_name = request.form['last_name']
password = request.form['password']
user = User(first_name=first_name, last_name=last_name, email=email, password=password)
db.session.add(user)
db.session.commit()
return jsonify(message="User created successfully."), 201
# database models
class User(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
email = Column(String, unique=True)
password = Column(String)
class Planet(db.Model):
__tablename__ = 'planets'
planet_id = Column(Integer, primary_key=True)
planet_name = Column(String)
planet_type = Column(String)
home_star = Column(String)
mass = Column(Float)
radius = Column(Float)
distance = Column(Float)
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'first_name', 'last_name', 'email', 'password')
class PlanetSchema(ma.Schema):
class Meta:
fields = ('planet_id', 'planet_name', 'planet_type', 'home_star', 'mass', 'radius', 'distance')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
planet_schema = PlanetSchema()
planets_schema = PlanetSchema(many=True)
if __name__ == '__main__':
app.run()
任何关于为什么会发生此错误的见解,以及我如何在仍然允许用户输入电子邮件、first_name 等字段的同时修复它,将不胜感激!
提前致谢。
如果您尝试访问请求中的对象或字段,而客户端尚未在请求中发送字段,则会引发 BadRequest
错误。
看来您在邮递员请求中输入错误。还要确保像这样访问它request.form['']