Re: TimeConverter validator

Jorge Godoy <[email protected]>
Newsgroups gmane.comp.python.formencode
Organization G2C Tech Consultoria Ltda.
Message-ID <[email protected]>
Ian Bicking <[email protected]> writes:

> Jorge Godoy wrote:
>> Should the patch only try using datetime.time or should it also try
>> mx.DateTime?  Just to remember, datetime is available in the standard library
>> since Python 2.3 (so say the docs).
>> 
>> I believe I can write the patch today if it is only targetted at datetime. 
>
> Just datetime.time is fine.  Be sure to add to the doctests.

I couldn't find a way to allow overriding messages, but here's a preliminar
patch.  I'm still getting acquainted with this code...

Is there a better way to do this?  How could I override the standard
messages? 


Sorry for my "newbieness" here :-)  I'll keep on reading the source looking
for a way to do that...


-- 
Jorge Godoy      <[email protected]>

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642

_______________________________________________
FormEncode-discuss mailing list
FormEncode-discuss-5NWGOfrQmneRv+LV9MX5uipxlwaOVQ5f@public.gmane.org
https://lists.sourceforge.net/lists/listinfo/formencode-discuss
formencode-validators.diff (text/x-patch, 3.2 KB)
Index: formencode/validators.py
===================================================================
--- formencode/validators.py	(revisão 1885)
+++ formencode/validators.py	(cópia de trabalho)
@@ -91,6 +91,19 @@
         except module.RangeError, e:
             raise ValueError(str(e))
 
+
+# TODO: Needs being extended to support mx.DateTime as well.
+def datetime_time(module):
+    if module.__name__ == 'datetime':
+        return module.time
+
+# TODO: Needs being extended to support mx.DateTime as well.
+def datetime_isotime(module):
+    if module.__name__ == 'datetime':
+        return module.time.isoformat
+
+
+
 ############################################################
 ## Wrapper Validators
 ############################################################
@@ -1751,7 +1764,7 @@
 
     messages = {
         'noAMPM': 'You must indicate AM or PM',
-        'tooManyColon': 'There are two many :\'s',
+        'tooManyColon': 'There are too many :\'s',
         'noSeconds': 'You may not enter seconds',
         'secondsRequired': 'You must enter seconds',
         'minutesRequired': 'You must enter minutes (after a :)',
@@ -1880,8 +1893,62 @@
             return '%i:%02i:%02i%s' % (hour, minute, second, ampm)
         else:
             return '%i:%02i%s' % (hour, minute, ampm)
-        
 
+class TimeValidator(TimeConverter):
+    """
+    Converts times in the format HH:MM:SSampm to a datetime.time object.
+    Seconds are optional.
+
+    For ampm, set use_ampm = True.  For seconds, use_seconds = True.
+    Use 'optional' for either of these to make them optional.
+
+    Examples::
+
+        >>> v = TimeValidator()
+        >>> a = v.to_python('18:00')
+        >>> a
+        datetime.time(18, 0)
+        >>> b = v.to_python('30:00')
+        Traceback (most recent call last):
+            ...
+        formencode.api.Invalid: You must enter an hour in the range 0-23
+        >>> v2 = TimeValidator(prefer_ampm=True)
+        >>> v2.from_python(a)
+        '6:00:00pm'
+        >>> v3 = TimeValidator(prefer_ampm=True, use_seconds=False)
+        >>> a = v3.to_python('18:00')
+        >>> v3.from_python(a)
+        '6:00pm'
+        >>> a = v3.to_python('18:00:00')
+        Traceback (most recent call last):
+            ...
+        formencode.api.Invalid: You may not enter seconds
+    """
+
+    datetime_module = None
+
+    def _to_python(self, value, state):
+        tim = TimeConverter(use_ampm=self.use_ampm,
+                            use_seconds=self.use_seconds,
+                            prefer_ampm=self.prefer_ampm)
+        value, state = tim._to_python(value, state)
+        dt_mod = import_datetime(self.datetime_module)
+        time = datetime_time(dt_mod)
+        return time(value)
+
+    def _from_python(self, value, state):
+        tim = TimeConverter(use_ampm=self.use_ampm,
+                            use_seconds=self.use_seconds,
+                            prefer_ampm=self.prefer_ampm)
+        dt_mod = import_datetime(self.datetime_module)
+        isotime = datetime_isotime(dt_mod)
+        value = isotime(value)
+        if not self.use_seconds:
+            value = value[:-3]
+        value = tim._to_python(value, state)
+        value = tim._from_python(value, state)
+        return value
+
 class PostalCode(Regex):
 
     """
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.