Forked from JensRantil/custom_schematics_type.py
Last active
December 18, 2015 22:38
-
-
Save lkraider/5855463 to your computer and use it in GitHub Desktop.
Demonstrating the convert -> validate -> primitive structure
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
#!/bin/env python2.7 | |
from schematics.models import Model | |
from schematics.types import StringType | |
from schematics.exceptions import ValidationError | |
class EventType(StringType): | |
DIVIDER = ':' | |
def convert(self, value): | |
if not isinstance(value, tuple): | |
value = super(EventType, self).convert(value) | |
value = value.split(self.DIVIDER) | |
return tuple(str(v) for v in value) | |
def validate_event(self, value, *a, **kw): | |
if len(value) != 2: | |
raise ValidationError('Not a valid Event ID: {}'.format(value)) | |
def to_primitive(self, value): | |
return self.DIVIDER.join(value) | |
class Event(Model): | |
id = EventType(required=True) | |
if __name__ == '__main__': | |
# initialize from string | |
event = Event({'id': '00:1001'}) | |
event.validate() | |
print event.serialize() | |
# set id from tuple | |
event.id = (1,2) | |
event.validate() | |
print event.serialize() | |
# invalid string | |
try: | |
event.id = 'hello' | |
event.validate() | |
except ValidationError as error: | |
print error.message | |
# invalid tuple | |
try: | |
event.id = (1,2,3) | |
event.validate() | |
except ValidationError as error: | |
print error.message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: