-
-
Save mikitebeka/337067 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ValidatorException(Exception): pass | |
| class Validated: | |
| __fields__ = {} # field -> validator list | |
| def validate(self): | |
| errors = [] | |
| for field, validators in self.__fields__.iteritems(): | |
| if not hasattr(self, field): | |
| errors.append("field %s missing" % field) | |
| continue | |
| field_errors = [] | |
| value = getattr(self, field) | |
| for validator in validators: | |
| try: | |
| validator(value) | |
| except Exception, e: | |
| field_errors.append(str(e)) | |
| if field_errors: | |
| errors.append("%s: %s" % (field, ", ".join(field_errors))) | |
| if errors: | |
| raise ValidatorException(errors) | |
| @classmethod | |
| def is_positive(cls, n): | |
| assert (type(n) in (int, long, float)) and (n > 0), "not positive" | |
| class Tunnel(Validated): | |
| __fields__ = { | |
| "status" : [Validated.is_positive] | |
| } | |
| status = 0 | |
| host = 0 | |
| type = 0 | |
| def save(self): | |
| self.validate() | |
| # ... | |
| t = Tunnel() | |
| t.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment