【问题标题】:Flask sqlAlchemy validation issue with flask_MarshmallowFlask sqlAlchemy 验证问题与 flask_Marshmallow
【发布时间】:2024-04-16 06:30:02
【问题描述】:

使用 flask_marshmallow 进行输入验证,通过 scheme.load() ,我无法捕获模型中 @validates 装饰器生成的错误

我在资源中捕获了结果和错误,但错误会直接发送给用户

==========model.py===========

```python

from sqlalchemy.orm import validates

from sqlalchemy import Column, ForeignKey, Integer, String, DateTime
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.sql import func

from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy.orm import joinedload


db = SQLAlchemy()
ma = Marshmallow()

class Company(db.Model):

    __tablename__ = "company"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), nullable=False)
    addressLine1 = db.Column(db.String(250), nullable=False)
    addressLine2 = db.Column(db.String(250), nullable=True)
    city = db.Column(db.String(250), nullable=False)
    state = db.Column(db.String(250), nullable=False)
    zipCode = db.Column(db.String(10), nullable=False)
    logo = db.Column(db.String(250), nullable=True)
    website = db.Column(db.String(250), nullable=False)
    recognition = db.Column(db.String(250), nullable=True)
    vision = db.Column(db.String(250), nullable=True)
    history = db.Column(db.String(250), nullable=True)
    mission = db.Column(db.String(250), nullable=True)
    jobs = relationship("Job", cascade="all, delete-orphan")

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    @validates('name')
    def validate_name(self, key, name):
        print("=====inside validate_name=======")
        if not name:
            raise AssertionError('No Company name provided')

        if Company.query.filter(Company.name == name).first():
            raise AssertionError('Company name is already in use')

        if len(name) < 4 or len(name) > 120:
            raise AssertionError('Company  name must be between 3 and 120 characters')

        return name

```

==========schemas_company.py==============

```python
from ma import ma
from models.model import Company


class CompanySchema(ma.ModelSchema):

    class Meta:
        model = Company
```

=============resources_company.py

```python
from schemas.company import CompanySchema
company_schema = CompanySchema(exclude='jobs')


COMPANY_ALREADY_EXIST = "A company with the same name already exists"
COMPANY_CREATED_SUCCESSFULLY = "The company was sucessfully created"


@api.route('/company')
class Company(Resource):

    def post(self, *args, **kwargs):
        """ Creating a new Company """
        data = request.get_json(force=True)
        schema = CompanySchema()
        if data:
            logger.info("Data got by /api/test/testId methd %s" % data)


            # Validation with schema.load() OPTION_2
            company, errors = schema.load(data)
            print(company)
            print(errors)

            if errors:
                return {"errors": errors}, 422
            company.save_to_db()
            return {"message": COMPANY_CREATED_SUCCESSFULLY}, 201

```

===========请求==========

这是来自用户的 POST 请求

{
    "name": "123",
    "addressLine1": "400 S Royal King Ave",
    "addressLine2": "Suite 356",
    "city": "Miami",
    "state": "FL",
    "zipCode": "88377",
    "logo": "This is the logo",
    "website": "http://www.python.com",
    "recognition": "Most innovated company in the USA 2018-2019",
    "vision": "We want to change for better all that needs to be changed",
    "history": "Created in 2016 with the objective of automate all needed process",
    "mission": " Our mission is to find solutions to old problems"
}

====问题描述======

上述 POST 请求根据 model.py 中的 validate_name 函数生成 AssertionError 异常,如下所示:

File "code/models/model.py", line 95, in validate_name
raise AssertionError('Company  name must be between 3 and 120 characters')
AssertionError: Company  name must be between 3 and 120 characters
127.0.0.1 - - [30/Dec/2018 13:44:58] "POST /api/company HTTP/1.1" 500 -

所以返回给用户的响应就是这个无用的错误信息

{
    "message": "Internal Server Error"
}

我的问题是:

