3

我正在使用 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了装饰器来避免代码重复。

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

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

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

我究竟做错了什么?请帮忙

4

1 回答 1

0

validate_first_namephonefirst_name字段复制了函数。

于 2017-03-06T18:16:22.080 回答