繁体   English   中英

Flask sqlAlchemy 验证问题与flask_Marshmallow

[英]Flask sqlAlchemy validation issue with flask_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') 生成的异常,但看起来并非如此。

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

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. - 验证与 schema.load() 一起使用
  4. - 我想知道如何向输入添加比我使用的更复杂的验证?
  5. - 这是一个很好的模式,可以做哪些改进?

谢谢

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

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

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." ] }

或许看看:

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

您可能会为您的AssertionError注册一个handler

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM