Commits

imbolc committed a95c610

add ChoiceProperty

  • Participants
  • Parent commits ab7e2c0

Comments (0)

Files changed (4)

     ...     messages    = tl.CompressedDumpProperty(default=[])
     ...     is_active   = tl.BooleanProperty(default=True)
     ...     created     = tl.DateTimeProperty(index=True) # indexed field
+    ...     choice      = tl.ChoiceProperty([('1', 'first'), ('2', 'second')])
     ...
     ...     __file__ = 'var/readme_test.tclite'
     ...     #__host__ = 'localhost:1978'
     >>> User(username='Foo', key='user-foo').save()  # set custom key name
     >>> User.get('user-foo').username  # get by keyname
     u'Foo'
+
 from setuptools import setup
 
 PACKAGE = 'tclite'
-VERSION = '0.3'
+VERSION = '0.32'
 
 readme = open(os.path.join(os.path.dirname(__file__), 'README')).read()
 
 
     setup(
         version = VERSION,
-        description = 'Object wrapper for tokyo cabinet / tokyo python',
+        description = 'Object wrapper for tokyo cabinet / tokyo tyrant',
         long_description = readme,
         author = 'Imbolc',
         author_email = 'imbolc@imbolc.name',
         package_data = {'tclite': data_files},
 
         license = "BSD",
-        keywords = "tc, tokyo, cabinet, orm, model, document, non-relational, document-oriented, key/value",
+        keywords = "tc, tokyo, cabinet, tyrant, nosql, orm, model, document, non-relational, document-oriented, key/value",
         classifiers=[
             'Development Status :: 4 - Beta',
             'License :: OSI Approved :: BSD License',

File tclite/__init__.py

         return value
 
 
-class Error(Exception):
-    pass
-
-
 class Model(object):
     __file__ = None
     __host__ = None

File tclite/properties.py

     },
 }    
 
+class Error(Exception):
+    pass
 
 class KeyProperty(object):
     index = False
         return s.decode(self.internal_encoding, self.encoding_errors)
 
 
+class ChoiceProperty(UnicodeProperty):
+    '''
+        >>> choices = [
+        ...     ('1', 'first'),
+        ...     ('2', 'second'),
+        ... ]
+        >>> obj = ChoiceProperty(choices)
+        >>> obj.dumps('first')
+        '1'
+        >>> obj.loads('2')
+        'second'
+    '''
+    def __init__(self, choices, *args, **kwargs):
+        self.set_choices(choices)
+        super(self.__class__, self).__init__(*args, **kwargs)
+            
+    def set_choices(self, choices):
+        self.choices = []
+        self._choices_kv = {}
+        self._choices_vk = {}
+        for item in choices:
+            k, v = item if isinstance(item, (tuple, list)) else (item, item)
+            k = unicode(k)
+            if k in self._choices_kv:
+                raise Error(u'Duplicate choice key: %s' % k)
+            self.choices.append((k, v))
+            self._choices_kv[k] = v
+            self._choices_vk[v] = k
+
+    def dumps(self, value):
+        try:
+            value = self._choices_vk[value]
+        except KeyError:
+            raise Error(u'Unknown choice value. Allowed: %s' 
+                % ', '.join(self._choices_vk.keys()))
+        return super(self.__class__, self).dumps(value)
+
+    def loads(self, value):
+        ret = super(self.__class__, self).loads(value)
+        try:
+            ret = self._choices_kv[ret]
+        except KeyError:
+            raise Error(u'Unknown choice key. Allowed: %s' 
+                % ', '.join(self._choices_kv.keys()))
+        return ret
+
+
 class IntegerProperty(BaseProperty):
     '''
         >>> value = 10