Ignore:
Timestamp:
29 Jul 2010, 09:02:24 (14 years ago)
Author:
Henrik Bettermann
Message:

merge changes made in trunk into henrik-experimental-layout

File:
1 edited

Legend:

Unmodified
Added
Removed
  • main/waeup.sirp/branches/henrik-experimental-layout/src/waeup/sirp/utils/converters.py

    r4920 r5330  
    11"""Converters for zope.schema-based datatypes.
    22"""
     3import datetime
    34import grok
    45from zope.component import getMultiAdapter
     
    89except ImportError:
    910    from zope.browser.interfaces import ITerms
    10 from zope.schema.interfaces import IBool, IText, IInt, IChoice
     11from zope.schema.interfaces import IBool, IText, IInt, IChoice, IDate
    1112from waeup.sirp.interfaces import ISchemaTypeConverter
    1213
     
    5253
    5354    def toString(self, value, strict=True):
     55        """Convert given `value` to string according to assigned field type.
     56        """
    5457        if strict:
    5558            self.context.validate(value)
     
    131134    def _convertValueFromString(self, string):
    132135        if self.tokens is not None:
    133             return self.tokens[string]
     136            result = None
     137            try:
     138                result = self.tokens[string]
     139            except KeyError:
     140                # Be gentle...
     141                try:
     142                    result = self.tokens[string.lower()]
     143                    return result
     144                except KeyError:
     145                    tokenlist = (','.join(self.tokens[:2]))
     146                    raise ValueError(
     147                        'The token %s is not valid. Use one of %s, ...' % (
     148                            string, tokenlist))
     149            return result
    134150        if self.terms is not None:
    135151            return self.terms.getValue(string)
    136         return self.context.source.getTermByToken(string).value
     152        result = self.context.source.getTermByToken(string).value
     153        return result
    137154
    138155    def _convertValueToString(self, value):
     
    164181        return super(ChoiceConverter, self).toString(value=value,
    165182                                                     strict=strict)
     183
     184class DateConverter(Converter):
     185    """A converter for zope.schema.IDate fields.
     186
     187    Converts date to string and vice versa. Stringified dates are
     188    expected in format ``YYYY-MM-DD``.
     189
     190    To support at least some other formats, we accept for conversion
     191    from string also the following formats:
     192
     193    * ``YYYY/MM/DD``
     194   
     195    * ``DD/MM/YYYY``
     196   
     197    * ``D/M/YYYY``
     198
     199    * ``DD.MM.YYYY``
     200
     201    * ``D.M.YYYY``
     202
     203    When converting to strings, always 'YYYY-MM-DD' is returned.
     204
     205    For convenience, when converting from strings also string data
     206    separated by space is stripped before processing. Therefore
     207    strings like '1990-04-01 12:12:01 GMT +1' will also work.
     208    """
     209    grok.context(IDate)
     210    grok.provides(ISchemaTypeConverter)
     211
     212    #: List of supported date formats in `strftime()` notation.
     213    formats = ['%Y-%m-%d', '%Y/%m/%d' , '%d/%m/%Y', '%D/%M/%Y',
     214               '%d.%m.%Y', '%D.%M.%Y']
     215   
     216    def _convertValueFromString(self, string):
     217        orig_string = string
     218        if string is NONE_STRING_VALUE:
     219            string = None
     220        if string is None:
     221            return None
     222        value = None
     223        if ' ' in string:
     224            string = string.split(' ')[0]
     225        for format in self.formats:
     226            try:
     227                value = datetime.datetime.strptime(string, format)
     228                break
     229            except ValueError:
     230                pass
     231        if value is None:
     232            raise ValueError(
     233                'Cannot convert to date: %s. Use YYYY-MM-DD.' %
     234                orig_string)
     235        value = value.date()
     236        return value
     237
     238    def _convertValueToString(self, value):
     239        return datetime.date.strftime(value, '%Y-%m-%d')
Note: See TracChangeset for help on using the changeset viewer.