Skip to content

Instantly share code, notes, and snippets.

@lkraider
Forked from JensRantil/custom_schematics_type.py
Last active December 18, 2015 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lkraider/5855463 to your computer and use it in GitHub Desktop.
Save lkraider/5855463 to your computer and use it in GitHub Desktop.
Demonstrating the convert -> validate -> primitive structure
#!/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
@lkraider
Copy link
Author

output:

{'id': '00:1001'}
{'id': '1:2'}
{'id': ["Not a valid Event ID: ('hello',)"]}
{'id': ["Not a valid Event ID: ('1', '2', '3')"]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment