Last active
December 20, 2015 14:19
-
-
Save hirokiky/6145543 to your computer and use it in GitHub Desktop.
A Class handling choices and it's schema type.
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
import colandar | |
class InvalidChoice(Exception): | |
pass | |
class Choice(str): | |
"""Class for choice value of some schema | |
""" | |
choices = () | |
IsInvalidChoice = InvalidChoice | |
def __init__(self, string=''): | |
self.validate(string) | |
self.choice = string | |
@property | |
def choice_keys(self): | |
return [choice[0] for choice in self.choices] | |
def validate(self, value): | |
if not value in self.choice_keys: | |
raise self.IsInvalidChoice | |
class LikingChoice(Choice): | |
choices = (('like', 'Like'), | |
('soso', 'Soso'), | |
('unlike', 'Unlike')) | |
int_mapping = { | |
'like': 1, | |
'soso': 0, | |
'unlike': -1, | |
} | |
def __int__(self): | |
return self.int_mapping[self] | |
class ChoiceSchemaType(colander.String): | |
def __init__(self, choice_class, encoding=None): | |
self.choice_class = choice_class | |
self.encoding = encoding | |
def deserialize(self, node, cstruct): | |
value = super(Choice, self).deserialize(node, cstruct) | |
try: | |
choice = self.choice_class(value) | |
except self.choice_class.IsInvalidChoice: | |
choices = ', '.join(['%s' % x for x in self.choice_class.choices]) | |
err = colander._('"${val}" is not one of ${choices}', | |
mapping={'val':value, 'choices':choices}) | |
raise colander.Invalid(node, err) | |
return choice |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment