我有一个接受get和post请求的flask视图,我使用Pydantic使用flask- Pydantic进行请求体验证。对于post请求,它可以正常工作,但对于get请求,它会返回一个415错误,并带有此消息-请求中{"detail":"不支持的媒体类型"。'application/json'是必需的。"}
@bp.route('/login', methods=('GET', 'POST',))
@validate()
def login(body: UserLoginSchema):
if request.method == 'POST':
existing_user = UserListSchema.from_orm(
db_session.query(UserModel.id, UserModel.email, UserModel.first_name, UserModel.last_name,
UserModel.is_admin, UserModel.is_verified, UserModel.password)
.filter_by(email=body.email, is_active=True).first()
)
if existing_user:
if check_password_hash(existing_user.password, body.password):
session.clear()
session['user'] = str(existing_user.json())
return redirect(url_for('index'))
flash('Invalid username or password')
return render_template('auth/login.html')
我已经尝试将函数中的查询参数设置为空字符串或None,它没有帮助。
我删除了flask-pydantic包并手动初始化了pydantic模型,因为flask-pydantic的验证装饰器要求将content-type头设置为application/json.
@bp.route('/login', methods=('GET', 'POST',))
def login():
if request.method == 'POST':
body = auth_schemas.UserLoginSchema(**request.form)
existing_user = auth_schemas.UserListSchema.from_orm(
db_session.query(UserModel.id, UserModel.email, UserModel.first_name, UserModel.last_name,
UserModel.is_admin, UserModel.is_verified, UserModel.password)
.filter_by(email=body.email, is_active=True).first()
)
if existing_user:
if check_password_hash(existing_user.password, body.password):
session.clear()
session['user'] = str(existing_user.json())
return redirect(url_for('index'))
flash('Invalid username or password')
return render_template('auth/login.html')
然后我创建了一个ValidationError初始化pydantic模型类时捕获验证错误的处理程序。
from pydantic import ValidationError
@app.errorhandler(ValidationError)
def handle_pydantic_validation_errors(e):
return jsonify(e.errors())