Flask_Marshmallow的烧瓶sqlAlchemy验证问题

时间:2018-12-30 19:46:50

标签: python exception flask-sqlalchemy marshmallow

使用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')生成的异常,但看起来并非如此。

5 个答案:

答案 0 :(得分:0)

也许看看:

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

您可能会为handler注册一个AssertionError

答案 1 :(得分:0)

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

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') 公司类(资源):

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. -在我的模型中,我使用了蛋白软糖(而不是flask_marshmallow)进行验证
  3. -Validation与schema.load()一起使用
  4. -我想知道如何为输入添加比我使用的更复杂的验证?
  5. -这是一个很好的模式,可以做哪些改进?

谢谢

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

我要做的是代替棉花糖的负荷

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 :(得分:0)

我希望这还不算太晚, 以下示例是一个将错误显示在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." ] }