【问题标题】:flask-restless validation_exceptions not working for few column in flask-sqlalchemy modelsflask-restless validation_exceptions 不适用于 flask-sqlalchemy 模型中的少数列
【发布时间】:2015-07-29 19:09:59
【问题描述】:

我正在使用 Flask-Restless 来创建 /api/v1/candidate。那里我用过validation_exceptions=[MyValidationError]

# ... code snippet from my models.py ....

class MyValidationError(Exception):
    pass

def validate_required_field(method):
    def wrapper(self, key, string):
        if not string:
            exception = MyValidationError()
            exception.errors = {key: 'must not be empty'}
            raise exception
        return method(self, key, string)
    return wrapper

class Candidate(db.Model):

    __tablename__ = 'candidate'

    # ... snip ...
    first_name = db.Column(db.String(100), nullable=False)  
    phone = db.Column(db.String(20), nullable=False, unique=True)
    # ... snip ...

    @orm.validates('first_name')
    @validate_required_field
    def validate_first_name(self, key, string):
        return string

    @orm.validates('phone')
    @validate_required_field
    def validate_first_name(self, key, string):
        return string

注意:我写了validate_required_field装饰器以避免代码重复。

当我使用空 phone 列将数据发布到 /api/v1/candidate 时,它会验证它是否正确并给我错误

{
    "validation_errors": {
        "phone": "must not be empty"
    }
}

但是当我传递空的 first_name 列时,同样的事情不会发生:(

我做错了什么?请帮忙

【问题讨论】:

    标签: python flask-sqlalchemy flask-restless


    【解决方案1】:

    您为 phonefirst_name 字段复制了函数 validate_first_name

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 2018-06-18
      • 2013-10-16
      • 2021-03-09
      • 2013-02-06
      • 2014-12-03
      • 2013-02-07
      • 2023-03-17
      • 2016-01-14
      相关资源
      最近更新 更多