我有一个接受 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')
Run Code Online (Sandbox Code Playgroud)
我尝试将函数中的查询参数设置为空字符串或无,但没有帮助。
我删除了flask-pydantic包并手动初始化了pydantic模型,因为flask-pydantic中的验证装饰器需要将内容类型标头设置为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')
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个ValidationError处理程序来在初始化 pydantic 模型类时捕获验证错误。
from pydantic import ValidationError
@app.errorhandler(ValidationError)
def handle_pydantic_validation_errors(e):
return jsonify(e.errors())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2026 次 |
| 最近记录: |