1 # -*- coding: iso-8859-15 -*-
2 """This file contains "validators" that convert between string and python (database) representation
3 of properties used in the "Rodelbahnbox" and "Gasthausbox".
4 The "to_python" method has to get a unicode argument.
6 >>> nosetests --with-pylons=test.ini
9 import formencode.national
12 import xml.dom.minidom as minidom
13 from xml.parsers.expat import ExpatError
16 class NoneValidator(formencode.FancyValidator):
17 """Takes a validator and makes it possible that empty strings are mapped to None."""
18 def __init__(self, validator, python_none=None):
19 self.validator = validator
20 self.python_none = python_none
22 def to_python(self, value):
23 self.assert_string(value, None)
24 if value == u'': return self.python_none
25 return self.validator.to_python(value)
27 def from_python(self, value):
28 if value == self.python_none: return u''
29 return self.validator.from_python(value)
32 class NeinValidator(formencode.FancyValidator):
33 """Take an arbitrary validator and adds the possibility that the
34 string can be u'Nein'.
35 Example together with an UnsignedNone validator:
36 >>> v = NeinValidator(UnsignedNone())
39 >>> v.to_python(u'34')
41 >>> v.to_python(u'Nein')
44 def __init__(self, validator, python_no=u'Nein'):
45 self.validator = validator
46 self.python_no = python_no
48 def to_python(self, value):
49 self.assert_string(value, None)
50 if value == u'Nein': return self.python_no
51 return self.validator.to_python(value)
53 def from_python(self, value):
54 if value == self.python_no: return u'Nein'
55 return self.validator.from_python(value)
58 class Unicode(formencode.FancyValidator):
59 """Converts an unicode string to an unicode string:
60 u'any string' <=> u'any string'"""
61 def to_python(self, value):
62 self.assert_string(value, None)
65 def from_python(self, value):
69 class UnicodeNone(NoneValidator):
70 """Converts an unicode string to an unicode string:
72 u'any string' <=> u'any string'"""
74 NoneValidator.__init__(self, Unicode())
77 class Unsigned(formencode.FancyValidator):
78 """Converts an unsigned number to a string and vice versa:
83 def __init__(self, max=None):
84 self.iv = formencode.validators.Int(min=0, max=max)
86 def to_python(self, value):
87 self.assert_string(value, None)
88 return self.iv.to_python(value)
90 def from_python(self, value):
94 class UnsignedNone(NoneValidator):
95 """Converts an unsigned number to a string and vice versa:
101 def __init__(self, max=None):
102 NoneValidator.__init__(self, Unsigned(max))
105 class UnsignedNeinNone(NoneValidator):
106 """ Translates a number of Nein to a number.
114 NoneValidator.__init__(self, UnsignedNone())
117 class Loop(formencode.FancyValidator):
118 """Takes a validator and calls from_python(to_python(value))."""
119 def __init__(self, validator):
120 self.validator = validator
122 def to_python(self, value):
123 self.assert_string(value, None)
124 return self.validator.from_python(self.validator.to_python(value))
126 def from_python(self, value):
127 # we don't call self.validator.to_python(self.validator.from_python(value))
128 # here because our to_python implementation basically leaves the input untouches
129 # and so should from_python do.
130 return self.validator.from_python(self.validator.to_python(value))
133 class DictValidator(formencode.FancyValidator):
134 """Translates strings to other values via a python directory.
135 >>> boolValidator = DictValidator({u'': None, u'Ja': True, u'Nein': False})
136 >>> boolValidator.to_python(u'')
138 >>> boolValidator.to_python(u'Ja')
141 def __init__(self, dict):
144 def to_python(self, value):
145 self.assert_string(value, None)
146 if not self.dict.has_key(value): raise formencode.Invalid("Key not found in dict.", value, None)
147 return self.dict[value]
149 def from_python(self, value):
150 for k, v in self.dict.iteritems():
151 if type(v) == type(value) and v == value: return k
152 raise formencode.Invalid('Invalid value', value, None)
155 class GermanBoolNone(DictValidator):
156 """Converts German bool values to the python bool type:
162 DictValidator.__init__(self, {u'': None, u'Ja': True, u'Nein': False})
165 class GermanTristateTuple(DictValidator):
166 """Does the following conversion:
168 u'Ja' <=> (True, False)
169 u'Teilweise' <=> (True, True)
170 u'Nein' <=> (False, True)"""
171 def __init__(self, yes_python = (True, False), no_python = (False, True), partly_python = (True, True), none_python = (None, None)):
172 DictValidator.__init__(self, {u'': none_python, u'Ja': yes_python, u'Nein': no_python, u'Teilweise': partly_python})
175 class GermanTristateFloat(GermanTristateTuple):
176 """Converts the a property with the possible values 0.0, 0.5, 1.0 or None
183 GermanTristateTuple.__init__(self, yes_python=1.0, no_python=0.0, partly_python=0.5, none_python=None)
186 class ValueComment(formencode.FancyValidator):
187 """Converts value with a potentially optional comment to a python tuple:
189 u'value' <=> (u'value', None)
190 u'value (comment)' <=> (u'value', u'comment')"""
191 def __init__(self, value_validator=UnicodeNone(), comment_validator=UnicodeNone(), comment_is_optional=True):
192 self.value_validator = value_validator
193 self.comment_validator = comment_validator
194 self.comment_is_optional = comment_is_optional
196 def to_python(self, value):
197 self.assert_string(value, None)
202 left = value.find('(')
203 right = value.rfind(')')
204 if left < 0 and right < 0:
205 if not self.comment_is_optional: raise formencode.Invalid(u'Mandatory comment not present', value, None)
208 elif left >= 0 and right >= 0 and left < right:
209 v = value[:left].strip()
210 c = value[left+1:right].strip()
211 else: raise formencode.Invalid(u'Invalid format', value, None)
212 return self.value_validator.to_python(v), self.comment_validator.to_python(c)
214 def from_python(self, value):
215 assert len(value) == 2
216 v = self.value_validator.from_python(value[0])
217 c = self.comment_validator.from_python(value[1])
219 if len(v) > 0: return u'%s (%s)' % (v, c)
220 else: return u'(%s)' % c
224 class SemicolonList(formencode.FancyValidator):
225 """Applies a given validator to a semicolon separated list of values and returns a python list.
226 For an empty string an empty list is returned."""
227 def __init__(self, validator=Unicode()):
228 self.validator = validator
230 def to_python(self, value):
231 self.assert_string(value, None)
232 return [self.validator.to_python(s.strip()) for s in value.split(';')]
234 def from_python(self, value):
235 return "; ".join([self.validator.from_python(s) for s in value])
238 class ValueCommentList(SemicolonList):
239 """A value-comment list looks like one of the following lines:
241 value (optional comment)
243 value1; value2 (optional comment)
244 value1 (optional comment1); value2 (optional comment2); value3 (otional comment3)
245 value1 (optional comment1); value2 (optional comment2); value3 (otional comment3)
246 This function returns the value-comment list as list of tuples:
247 [(u'value1', u'comment1'), (u'value2', None)]
248 If no comment is present, None is specified.
249 For an empty string, [] is returned."""
250 def __init__(self, value_validator=Unicode(), comments_are_optional=True):
251 SemicolonList.__init__(self, ValueComment(value_validator, comment_is_optional=comments_are_optional))
254 class GenericDateTime(formencode.FancyValidator):
255 """Converts a generic date/time information to a datetime class with a user defined format.
256 '2009-03-22 20:36:15' would be specified as '%Y-%m-%d %H:%M:%S'."""
258 def __init__(self, date_time_format = '%Y-%m-%d %H:%M:%S', **keywords):
259 formencode.FancyValidator.__init__(self, **keywords)
260 self.date_time_format = date_time_format
262 def to_python(self, value):
263 self.assert_string(value, None)
264 try: return datetime.datetime.strptime(value, self.date_time_format)
265 except ValueError, e: raise formencode.Invalid(str(e), value, None)
267 def from_python(self, value):
268 return value.strftime(self.date_time_format)
271 class DateTimeNoSec(GenericDateTime):
272 def __init__(self, **keywords):
273 GenericDateTime.__init__(self, '%Y-%m-%d %H:%M', **keywords)
276 class DateNone(NoneValidator):
277 """Converts date information to date classes with the format '%Y-%m-%d' or None."""
279 NoneValidator.__init__(self, GenericDateTime('%Y-%m-%d'))
282 class Geo(formencode.FancyValidator):
283 """Formats to coordinates '47.076207 N 11.453553 E' to the (latitude, longitude) tuplet."""
284 def to_python(self, value):
285 self.assert_string(value, None)
286 r = re.match(u'(\d+\.\d+) N (\d+\.\d+) E', value)
287 if r is None: raise formencode.Invalid(u"Coordinates '%s' have not a format like '47.076207 N 11.453553 E'" % value, value, None)
288 return (float(r.groups()[0]), float(r.groups()[1]))
290 def from_python(self, value):
291 latitude, longitude = value
292 return u'%.6f N %.6f E' % (latitude, longitude)
295 class GeoNone(NoneValidator):
296 """Formats to coordinates '47.076207 N 11.453553 E' to the (latitude, longitude) tuplet."""
298 NoneValidator.__init__(self, Geo(), (None, None))
301 class MultiGeo(formencode.FancyValidator):
302 "Formats multiple coordinates, even in multiple lines to [(latitude, longitude, elevation), ...] or [(latitude, longitude, None), ...] tuplets."
304 # Valid for input_format
305 FORMAT_GUESS = 0 # guesses the input format; default for input_format
306 FORMAT_NONE = -1 # indicates missing formats
308 # Valid for input_format and output_format
309 FORMAT_GEOCACHING = 1 # e.g. "N 47° 13.692 E 011° 25.535"
310 FORMAT_WINTERRODELN = 2 # e.g. "47.222134 N 11.467211 E"
311 FORMAT_GMAPPLUGIN = 3 # e.g. "47.232922, 11.452239"
312 FORMAT_GPX = 4 # e.g. "<trkpt lat="47.181289" lon="11.408827"><ele>1090.57</ele></trkpt>"
314 input_format = FORMAT_GUESS
315 output_format = FORMAT_WINTERRODELN
316 last_input_format = FORMAT_NONE
318 def __init__(self, input_format = FORMAT_GUESS, output_format = FORMAT_WINTERRODELN, **keywords):
319 self.input_format = input_format
320 self.output_format = output_format
321 formencode.FancyValidator.__init__(self, if_empty = (None, None, None), **keywords)
323 def to_python(self, value):
324 self.assert_string(value, None)
325 input_format = self.input_format
326 if not input_format in [self.FORMAT_GUESS, self.FORMAT_GEOCACHING, self.FORMAT_WINTERRODELN, self.FORMAT_GMAPPLUGIN, self.FORMAT_GPX]:
327 raise formencode.Invalid(u"input_format %d is not recognized" % input_format, value, None) # Shouldn't it be an other type of runtime error?
328 lines = [line.strip() for line in value.split("\n") if len(line.strip()) > 0]
332 if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GEOCACHING:
333 r = re.match(u'N ?(\d+)° ?(\d+\.\d+) +E ?(\d+)° ?(\d+\.\d+)', line)
336 result.append((float(g[0]) + float(g[1])/60, float(g[2]) + float(g[3])/60, None))
337 last_input_format = self.FORMAT_WINTERRODELN
340 if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_WINTERRODELN:
341 r = re.match(u'(\d+\.\d+) N (\d+\.\d+) E', line)
343 result.append((float(r.groups()[0]), float(r.groups()[1]), None))
344 last_input_format = self.FORMAT_WINTERRODELN
347 if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GMAPPLUGIN:
348 r = re.match(u'(\d+\.\d+), ?(\d+\.\d+)', line)
350 result.append((float(r.groups()[0]), float(r.groups()[1]), None))
351 last_input_format = self.FORMAT_GMAPPLUGIN
354 if input_format == self.FORMAT_GUESS or input_format == self.FORMAT_GPX:
356 xml = minidom.parseString(line)
357 coord = xml.documentElement
358 lat = float(coord.getAttribute('lat'))
359 lon = float(coord.getAttribute('lon'))
360 try: ele = float(coord.childNodes[0].childNodes[0].nodeValue)
361 except (IndexError, ValueError): ele = None
362 result.append((lat, lon, ele))
363 last_input_format = self.FORMAT_GPX
365 except (ExpatError, IndexError, ValueError): pass
367 raise formencode.Invalid(u"Coordinates '%s' have no known format" % line, value, None)
371 def from_python(self, value):
372 output_format = self.output_format
374 for latitude, longitude, height in value:
375 if output_format == self.FORMAT_GEOCACHING:
377 result.append(u'N %02d° %02.3f E %03d° %02.3f' % (latitude, latitude % 1 * 60, longitude, longitude % 1 * 60))
379 elif output_format == self.FORMAT_WINTERRODELN:
380 result.append(u'%.6f N %.6f E' % (latitude, longitude))
382 elif output_format == self.FORMAT_GMAPPLUGIN:
383 result.append(u'%.6f, %.6f' % (latitude, longitude))
385 elif output_format == self.FORMAT_GPX:
386 if not height is None: result.append(u'<trkpt lat="%.6f" lon="%.6f"><ele>%.2f</ele></trkpt>' % (latitude, longitude, height))
387 else: result.append(u'<trkpt lat="%.6f" lon="%.6f"/>' % (latitude, longitude))
390 raise formencode.Invalid(u"output_format %d is not recognized" % output_format, value, None) # Shouldn't it be an other type of runtime error?
392 return "\n".join(result)
396 class AustrianPhoneNumber(formencode.FancyValidator):
398 Validates and converts phone numbers to +##/###/####### or +##/###/#######-### (having an extension)
399 @param default_cc country code for prepending if none is provided, defaults to 43 (Austria)
401 >>> v = AustrianPhoneNumber()
402 >>> v.to_python(u'0512/12345678')
404 >>> v.to_python(u'+43/512/12345678')
406 >>> v.to_python(u'0512/1234567-89') # 89 is the extension
407 u'+43/512/1234567-89'
408 >>> v.to_python(u'+43/512/1234567-89')
409 u'+43/512/1234567-89'
410 >>> v.to_python(u'0512 / 12345678') # Exception
411 >>> v.to_python(u'0512-12345678') # Exception
413 # Inspired by formencode.national.InternationalPhoneNumber
415 default_cc = 43 # Default country code
416 messages = {'phoneFormat': "'%%(value)s' is an invalid format. Please enter a number in the form +43/###/####### or 0###/########."}
418 def to_python(self, value):
419 self.assert_string(value, None)
420 m = re.match(u'^(?:\+(\d+)/)?([\d/]+)(?:-(\d+))?$', value)
422 # u'+43/512/1234567-89' => (u'43', u'512/1234567', u'89')
423 # u'+43/512/1234/567-89' => (u'43', u'512/1234/567', u'89')
424 # u'+43/512/1234/567' => (u'43', u'512/1234/567', None)
425 # u'0512/1234567' => (None, u'0512/1234567', None)
426 if m is None: raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
427 (country, phone, extension) = m.groups()
430 if phone.find(u'//') > -1 or phone.count('/') == 0: raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
434 if phone[0] != '0': raise formencode.Invalid(self.message('phoneFormat', None) % {'value': value}, value, None)
436 country = unicode(self.default_cc)
438 if extension is None: return '+%s/%s' % (country, phone)
439 return '+%s/%s-%s' % (country, phone, extension)
443 class AustrianPhoneNumberNone(NoneValidator):
445 NoneValidator.__init__(self, AustrianPhoneNumber())
449 class AustrianPhoneNumberCommentLoop(NoneValidator):
451 NoneValidator.__init__(self, Loop(ValueComment(AustrianPhoneNumber())))
454 class GermanDifficulty(DictValidator):
455 """Converts the difficulty represented in a number from 1 to 3 (or None)
456 to a German representation:
462 DictValidator.__init__(self, {u'': None, u'leicht': 1, u'mittel': 2, u'schwer': 3})
465 class GermanAvalanches(DictValidator):
466 """Converts the avalanches property represented as number from 1 to 4 (or None)
467 to a German representation:
471 u'gelegentlich' <=> 3
474 DictValidator.__init__(self, {u'': None, u'kaum': 1, u'selten': 2, u'gelegentlich': 3, u'häufig': 4})
477 class GermanPublicTransport(DictValidator):
478 """Converts the public_transport property represented as number from 1 to 6 (or None)
479 to a German representation:
488 DictValidator.__init__(self, {u'': None, u'Sehr gut': 1, u'Gut': 2, u'Mittelmäßig': 3, u'Schlecht': 4, u'Nein': 5, u'Ja': 6})
491 class GermanTristateFloatComment(ValueComment):
492 """Converts the a property with the possible values 0.0, 0.5, 1.0 or None and an optional comment
493 in parenthesis to a German text:
495 u'Ja' <=> (1.0, None)
496 u'Teilweise' <=> (0.5, None)
497 u'Nein' <=> (0.0, None)
498 u'Ja (aber schmal)' <=> (1.0, u'aber schmal')
499 u'Teilweise (oben)' <=> (0.5, u'oben')
500 u'Nein (aber breit)' <=> (0.0, u'aber breit')
503 ValueComment.__init__(self, GermanTristateFloat())
506 class UnsignedCommentNone(NoneValidator):
507 """Converts the a property with unsigned values an optional comment
508 in parenthesis to a text:
510 u'2 (Mo, Di)' <=> (2, u'Mo, Di')
514 def __init__(self, max=None):
515 NoneValidator.__init__(self, ValueComment(Unsigned(max=max)), (None, None))
518 class GermanCachet(formencode.FancyValidator):
519 """Converts a "Gütesiegel":
522 u'Tiroler Naturrodelbahn-Gütesiegel 2009 mittel' <=> u'Tiroler Naturrodelbahn-Gütesiegel 2009 mittel'"""
523 def to_python(self, value):
524 self.assert_string(value, None)
525 if value == u'': return None
526 elif value == u'Nein': return value
527 elif value.startswith(u'Tiroler Naturrodelbahn-Gütesiegel '):
529 Unsigned().to_python(p[2]) # check if year can be parsed
530 if not p[3] in ['leicht', 'mittel', 'schwer']: raise formencode.Invalid("Unbekannter Schwierigkeitsgrad", value, None)
532 else: raise formencode.Invalid("Unbekanntes Gütesiegel", value, None)
534 def from_python(self, value):
535 if value == None: return u''
537 return self.to_python(self, value)
540 class Url(formencode.FancyValidator):
541 """Validates an URL. In contrast to fromencode.validators.URL, umlauts are allowed."""
542 urlv = formencode.validators.URL()
543 def to_python(self, value):
544 self.assert_string(value, None)
546 v = v.replace(u'ä', u'a')
547 v = v.replace(u'ö', u'o')
548 v = v.replace(u'ü', u'u')
549 v = v.replace(u'ß', u'ss')
550 v = self.urlv.to_python(v)
553 def from_python(self, value):
557 class UrlNeinNone(NoneValidator):
558 """Validates an URL. In contrast to fromencode.validators.URL, umlauts are allowed.
559 The special value u"Nein" is allowed."""
561 NoneValidator.__init__(self, NeinValidator(Url()))
564 class ValueCommentListNeinLoopNone(NoneValidator):
565 """Translates a semicolon separated list of values with optional comments in paranthesis or u'Nein' to itself.
566 An empty string is translated to None:
569 u'T-Mobile (gut); A1' <=> u'T-Mobile (gut); A1'"""
571 NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList())))
574 class PhoneCommentListNeinLoopNone(NoneValidator):
575 """List with semicolon-separated phone numbers in international format with optional comment or 'Nein' as string:
578 u'+43-699-1234567 (nicht nach 20:00 Uhr); +43-512-123456' <=> u'+43-699-1234567 (nicht nach 20:00 Uhr); +43-512-123456'
580 def __init__(self, comments_are_optional):
581 NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList(formencode.national.InternationalPhoneNumber(default_cc=lambda: 43), comments_are_optional=comments_are_optional))))
584 class EmailCommentListNeinLoopNone(NoneValidator):
585 """Converts a semicolon-separated list of email addresses with optional comments to itself.
586 The special value of u'Nein' indicates that there are no email addresses.
587 The empty string translates to None:
590 u'first@example.com' <=> u'first@example.com'
591 u'first@example.com (Nur Winter); second@example.com' <=> u'first@example.com (Nur Winter); second@example.com'
594 NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList(formencode.validators.Email()))))
597 class WikiPage(formencode.FancyValidator):
598 """Validates wiki page name like u'[[Birgitzer Alm]]'.
599 The page is not checked for existance.
600 An empty string is an error.
601 u'[[Birgitzer Alm]]' <=> u'[[Birgitzer Alm]]'
603 def to_python(self, value):
604 self.assert_string(value, None)
605 if not value.startswith('[[') or not value.endswith(']]'):
606 raise formencode.Invalid('No valid wiki page name', value, None)
609 def from_python(self, value):
613 class WikiPageList(SemicolonList):
614 """Validates a list of wiki pages like u'[[Birgitzer Alm]]; [[Kemater Alm]]'.
615 u'[[Birgitzer Alm]]; [[Kemater Alm]]' <=> [u'[[Birgitzer Alm]]', u'[[Kemater Alm]]']
616 u'[[Birgitzer Alm]]' <=> [u'[[Birgitzer Alm]]']
620 SemicolonList.__init__(self, WikiPage())
623 class WikiPageListLoopNone(NoneValidator):
624 """Validates a list of wiki pages like u'[[Birgitzer Alm]]; [[Kemater Alm]]' as string.
625 u'[[Birgitzer Alm]]; [[Kemater Alm]]' <=> u'[[Birgitzer Alm]]; [[Kemater Alm]]'
626 u'[[Birgitzer Alm]]' <=> u'[[Birgitzer Alm]]'
630 NoneValidator.__init__(self, Loop(WikiPageList()))
633 class TupleSecondValidator(formencode.FancyValidator):
634 """Does not really validate anything but puts the string through
635 a validator in the second part of a tuple.
636 Examples with an Unsigned() validator and the True argument:
638 u'2' <=> (True, 2)"""
639 def __init__(self, first=True, validator=UnicodeNone()):
641 self.validator = validator
643 def to_python(self, value):
644 self.assert_string(value, None)
645 return self.first, self.validator.to_python(value)
647 def from_python(self, value):
648 assert value[0] == self.first
649 return self.validator.from_python(value[1])
652 class BoolUnicodeTupleValidator(NoneValidator):
653 """Translates an unparsed string or u'Nein' to a tuple:
655 u'Nein' <=> (False, None)
656 u'any text' <=> (True, u'any text')
658 def __init__(self, validator=UnicodeNone()):
659 NoneValidator.__init__(self, NeinValidator(TupleSecondValidator(True, validator), (False, None)), (None, None))
662 class GermanLift(BoolUnicodeTupleValidator):
663 """Checks a lift_details property. It is a value comment property with the following
670 Alternatively, the value u'Nein' is allowed.
671 An empty string maps to (None, None).
675 u'Nein' <=> (False, None)
676 u'Sessellift <=> (True, u'Sessellift')
677 u'Gondel (nur bis zur Hälfte)' <=> (True, u'Gondel (nur bis zur Hälfte)')
678 u'Sessellift; Taxi' <=> (True, u'Sessellift; Taxi')
679 u'Sessellift (Wochenende); Taxi (6 Euro)' <=> (True, u'Sessellift (Wochenende); Taxi (6 Euro)')
682 BoolUnicodeTupleValidator.__init__(self, Loop(ValueCommentList(DictValidator({u'Sessellift': u'Sessellift', u'Gondel': u'Gondel', u'Linienbus': u'Linienbus', u'Taxi': u'Taxi', u'Sonstige': u'Sonstige'}))))
685 class SledRental(BoolUnicodeTupleValidator):
686 """The value can be an empty string, u'Nein' or a comma-separated list of unicode strings with optional comments.
688 u'Nein' <=> (False, None)
689 u'Talstation (nur mit Ticket); Schneealm' <=> (True, u'Talstation (nur mit Ticket); Schneealm')"""
691 BoolUnicodeTupleValidator.__init__(self, Loop(ValueCommentList()))