Created
March 18, 2010 23:42
-
-
Save mikitebeka/337063 to your computer and use it in GitHub Desktop.
This file contains 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 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: | |
assert 0, errors | |
def is_positive(n): | |
assert (type(n) in (int, long, float)) and (n > 0), "not positive" | |
class Tunnel(Validated): | |
__fields__ = { | |
"status" : [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