/
__init__.py
91 lines (71 loc) · 2.52 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from formencode import Schema, validators, Invalid
from formencode.api import Validator
from formencode.validators import _
import dateutil.parser
from decimal import Decimal, InvalidOperation
from datetime import datetime
class IgnoreKeyMissed(object):
'''
dummy class to pass to a if_missing field in formeencode Schema.
when we want to ignore appearing of a field when missed, we will
set if_missing=IgnoreKeyMissed.
'''
class DummyValidator(Validator):
'''
a dummy Validator for MDMSchema.
all fields with this type of validator will ignore,
so not important what is that value.
'''
if_missing = IgnoreKeyMissed
def _to_python(self, value, state):
return IgnoreKeyMissed
class BaseSchema(Schema):
"""
new Implementation of formencode Schema to cover some deficits
"""
def _to_python(self, value_dict, state):
value_dict = super(BaseSchema, self)._to_python(value_dict, state)
for k, v in value_dict.items():
if v == IgnoreKeyMissed:
value_dict.pop(k)
return value_dict
class ISODateTimeValidator(validators.String):
'''
a validator to validate an str in iso format.
e.g: 2014-01-16T10:22:51.585719 or 2014-01-16T10:22:51
'''
messages = dict(
invalidIso=_('Invalid iso datetime format'))
def _to_python(self, value, state):
if not value:
return None
try:
return dateutil.parser.parse(value.rstrip('Z'))
except (ValueError, TypeError):
raise Invalid(self.message('invalidIso', state), value, state)
def empty_value(self, value):
return None
class ISODateValidator(ISODateTimeValidator):
'''
a validator to validate an str in iso format.
e.g: 2014-01-16T10:22:51.585719 or 2014-01-16T10:22:51
'''
messages = dict(
invalidIso=_('Invalid iso date format'))
def _to_python(self, value, state):
if not value:
return None
try:
return datetime.strptime(value, '%Y-%m-%d').date()
except (ValueError, TypeError):
raise Invalid(self.message('invalidIso', state), value, state)
class DecimalValidator(validators.RangeValidator):
'''
Validate a numeric string and return a Decimal
'''
messages = {'bad_value': 'Please enter a number'}
def _to_python(self, value, state):
try:
return Decimal(str(value))
except InvalidOperation:
raise Invalid(self.message('bad_value', state), value, state)