FLAASK_MARSHMALLOW的flask sqlAlChemy验证问题 [英] Flask sqlAlchemy validation issue with flask_Marshmallow

查看:33
本文介绍了FLAASK_MARSHMALLOW的flask sqlAlChemy验证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用flask_marshmallow进行输入验证,再加上scheme.load(),我无法捕获模型中由@validate修饰符生成的错误

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

=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"
}

我原以为该错误会捕获@Validate(‘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')
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. -在我的模型中,我使用棉花糖(而不是flask_marshmallow)进行验证
  3. -验证使用schema.load()
  4. -我想知道如何才能向输入添加比我使用的更复杂的验证?
  5. -这是一个很好的模式吗,可以做哪些改进?

谢谢

这篇关于FLAASK_MARSHMALLOW的flask sqlAlChemy验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