Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获得;werkzeug.exceptions.BadRequestKeyError:400错误请求“;在Python Flask REST API上创建表单时_Rest_Flask_Post_Http Status Code 400_Marshmallow - Fatal编程技术网

获得;werkzeug.exceptions.BadRequestKeyError:400错误请求“;在Python Flask REST API上创建表单时

获得;werkzeug.exceptions.BadRequestKeyError:400错误请求“;在Python Flask REST API上创建表单时,rest,flask,post,http-status-code-400,marshmallow,Rest,Flask,Post,Http Status Code 400,Marshmallow,我正在学习PythonFlask并学习这门课程,这门课程教我如何用它构建RESTfulAPI 现在,我正试图使用request.form通过其“/register”路由向用户请求信息(提交),但是在使用Postman测试其POST请求时,我得到了raise异常。BadRequestKeyError(key) werkzeug.exceptions.BadRequestKeyError:400错误请求:浏览器(或代理)发送了此服务器无法理解的请求。 KeyError:“电子邮件” 我在这里看到

我正在学习PythonFlask并学习这门课程,这门课程教我如何用它构建RESTfulAPI

现在,我正试图使用request.form通过其“/register”路由向用户请求信息(提交),但是在使用Postman测试其POST请求时,我得到了raise异常。BadRequestKeyError(key) werkzeug.exceptions.BadRequestKeyError:400错误请求:浏览器(或代理)发送了此服务器无法理解的请求。 KeyError:“电子邮件”

我在这里看到过其他有类似问题的帖子,但其中有些帖子也包含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棉花糖):

从烧瓶导入烧瓶,jsonify,请求
从flask_sqlalchemy导入sqlalchemy
从sqlalchemy导入列、整数、字符串、浮点
导入操作系统
从美国进口棉花糖
app=烧瓶(名称)
basedir=os.path.abspath(os.path.dirname(_文件__))
app.config['SQLALCHEMY\u DATABASE\u URI']=“sqlite://'+os.path.join(basedir,'planets.db')
db=SQLAlchemy(应用程序)
ma=棉花糖(应用程序)
@app.cli.command('db_create')
def db_create():
db.create_all()
打印('已创建数据库!')
@app.cli.command('db\u drop')
def db_drop():
db.drop_all()
打印('数据库已删除!')
@app.cli.command('db\u seed')
def db_seed():
水星=行星(行星名称为水星),
行星_type='classd',
家"星","太阳",,
质量=2.258e23,
半径=1516,
距离=35.98e6)
金星=行星,
行星_type='classk',
家"星","太阳",,
质量=4.867e24,
半径=3760,
距离=67.24e6)
地球=行星(行星名称=地球),
行星_type='classm',
家"星","太阳",,
质量=5.972e24,
半径=3959,
距离=92.96e6)
db.session.add(mercury)
db.session.add(维纳斯)
db.session.add(地球)
test_user=user(first_name='William',
姓class='Herschel',
电子邮件test@test.com',
密码='P@ssw0rd')
db.session.add(测试用户)
db.session.commit()
打印('数据库种子!')
@应用程序路径(“/”)
def hello_world():
返回“你好,世界!”
@应用程序路径(“/super_simple”)
def super_simple():
返回jsonify(message='Hello from the Planetary API'),200
@应用程序路径(“/未找到”)
未找到def_():
返回jsonify(message='That resource not found'),404
@app.route(“/parameters”)
def参数():
name=request.args.get('name')
age=int(request.args.get('age'))
如果年龄<18岁:
返回jsonify(message=“Sorry”+name+”,您还不够大。”),401
其他:
return jsonify(message=“Welcome”+name+”,您已经足够大了!)
@app.route('/url_variables/'))
def url_变量(名称:str,年龄:int):
如果年龄<18岁:
返回jsonify(message=“Sorry”+name+”,您还不够大。”),401
其他:
return jsonify(message=“Welcome”+name+”,您已经足够大了!)
@app.route('/planets',methods=['GET'])
定义行星():
planets\u list=Planet.query.all()
结果=planets\u schema.dump(planets\u列表)
返回jsonify(result.data)
@app.route('/register',methods=['POST'])
def寄存器():
电子邮件=请求。表格['email']
test=User.query.filter\u by(email=email).first()
如果测试:
返回jsonify(message='那封电子邮件已经存在'),409
其他:
first\u name=请求。表单['first\u name']
last_name=请求。表单['last_name']
密码=请求。表单['password']
用户=用户(名字=名字,姓氏=姓氏,电子邮件=电子邮件,密码=密码)
db.session.add(用户)
db.session.commit()
返回jsonify(message=“User created successfully”),201
#数据库模型
类用户(db.Model):
__tablename_uu='users'
id=列(整数,主键=True)
第一个名称=列(字符串)
姓氏=列(字符串)
email=列(字符串,unique=True)
密码=列(字符串)
行星类(db.型号):
__tablename_uu=‘行星’
行星标识=列(整数,主键=真)
行星名称=列(字符串)
行星_类型=列(字符串)
home\u star=列(字符串)
质量=柱(浮动)
半径=列(浮动)
距离=列(浮动)
类UserSchema(ma.Schema):
类元:
字段=('id'、'first\u name'、'last\u name'、'email'、'password')
类PlanetSchema(ma.Schema):
类元:
字段=(‘行星id’、‘行星名称’、‘行星类型’、‘主恒星’、‘质量’、‘半径’、‘距离’)
user_schema=UserSchema()
users\u schema=UserSchema(many=True)
planet_schema=PlanetSchema()
行星模式=行星模式(多个=真)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.run()
如果您能了解发生此错误的原因,以及我如何在允许用户输入电子邮件、名字等字段的同时修复此错误,我们将不胜感激


提前感谢。

当客户端尚未发送请求中的字段时,如果您尝试从请求中访问对象或字段,则会引发
BADDREQUEST
错误


看来你在邮递员的要求上打错了字。另外,请确保按此
请求访问它。表单['']

您好,请显示您的html以注册routeHi@CodeYard,据我所知,此处未使用html。我在用装有PyCharm的烧瓶来做cr
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()