3

I am using Flask-Restless for creating /api/v1/candidate. There I have used 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

Note: I have written validate_required_field decorator to avoid code repetition.

When I POST data to /api/v1/candidate with empty phone column, it validates it right and gives me error

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

But when I pass empty first_name column, same thing does not happen :(

What am I doing wrong? Please help

Hussain
  • 5,057
  • 6
  • 45
  • 71

1 Answers1

0

You duplicated your function validate_first_name for both phone and first_name fields.

Tien Hoang
  • 673
  • 1
  • 7
  • 20