【问题标题】:Flask-Pydantic disable validation on get requestFlask-Pydantic 在获取请求时禁用验证
【发布时间】:2021-07-23 22:33:28
【问题描述】:

我有一个接受 get 和 post 请求的烧瓶视图,我使用 Pydantic 使用 flask-pydantic 进行请求正文验证。它适用于发布请求,但在获取请求时,它会返回带有此消息的 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')

我尝试将函数中的 query 参数设置为空字符串或 None,但没有帮助。

【问题讨论】:

    标签: flask pydantic


    【解决方案1】:

    我删除了 flask-pydantic 包并手动初始化了 pydantic 模型,因为来自 flask-pydantic 的 validate 装饰器需要将 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())
    

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 2022-11-17
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2015-04-20
      • 2020-03-11
      相关资源
      最近更新 更多