from wrpylib.mwmarkup import template_to_table
-class OrderedSchema(formencode.Schema):
- def _convert_to_python(self, value, state):
- pre_validators = self.pre_validators
- chained_validators = self.chained_validators
- for validator in pre_validators:
- value = validator.to_python(value, state)
- self.pre_validators = []
- self.chained_validators = []
- try:
- result = formencode.Schema._convert_to_python(self, value, state)
- ordered_result = OrderedDict()
- for key in value.keys():
- ordered_result[key] = result[key]
- for validator in chained_validators:
- ordered_result = validator.to_python(ordered_result, state)
- finally:
- self.pre_validators = pre_validators
- self.chained_validators = chained_validators
- return ordered_result
-
- def _convert_from_python(self, value, state):
- # store original pre- and chained validators
- pre_validators = self.pre_validators
- chained_validators = self.chained_validators[:]
- # apply chained validators
- chained = chained_validators[:]
- chained.reverse()
- for validator in chained:
- value = validator.from_python(value, state)
- # tempoarly remove pre- and chained validators
- self.pre_validators = []
- self.chained_validators = []
- # apply original _convert_from_python method
- try:
- result = formencode.Schema._convert_from_python(self, value, state)
- ordered_result = OrderedDict()
- for key in value.keys():
- ordered_result[key] = result[key]
- # apply pre_validators
- pre = pre_validators[:]
- pre.reverse()
- for validator in pre:
- ordered_result = validator.from_python(ordered_result, state)
- finally:
- # resore original pre- and chained_validators
- self.pre_validators = pre_validators
- self.chained_validators = chained_validators
- return ordered_result
-
-
-class NoneValidator(formencode.FancyValidator):
- """Takes a validator and makes it possible that empty strings are mapped to None."""
- def __init__(self, validator, python_none=None):
- self.validator = validator
- self.python_none = python_none
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- if value == '': return self.python_none
- return self.validator.to_python(value, state)
-
- def from_python(self, value, state=None):
- if value == self.python_none: return ''
- return self.validator.from_python(value, state)
-
-
-class NeinValidator(formencode.FancyValidator):
- """Take an arbitrary validator and adds the possibility that the
- string can be u'Nein'.
- Example together with an UnsignedNone validator:
- >>> v = NeinValidator(UnsignedNone())
- >>> v.to_python(u'')
- None
- >>> v.to_python(u'34')
- 34
- >>> v.to_python(u'Nein')
- u'Nein'
- """
- def __init__(self, validator, python_no='Nein'):
- self.validator = validator
- self.python_no = python_no
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- if value == 'Nein': return self.python_no
- return self.validator.to_python(value, state)
-
- def from_python(self, value, state=None):
- if value == self.python_no: return 'Nein'
- return self.validator.from_python(value, state)
-
-
-class Unicode(formencode.FancyValidator):
- """Converts an unicode string to an unicode string:
- u'any string' <=> u'any string'"""
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- return str(value)
-
- def from_python(self, value, state=None):
- return str(value)
-
-
-class UnicodeNone(NoneValidator):
- """Converts an unicode string to an unicode string:
- u'' <=> None
- u'any string' <=> u'any string'"""
- def __init__(self):
- NoneValidator.__init__(self, Unicode())
-
-
-class Unsigned(formencode.FancyValidator):
- """Converts an unsigned number to a string and vice versa:
- u'0' <=> 0
- u'1' <=> 1
- u'45' <=> 45
- """
- def __init__(self, max=None):
- self.iv = formencode.validators.Int(min=0, max=max)
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- return self.iv.to_python(value, state)
-
- def from_python(self, value, state=None):
- return str(value)
-
-
-class UnsignedNone(NoneValidator):
- """Converts an unsigned number to a string and vice versa:
- u'' <=> None
- u'0' <=> 0
- u'1' <=> 1
- u'45' <=> 45
- """
- def __init__(self, max=None):
- NoneValidator.__init__(self, Unsigned(max))
-
-
-class UnsignedNeinNone(NoneValidator):
- """ Translates a number of Nein to a number.
- u'' <=> None
- u'Nein' <=> 0
- u'1' <=> 1
- u'2' <=> 2
- ...
- """
- def __init__(self):
- NoneValidator.__init__(self, UnsignedNone())
-
-
-class Loop(formencode.FancyValidator):
- """Takes a validator and calls from_python(to_python(value))."""
- def __init__(self, validator):
- self.validator = validator
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- return self.validator.from_python(self.validator.to_python(value, state))
-
- def from_python(self, value, state=None):
- # we don't call self.validator.to_python(self.validator.from_python(value))
- # here because our to_python implementation basically leaves the input untouched
- # and so should from_python do.
- return self.validator.from_python(self.validator.to_python(value, state))
-
-
-class DictValidator(formencode.FancyValidator):
- """Translates strings to other values via a python directory.
- >>> boolValidator = DictValidator({u'': None, u'Ja': True, u'Nein': False})
- >>> boolValidator.to_python(u'')
- None
- >>> boolValidator.to_python(u'Ja')
- True
- """
- def __init__(self, dict):
- self.dict = dict
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- if value not in self.dict: raise formencode.Invalid("Key not found in dict.", value, state)
- return self.dict[value]
-
- def from_python(self, value, state=None):
- for k, v in self.dict.items():
- if v == value:
- return k
- raise formencode.Invalid('Invalid value', value, state)
-
-
-class GermanBoolNone(DictValidator):
- """Converts German bool values to the python bool type:
- u'' <=> None
- u'Ja' <=> True
- u'Nein' <=> False
- """
- def __init__(self):
- DictValidator.__init__(self, {'': None, 'Ja': True, 'Nein': False})
-
-
-class GermanTristateTuple(DictValidator):
- """Does the following conversion:
- u'' <=> (None, None)
- u'Ja' <=> (True, False)
- u'Teilweise' <=> (True, True)
- u'Nein' <=> (False, True)"""
- def __init__(self, yes_python = (True, False), no_python = (False, True), partly_python = (True, True), none_python = (None, None)):
- DictValidator.__init__(self, {'': none_python, 'Ja': yes_python, 'Nein': no_python, 'Teilweise': partly_python})
-
-
-class GermanTristateFloat(GermanTristateTuple):
- """Converts the a property with the possible values 0.0, 0.5, 1.0 or None
- to a German text:
- u'' <=> None
- u'Ja' <=> 1.0
- u'Teilweise' <=> 0.5
- u'Nein' <=> 0.0"""
- def __init__(self):
- GermanTristateTuple.__init__(self, yes_python=1.0, no_python=0.0, partly_python=0.5, none_python=None)
-
-
-class ValueComment(formencode.FancyValidator):
- """Converts value with a potentially optional comment to a python tuple. If a comment is present, the
- closing bracket has to be the rightmost character.
- u'' <=> (None, None)
- u'value' <=> (u'value', None)
- u'value (comment)' <=> (u'value', u'comment')
- u'[[link (linkcomment)]]' <=> (u'[[link (linkcomment)]]', None)
- u'[[link (linkcomment)]] (comment)' <=> (u'[[link (linkcomment)]]', comment)
- """
- def __init__(self, value_validator=UnicodeNone(), comment_validator=UnicodeNone(), comment_is_optional=True):
- self.value_validator = value_validator
- self.comment_validator = comment_validator
- self.comment_is_optional = comment_is_optional
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- if value == '':
- v = value
- c = value
- else:
- right = value.rfind(')')
- if right+1 != len(value):
- if not self.comment_is_optional: raise formencode.Invalid('Mandatory comment not present', value, state)
- v = value
- c = ''
- else:
- left = value.rfind('(')
- if left < 0: raise formencode.Invalid('Invalid format', value, state)
- v = value[:left].strip()
- c = value[left+1:right].strip()
- return self.value_validator.to_python(v, state), self.comment_validator.to_python(c, state)
-
- def from_python(self, value, state=None):
- assert len(value) == 2
- v = self.value_validator.from_python(value[0], state)
- c = self.comment_validator.from_python(value[1], state)
- if len(c) > 0:
- if len(v) > 0: return '%s (%s)' % (v, c)
- else: return '(%s)' % c
- return v
-
-
-
-class SemicolonList(formencode.FancyValidator):
- """Applies a given validator to a semicolon separated list of values and returns a python list.
- For an empty string an empty list is returned."""
- def __init__(self, validator=Unicode()):
- self.validator = validator
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- return [self.validator.to_python(s.strip(), state) for s in value.split(';')]
-
- def from_python(self, value, state=None):
- return "; ".join([self.validator.from_python(s, state) for s in value])
-
-
-class ValueCommentList(SemicolonList):
- """A value-comment list looks like one of the following lines:
- value
- value (optional comment)
- value1; value2
- value1; value2 (optional comment)
- value1 (optional comment1); value2 (optional comment2); value3 (otional comment3)
- value1 (optional comment1); value2 (optional comment2); value3 (otional comment3)
- This function returns the value-comment list as list of tuples:
- [(u'value1', u'comment1'), (u'value2', None)]
- If no comment is present, None is specified.
- For an empty string, [] is returned."""
- def __init__(self, value_validator=Unicode(), comments_are_optional=True):
- SemicolonList.__init__(self, ValueComment(value_validator, comment_is_optional=comments_are_optional))
-
-
-class GenericDateTime(formencode.FancyValidator):
- """Converts a generic date/time information to a datetime class with a user defined format.
- '2009-03-22 20:36:15' would be specified as '%Y-%m-%d %H:%M:%S'."""
-
- def __init__(self, date_time_format = '%Y-%m-%d %H:%M:%S', **keywords):
- formencode.FancyValidator.__init__(self, **keywords)
- self.date_time_format = date_time_format
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- try: return datetime.datetime.strptime(value, self.date_time_format)
- except ValueError as e: raise formencode.Invalid(str(e), value, state)
-
- def from_python(self, value, state=None):
- return value.strftime(self.date_time_format)
-
-
-class DateTimeNoSec(GenericDateTime):
- def __init__(self, **keywords):
- GenericDateTime.__init__(self, '%Y-%m-%d %H:%M', **keywords)
-
-
-class DateNone(NoneValidator):
- """Converts date information to date classes with the format '%Y-%m-%d' or None."""
- def __init__(self):
- NoneValidator.__init__(self, GenericDateTime('%Y-%m-%d'))
-
-
-
# Meta converter types and functions
# ----------------------------------
-class Converter:
- @classmethod
- def from_str(cls, value):
- return value
-
- @classmethod
- def to_str(cls, value):
- return str(value)
-
-
FromToConverter = namedtuple('FromToConverter', ['from_str', 'to_str'])
return '' if value == none else to_str(value)
-class OptionalConverter(Converter):
- converter = Converter
- none = None
-
- @classmethod
- def from_str(cls, value):
- return opt_from_str(value, cls.converter, cls.none)
-
- @classmethod
- def to_str(cls, value):
- return opt_to_str(value, cls.converter, cls.none)
-
-
def choice_from_str(value, choices):
if value not in choices:
raise ValueError('{} is an invalid value')
raise ValueError("Invalid value '{}'".format(value))
-class DictKeyConverter(Converter):
- key_str_dict = OrderedDict()
-
- @classmethod
- def from_str(cls, value):
- return dictkey_from_str(value, cls.key_str_dict)
-
- @classmethod
- def to_str(cls, value):
- return dictkey_to_str(value, cls.key_str_dict)
-
-
-
# Basic type converter functions
# ------------------------------
return str_from_str(value)
-class Str(Converter):
- pass
-
-
-class OptStr(OptionalConverter):
- converter = Str
-
-
def int_from_str(value, min=None, max=None):
value = int(value)
if min is not None and value < min:
opt_int_converter = FromToConverter(opt_int_from_str, opt_int_to_str)
-class Int(Converter):
- min = None
- max = None
-
- @classmethod
- def from_str(cls, value):
- return int_from_str(value, cls.min, cls.max)
-
-
IntConverter = FromToConverter(int_from_str, int_to_str)
-class OptInt(OptionalConverter):
- converter = Int
-
-
-class DateTime(Converter):
- format='%Y-%m-%d %H:%M:%S'
-
- @classmethod
- def from_str(cls, value):
- return datetime.datetime.strptime(value, cls.format)
-
- @classmethod
- def to_str(cls, value):
- return value.strftime(cls.format)
-
-
# Complex types
# -------------
return opt_to_str(value, lambda v: no_german_to_str(v, to_str, use_tuple, no_value), none)
-class GermanTristateFloatComment(ValueComment):
- """Converts the a property with the possible values 0.0, 0.5, 1.0 or None and an optional comment
- in parenthesis to a German text:
- u'' <=> (None, None)
- u'Ja' <=> (1.0, None)
- u'Teilweise' <=> (0.5, None)
- u'Nein' <=> (0.0, None)
- u'Ja (aber schmal)' <=> (1.0, u'aber schmal')
- u'Teilweise (oben)' <=> (0.5, u'oben')
- u'Nein (aber breit)' <=> (0.0, u'aber breit')
- """
- def __init__(self):
- ValueComment.__init__(self, GermanTristateFloat())
-
-
def night_light_from_str(value):
"""'Beleuchtungsanlage' Tristate with optional comment:
'' <=> (None, None)
return
-class NightLightDays(Int):
- min = 0
- max = 7
-
-
-class OptNightLightDays(OptionalConverter):
- converter = NightLightDays
-
-
def nightlightdays_from_str(value):
return value_comment_from_str(value, lambda val: opt_from_str(val, lambda v: int_from_str(v, min=0, max=7)), opt_str_from_str, comment_optional=True)
nightlightdays_converter = FromToConverter(nightlightdays_from_str, nightlightdays_to_str)
-class UnsignedCommentNone(NoneValidator):
- """Converts the a property with unsigned values an optional comment
- in parenthesis to a text:
- u'' <=> (None, None)
- u'2 (Mo, Di)' <=> (2, u'Mo, Di')
- u'7' <=> (7, None)
- u'0' <=> (0, None)
- """
- def __init__(self, max=None):
- NoneValidator.__init__(self, ValueComment(Unsigned(max=max)), (None, None))
-
-
CACHET_REGEXP = [r'(Tiroler Naturrodelbahn-Gütesiegel) ([12]\d{3}) (leicht|mittel|schwer)$']
return value
-class UrlNeinNone(NoneValidator):
- """Validates an URL. In contrast to fromencode.validators.URL, umlauts are allowed.
- The special value u"Nein" is allowed."""
- def __init__(self):
- NoneValidator.__init__(self, NeinValidator(Url()))
-
-
-class ValueCommentListNeinLoopNone(NoneValidator):
- """Translates a semicolon separated list of values with optional comments in paranthesis or u'Nein' to itself.
- An empty string is translated to None:
- u'' <=> None
- u'Nein' <=> u'Nein'
- u'T-Mobile (gut); A1' <=> u'T-Mobile (gut); A1'"""
- def __init__(self):
- NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList())))
-
-
def phone_number_from_str(value):
match = re.match(r'\+\d+(-\d+)*$', value)
if match is None:
except email.errors.HeaderParseError as e:
raise ValueError('Invalid email address: {}'.format(value), e)
return value
-class PhoneNumber(formencode.FancyValidator):
- """Telefonnumber in international format, e.g. u'+43-699-1234567'"""
- def __init__(self, default_cc=43):
- self.validator = formencode.national.InternationalPhoneNumber(default_cc=lambda: default_cc)
-
- def to_python(self, value, state=None):
- return str(self.validator.to_python(value, state))
-
- def from_python(self, value, state=None):
- return self.validator.from_python(value, state)
def email_to_str(value):
return str(email)
-class PhoneCommentListNeinLoopNone(NoneValidator):
- """List with semicolon-separated phone numbers in international format with optional comment or 'Nein' as string:
- u'' <=> None
- u'Nein' <=> u'Nein'
- u'+43-699-1234567 (nicht nach 20:00 Uhr); +43-512-123456' <=> u'+43-699-1234567 (nicht nach 20:00 Uhr); +43-512-123456'
- """
- def __init__(self, comments_are_optional):
- NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList(PhoneNumber(default_cc=43), comments_are_optional=comments_are_optional))))
class MaskedEmail(formencode.FancyValidator):
return email
+'''
class EmailCommentListNeinLoopNone(NoneValidator):
"""Converts a semicolon-separated list of email addresses with optional comments to itself.
The special value of u'Nein' indicates that there are no email addresses.
"""
def __init__(self, allow_masked_email=False):
NoneValidator.__init__(self, NeinValidator(Loop(ValueCommentList(MaskedEmail() if allow_masked_email else formencode.validators.Email()))))
-
+'''
class WikiPage(formencode.FancyValidator):
"""Validates wiki page name like u'[[Birgitzer Alm]]'.
"""
def __init__(self):
SemicolonList.__init__(self, WikiPage())
+'''
+'''
class WikiPageListLoopNone(NoneValidator):
"""Validates a list of wiki pages like u'[[Birgitzer Alm]]; [[Kemater Alm]]' as string.
u'[[Birgitzer Alm]]; [[Kemater Alm]]' <=> u'[[Birgitzer Alm]]; [[Kemater Alm]]'
"""
def __init__(self):
NoneValidator.__init__(self, Loop(WikiPageList()))
-
-
-class TupleSecondValidator(formencode.FancyValidator):
- """Does not really validate anything but puts the string through
- a validator in the second part of a tuple.
- Examples with an Unsigned() validator and the True argument:
- u'6' <=> (True, 6)
- u'2' <=> (True, 2)"""
- def __init__(self, first=True, validator=UnicodeNone()):
- self.first = first
- self.validator = validator
-
- def to_python(self, value, state=None):
- self.assert_string(value, state)
- return self.first, self.validator.to_python(value, state)
-
- def from_python(self, value, state=None):
- assert value[0] == self.first
- return self.validator.from_python(value[1], state)
-
-
-class BoolUnicodeTupleValidator(NoneValidator):
- """Translates an unparsed string or u'Nein' to a tuple:
- '' <=> (None, None)
- 'Nein' <=> (False, None)
- 'any text' <=> (True, 'any text')
- """
- def __init__(self, validator=UnicodeNone()):
- NoneValidator.__init__(self, NeinValidator(TupleSecondValidator(True, validator), (False, None)), (None, None))
+'''
LIFT_GERMAN = ['Sessellift', 'Gondel', 'Linienbus', 'Taxi', 'Sonstige']
lift_german_converter = FromToConverter(lift_german_from_str, lift_german_to_str)
-class GermanLift(BoolUnicodeTupleValidator):
- """Checks a lift_details property. It is a value comment property with the following
- values allowed:
- u'Sessellift'
- u'Gondel'
- u'Linienbus'
- u'Taxi'
- u'Sonstige'
- Alternatively, the value u'Nein' is allowed.
- An empty string maps to (None, None).
-
- Examples:
- u'' <=> (None, None)
- u'Nein' <=> (False, None)
- u'Sessellift <=> (True, u'Sessellift')
- u'Gondel (nur bis zur Hälfte)' <=> (True, u'Gondel (nur bis zur Hälfte)')
- u'Sessellift; Taxi' <=> (True, u'Sessellift; Taxi')
- u'Sessellift (Wochenende); Taxi (6 Euro)' <=> (True, u'Sessellift (Wochenende); Taxi (6 Euro)')
- """
- def __init__(self):
- BoolUnicodeTupleValidator.__init__(self, Loop(ValueCommentList(DictValidator({'Sessellift': 'Sessellift', 'Gondel': 'Gondel', 'Linienbus': 'Linienbus', 'Taxi': 'Taxi', 'Sonstige': 'Sonstige'}))))
-
-
def sledrental_from_str(value):
"""The value can be an empty string, 'Nein' or a semicolon-separated list of strings with optional comments.
'' => None
GASTHAUSBOX_TEMPLATE_NAME = 'Gasthausbox'
+'''
GASTHAUSBOX_DICT = OrderedDict([
('Position', opt_lonlat_converter), # '47.583333 N 15.75 E'
('Höhe', opt_meter_converter),
('Telefon', PhoneCommentListNeinLoopNone(comments_are_optional=True)),
('Bild', opt_str_converter),
('Rodelbahnen', WikiPageListLoopNone())])
-
+'''
def sledrun_page_title_to_pretty_url(page_title):