我必须怎么做才能将引发的 AssertionError 消息而不是这个丑陋的错误消息发送给用户?

AssertionError message
{
   "message": "Company  name must be between 3 and 120 characters" 
}

Exception 
{
    "message": "Internal Server Error"
}

我以为错误会捕获@validates('name') 生成的异常,但看起来情况并非如此。

【问题讨论】:

    标签: python exception flask-sqlalchemy marshmallow


    【解决方案1】:

    我找到了解决问题的方法。 我将架构更改如下:

    from ma import ma
    from models.model import Company
    
    from marshmallow import fields, validate
    
    
    class CompanySchema(ma.ModelSchema):
    
        name = fields.Str(required=True, validate=[validate.Length(min=4, max=250)])
        addressLine1 = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
        addressLine2 = fields.Str(required=False, validate=[validate.Length(max=250)])
        city = fields.Str(required=True, validate=[validate.Length(min=5, max=100)])
        state = fields.Str(required=True, validate=[validate.Length(min=2, max=10)])
        zipCode = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
        logo = fields.Str(required=False, validate=[validate.Length(max=250)])
        website = fields.Str(required=True, validate=[validate.Length(min=5, max=250)])
        recognition = fields.Str(required=False, validate=[validate.Length(max=250)])
        vision = fields.Str(required=False, validate=[validate.Length(max=250)])
        history = fields.Str(required=False, validate=[validate.Length(max=250)])
        mission = fields.Str(required=False, validate=[validate.Length(max=250)])
    
        class Meta:
            model = Company
    

    现在我不验证模型中的任何内容,所以我的模型只是

    class Company(db.Model):
    
        __tablename__ = "company"
    
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(250), nullable=False)
        addressLine1 = db.Column(db.String(250), nullable=False)
        addressLine2 = db.Column(db.String(250), nullable=True)
        city = db.Column(db.String(250), nullable=False)
        state = db.Column(db.String(250), nullable=False)
        zipCode = db.Column(db.String(10), nullable=False)
        logo = db.Column(db.String(250), nullable=True)
        website = db.Column(db.String(250), nullable=False)
        recognition = db.Column(db.String(250), nullable=True)
        vision = db.Column(db.String(250), nullable=True)
        history = db.Column(db.String(250), nullable=True)
        mission = db.Column(db.String(250), nullable=True)
        jobs = relationship("Job", cascade="all, delete-orphan")
    
        def save_to_db(self):
            print("=====inside save_to_db=======")
            db.session.add(self)
            db.session.commit()
    

    所以在资源(视图)端点中,我有:

    @api.route('/company')
    class Company(Resource):
    
        def post(self, *args, **kwargs):
            """ Creating a new Company """
            data = request.get_json(force=True)
            schema = CompanySchema()
            if data:
                logger.info("Data got by /api/test/testId method %s" % data)
    
                # Validation with schema.load() OPTION_2
                company, errors = schema.load(data)
                print(company)
    
                if errors:
                    return {"errors": errors}, 422
    
                company.save_to_db()
                return {"message": COMPANY_CREATED_SUCCESSFULLY}, 201
    

    所以现在,当用户提出一个名称长度小于 4 个字符的错误请求时,我可以向用户返回一个漂亮的错误响应,如下所示

    {
        "errors": {
            "name": [
                "Length must be between 4 and 250."
            ]
        }
    }
    

    但是,如果您注意到我这样做的原因以及我使用的“模式”,您将看到以下详细信息

    1. - 使用 flask_marshmallow 进行序列化和反序列化。
    2. -在我的模型中,我使用了 marshmallow(不是 flask_marshmallow)进行验证
    3. -验证适用于 schema.load()
    4. -我想知道如何向输入添加比我使用的验证更复杂的验证?
    5. -这是一个很好的模式,可以做哪些改进?

    谢谢

    【讨论】:

      【解决方案2】:

      我希望这还不算太晚, 下面的示例是一个将错误显示到 api 响应的工作示例。

      诀窍是使用 validate 方法返回错误字典,或者更确切地说是可以向用户显示的错误字典列表。

      from flask import request
      import datetime as dt
      from marshmallow import (
          Schema,RAISE,fields,pprint,validate,ValidationError,post_load)
      from flask_restplus import Api,Resource
      
      app = Flask(__name__)
      api = Api(app, prefix="/api/v1")
      
      class User:
          def __init__(self, name,email,age,permission):
              self.name = name
              self.email = email
              self.age = age
              self.permission = permission
              self.created_at = dt.datetime.utcnow()
      
          def __repr__(self):
              return "User(name={})".format(self.name)
      
      class Userschema(Schema):
          name = fields.Str(required=True,validate=[validate.Length(min=1)])
          email = fields.Email(required=True,validate=[validate.Length(min=1)])
          permission = fields.Str(validate=[validate.OneOf(["read","write","admin"])])
          age = fields.Int(validate=[validate.Range(min=10,max=30)])
      
          @post_load
          def make_user(self,data,**kwargs):
              return User(**data)
      
      users = [] 
      
      
      class UserCollection(Resource):
          def get(self):
              return {"subscriberList":users}
      
          def post(self,*args,**kwargs):
              schema = Userschema()
              data = request.get_json(force=True)
              errors = schema.validate(api.payload)
              if errors:
                  return errors, 422       
              user=schema.load(data)
              result = schema.dump(user)
              users.append(result)
      
              return {"msg": "Subscriber added"},201
      
      
      api.add_resource(UserCollection,'/subscribers')
      
      
      if __name__ == "__main__":
          app.run(debug=True)
      

      请求和响应

      http://localhost:5000/api/v1/subscribers

      帖子正文

      { "name": "derrick", "permission": "esc", "age": 2, "email":"me@gmail" }

      回应

      { "email": [ "Not a valid email address." ], "permission": [ "Must be one of: read, write, admin." ], "age": [ "Must be greater than or equal to 10 and less than or equal to 30." ] }

      【讨论】:

        【解决方案3】:

        我所做的是创建一个方法而不是棉花糖的加载

        def json_loader(schema, json):
            try:
                assert json is not None, "request body is required"
            except AssertionError as assertionError:
                raise InvalidUsage(40001, assertionError.args[0], 400)
            result = schema.load(json)
            if result.errors:
                raise InvalidUsage(40001, result.errors, 400)
            else:
                return result.data
        

        但是,如果使用的是 3.0 版本。他们改变了这部分。这是他们的例子。

        from marshmallow import ValidationError
        
        try:
            result = UserSchema().load({'name': 'John', 'email': 'foo'})
        except ValidationError as err:
            err.messages  # => {'email': ['"foo" is not a valid email address.']}
            valid_data = err.valid_data  # => {'name': 'John'}
        

        https://marshmallow.readthedocs.io/en/3.0/quickstart.html#validation

        【讨论】:

          【解决方案4】:

          我相信您的代码中的错误是您在验证器中提出了AssertionError,而不是棉花糖的ValidationError

          您的答案朝着正确的方向发展,创建了一个使用棉花糖验证器的架构(requiredLength、...)。您可以通过定义其他验证器(字段或架构验证器)来添加自定义验证。

          您可以使用webargs 来验证输入,而不是在视图函数中手动验证。它在内部使用棉花糖,由棉花糖团队维护。

          【讨论】:

          • 感谢您的回复。我会尝试您的解决方案并回复您。也感谢您对使用 webargs 的建议。
          【解决方案5】:

          也许看看:

          http://flask.pocoo.org/docs/1.0/errorhandling/

          您可以为您的AssertionError 注册一个handler

          【讨论】:

          • 感谢您的回复和您的时间。然而,我找到了我将在下面提出的问题的解决方案。但我发现下面的解决方案并不完全是我的想法。我仍然认为下面的解决方案应该有一个很好的解释