Changeset 4810 for waeup/branches/ulif-importers/src
- Timestamp:
- 14 Jan 2010, 17:28:58 (15 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
waeup/branches/ulif-importers/src/waeup/utils/converters.py
r4805 r4810 2 2 """ 3 3 import grok 4 from zope.schema.interfaces import IText 4 from zope.component import getMultiAdapter 5 from zope.publisher.browser import TestRequest 6 try: 7 from zope.app.form.browser.interfaces import ITerms 8 except ImportError: 9 from zope.browser.interfaces import ITerms 10 from zope.schema.interfaces import IText, IInt, IChoice 5 11 from waeup.interfaces import ISchemaTypeConverter 6 12 7 class TextConverter(grok.Adapter): 13 class Converter(grok.Adapter): 14 """Base for string-or-none to zope.schema field converters. 15 """ 16 grok.baseclass() 17 grok.provides(ISchemaTypeConverter) 18 19 def __init__(self, context): 20 """Create a converter with context, a zope.schema.Field, as context. 21 """ 22 self.context = context 23 24 def _convertValueFromString(self, string): 25 """You must at least override this method to build a working 26 converter. 27 """ 28 raise NotImplementedError('method not implemented') 29 30 def fromString(self, string=None, strict=True): 31 """Convert ``string`` to value according to assigned field type. 32 """ 33 result = None 34 if string is None: 35 if self.context.required is True: 36 result = self.context.default 37 else: 38 result = self.context.missing_value 39 else: 40 result = self._convertValueFromString(string) 41 if strict: 42 self.context.validate(result) 43 return result 44 45 class TextConverter(Converter): 8 46 grok.context(IText) 47 grok.provides(ISchemaTypeConverter) 48 49 def _convertValueFromString(self, string): 50 return unicode(string) 51 52 class IntConverter(Converter): 53 grok.context(IInt) 54 grok.provides(ISchemaTypeConverter) 55 56 def _convertValueFromString(self, string): 57 return int(string) 58 59 class ChoiceConverter(Converter): 60 grok.context(IChoice) 9 61 grok.provides(ISchemaTypeConverter) 10 62 11 63 def __init__(self, context): 12 64 self.context = context 13 14 def convert(self, string=None): 15 return unicode(string) 16 65 try: 66 self.terms = getMultiAdapter( 67 (self.context.source, TestRequest()), ITerms) 68 except: 69 pass 70 71 def _convertValueFromString(self, string): 72 try: 73 return self.context.source.getTermByToken(string).value 74 except AttributeError: 75 self.terms = getMultiAdapter( 76 (self.context.source, TestRequest()), ITerms) 77 return self.terms.getValue(string) 78
Note: See TracChangeset for help on using the changeset viewer.