Changeset 5313 for main/waeup.sirp/branches/ulif-fasttables/src/waeup/sirp
- Timestamp:
- 26 Jul 2010, 12:32:53 (14 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
main/waeup.sirp/branches/ulif-fasttables/src/waeup/sirp/utils/converters.py
r4920 r5313 1 1 """Converters for zope.schema-based datatypes. 2 2 """ 3 import datetime 3 4 import grok 4 5 from zope.component import getMultiAdapter … … 8 9 except ImportError: 9 10 from zope.browser.interfaces import ITerms 10 from zope.schema.interfaces import IBool, IText, IInt, IChoice 11 from zope.schema.interfaces import IBool, IText, IInt, IChoice, IDate 11 12 from waeup.sirp.interfaces import ISchemaTypeConverter 12 13 … … 52 53 53 54 def toString(self, value, strict=True): 55 """Convert given `value` to string according to assigned field type. 56 """ 54 57 if strict: 55 58 self.context.validate(value) … … 164 167 return super(ChoiceConverter, self).toString(value=value, 165 168 strict=strict) 169 170 class DateConverter(Converter): 171 """A converter for zope.schema.IDate fields. 172 173 Converts date to string and vice versa. Stringified dates are 174 expected in format ``YYYY-MM-DD``. 175 176 To support at least some other formats, we accept for conversion 177 from string also the following formats: 178 179 * ``YYYY/MM/DD`` 180 181 * ``DD/MM/YYYY`` 182 183 * ``D/M/YYYY`` 184 185 * ``DD.MM.YYYY`` 186 187 * ``D.M.YYYY`` 188 189 When converting to strings, always 'YYYY-MM-DD' is returned. 190 191 For convenience, when converting from strings also string data 192 separated by space is stripped before processing. Therefore 193 strings like '1990-04-01 12:12:01 GMT +1' will also work. 194 """ 195 grok.context(IDate) 196 grok.provides(ISchemaTypeConverter) 197 198 #: List of supported date formats in `strftime()` notation. 199 formats = ['%Y-%m-%d', '%Y/%m/%d' , '%d/%m/%Y', '%D/%M/%Y', 200 '%d.%m.%Y', '%D.%M.%Y'] 201 202 def _convertValueFromString(self, string): 203 orig_string = string 204 if string is NONE_STRING_VALUE: 205 string = None 206 if string is None: 207 return None 208 value = None 209 if ' ' in string: 210 string = string.split(' ')[0] 211 for format in self.formats: 212 try: 213 value = datetime.datetime.strptime(string, format) 214 break 215 except ValueError: 216 pass 217 if value is None: 218 raise ValueError( 219 'Cannot convert to date: %s. Use YYYY-MM-DD.' % 220 orig_string) 221 value = value.date() 222 return value 223 224 def _convertValueToString(self, value): 225 return datetime.date.strftime(value, '%Y-%m-%d')
Note: See TracChangeset for help on using the changeset viewer.