Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
3112 lines (2616 loc) · 105 KB

File metadata and controls

3112 lines (2616 loc) · 105 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# FormEncode, a Form processor
# Copyright (C) 2003, Ian Bicking <ianb@colorstudy.com>
"""
Validator/Converters for use with FormEncode.
"""
try:
import cgi
except ImportError: # Python >= 3.13
cgi = None
import re
import warnings
from encodings import idna
try: # import dnspython
import dns.resolver
import dns.exception
except (IOError, ImportError):
have_dns = False
else:
have_dns = True
# These are only imported when needed
http_client = None
random = None
sha1 = None
socket = None
urlparse = None
from .api import (FancyValidator, Identity, Invalid, NoDefault, Validator,
deprecation_warning, is_empty)
assert Identity and Invalid and NoDefault # silence unused import warnings
# Dummy i18n translation function, nothing is translated here.
# Instead, this is actually done in api.message.
# The surrounding _('string') of the strings is only for extracting
# the strings automatically.
# If you run pygettext with this source comment this function out temporarily.
_ = lambda s: s
# Utility methods
# These all deal with accepting both datetime and mxDateTime modules and types
datetime_module = None
mxDateTime_module = None
def import_datetime(module_type):
global datetime_module, mxDateTime_module
module_type = module_type.lower() if module_type else 'datetime'
if module_type == 'datetime':
if datetime_module is None:
import datetime as datetime_module
return datetime_module
elif module_type == 'mxdatetime':
if mxDateTime_module is None:
from mx import DateTime as mxDateTime_module
return mxDateTime_module
else:
raise ImportError('Invalid datetime module %r' % module_type)
def datetime_now(module):
if module.__name__ == 'datetime':
return module.datetime.now()
else:
return module.now()
def datetime_makedate(module, year, month, day):
if module.__name__ == 'datetime':
return module.date(year, month, day)
else:
try:
return module.DateTime(year, month, day)
except module.RangeError as e:
raise ValueError(str(e))
def datetime_time(module):
if module.__name__ == 'datetime':
return module.time
else:
return module.Time
def datetime_isotime(module):
if module.__name__ == 'datetime':
return module.time.isoformat
else:
return module.ISO.Time
# Wrapper Validators
class ConfirmType(FancyValidator):
"""
Confirms that the input/output is of the proper type.
Uses the parameters:
subclass:
The class or a tuple of classes; the item must be an instance
of the class or a subclass.
type:
A type or tuple of types (or classes); the item must be of
the exact class or type. Subclasses are not allowed.
Examples::
>>> cint = ConfirmType(subclass=int)
>>> cint.to_python(True)
True
>>> cint.to_python('1')
Traceback (most recent call last):
...
Invalid: '1' is not a subclass of <type 'int'>
>>> cintfloat = ConfirmType(subclass=(float, int))
>>> cintfloat.to_python(1.0), cintfloat.from_python(1.0)
(1.0, 1.0)
>>> cintfloat.to_python(1), cintfloat.from_python(1)
(1, 1)
>>> cintfloat.to_python(None)
Traceback (most recent call last):
...
Invalid: None is not a subclass of one of the types <type 'float'>, <type 'int'>
>>> cint2 = ConfirmType(type=int)
>>> cint2(accept_python=False).from_python(True)
Traceback (most recent call last):
...
Invalid: True must be of the type <type 'int'>
"""
accept_iterator = True
subclass = None
type = None
messages = dict(
subclass=_('%(object)r is not a subclass of %(subclass)s'),
inSubclass=_('%(object)r is not a subclass of one of the types %(subclassList)s'),
inType=_('%(object)r must be one of the types %(typeList)s'),
type=_('%(object)r must be of the type %(type)s'))
def __init__(self, *args, **kw):
FancyValidator.__init__(self, *args, **kw)
if self.subclass:
if isinstance(self.subclass, list):
self.subclass = tuple(self.subclass)
elif not isinstance(self.subclass, tuple):
self.subclass = (self.subclass,)
self._validate_python = self.confirm_subclass
if self.type:
if isinstance(self.type, list):
self.type = tuple(self.type)
elif not isinstance(self.type, tuple):
self.type = (self.type,)
self._validate_python = self.confirm_type
def confirm_subclass(self, value, state):
if not isinstance(value, self.subclass):
if len(self.subclass) == 1:
msg = self.message('subclass', state, object=value,
subclass=self.subclass[0])
else:
subclass_list = ', '.join(map(str, self.subclass))
msg = self.message('inSubclass', state, object=value,
subclassList=subclass_list)
raise Invalid(msg, value, state)
def confirm_type(self, value, state):
for t in self.type:
if type(value) is t:
break
else:
if len(self.type) == 1:
msg = self.message('type', state, object=value,
type=self.type[0])
else:
msg = self.message('inType', state, object=value,
typeList=', '.join(map(str, self.type)))
raise Invalid(msg, value, state)
return value
def is_empty(self, value):
return False
class Wrapper(FancyValidator):
"""
Used to convert functions to validator/converters.
You can give a simple function for `_convert_to_python`,
`_convert_from_python`, `_validate_python` or `_validate_other`.
If that function raises an exception, the value is considered invalid.
Whatever value the function returns is considered the converted value.
Unlike validators, the `state` argument is not used. Functions
like `int` can be used here, that take a single argument.
Note that as Wrapper will generate a FancyValidator, empty
values (those who pass ``FancyValidator.is_empty)`` will return ``None``.
To override this behavior you can use ``Wrapper(empty_value=callable)``.
For example passing ``Wrapper(empty_value=lambda val: val)`` will return
the value itself when is considered empty.
Examples::
>>> def downcase(v):
... return v.lower()
>>> wrap = Wrapper(convert_to_python=downcase)
>>> wrap.to_python('This')
'this'
>>> wrap.from_python('This')
'This'
>>> wrap.to_python('') is None
True
>>> wrap2 = Wrapper(
... convert_from_python=downcase, empty_value=lambda value: value)
>>> wrap2.from_python('This')
'this'
>>> wrap2.to_python('')
''
>>> wrap2.from_python(1)
Traceback (most recent call last):
...
Invalid: 'int' object has no attribute 'lower'
>>> wrap3 = Wrapper(validate_python=int)
>>> wrap3.to_python('1')
'1'
>>> wrap3.to_python('a') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
Invalid: invalid literal for int()...
"""
func_convert_to_python = None
func_convert_from_python = None
func_validate_python = None
func_validate_other = None
_deprecated_methods = (
('func_to_python', 'func_convert_to_python'),
('func_from_python', 'func_convert_from_python'))
def __init__(self, *args, **kw):
# allow old method names as parameters
if 'to_python' in kw and 'convert_to_python' not in kw:
kw['convert_to_python'] = kw.pop('to_python')
if 'from_python' in kw and 'convert_from_python' not in kw:
kw['convert_from_python'] = kw.pop('from_python')
for n in ('convert_to_python', 'convert_from_python',
'validate_python', 'validate_other'):
if n in kw:
kw['func_%s' % n] = kw.pop(n)
FancyValidator.__init__(self, *args, **kw)
self._convert_to_python = self.wrap(self.func_convert_to_python)
self._convert_from_python = self.wrap(self.func_convert_from_python)
self._validate_python = self.wrap(self.func_validate_python)
self._validate_other = self.wrap(self.func_validate_other)
def wrap(self, func):
if not func:
return None
def result(value, state, func=func):
try:
return func(value)
except Exception as e:
raise Invalid(str(e), value, state)
return result
class Constant(FancyValidator):
"""
This converter converts everything to the same thing.
I.e., you pass in the constant value when initializing, then all
values get converted to that constant value.
This is only really useful for funny situations, like::
# Any evaluates sub validators in reverse order for to_python
fromEmailValidator = Any(
Constant('unknown@localhost'),
Email())
In this case, the if the email is not valid
``'unknown@localhost'`` will be used instead. Of course, you
could use ``if_invalid`` instead.
Examples::
>>> Constant('X').to_python('y')
'X'
"""
__unpackargs__ = ('value',)
def _convert_to_python(self, value, state):
return self.value
_convert_from_python = _convert_to_python
# Normal validators
class MaxLength(FancyValidator):
"""
Invalid if the value is longer than `maxLength`. Uses len(),
so it can work for strings, lists, or anything with length.
Examples::
>>> max5 = MaxLength(5)
>>> max5.to_python('12345')
'12345'
>>> max5.from_python('12345')
'12345'
>>> max5.to_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5(accept_python=False).from_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python([1, 2, 3])
[1, 2, 3]
>>> max5.to_python([1, 2, 3, 4, 5, 6])
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
"""
__unpackargs__ = ('maxLength',)
messages = dict(
tooLong=_('Enter a value less than %(maxLength)i characters long'),
invalid=_('Invalid value (value with length expected)'))
def _validate_python(self, value, state):
try:
if value and len(value) > self.maxLength:
raise Invalid(
self.message('tooLong', state,
maxLength=self.maxLength), value, state)
else:
return None
except TypeError:
raise Invalid(
self.message('invalid', state), value, state)
class MinLength(FancyValidator):
"""
Invalid if the value is shorter than `minlength`. Uses len(), so
it can work for strings, lists, or anything with length. Note
that you **must** use ``not_empty=True`` if you don't want to
accept empty values -- empty values are not tested for length.
Examples::
>>> min5 = MinLength(5)
>>> min5.to_python('12345')
'12345'
>>> min5.from_python('12345')
'12345'
>>> min5.to_python('1234')
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5(accept_python=False).from_python('1234')
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5.to_python([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> min5.to_python([1, 2, 3])
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
"""
__unpackargs__ = ('minLength',)
messages = dict(
tooShort=_('Enter a value at least %(minLength)i characters long'),
invalid=_('Invalid value (value with length expected)'))
def _validate_python(self, value, state):
try:
if len(value) < self.minLength:
raise Invalid(
self.message('tooShort', state,
minLength=self.minLength), value, state)
except TypeError:
raise Invalid(
self.message('invalid', state), value, state)
class NotEmpty(FancyValidator):
"""
Invalid if value is empty (empty string, empty list, etc).
Generally for objects that Python considers false, except zero
which is not considered invalid.
Examples::
>>> ne = NotEmpty(messages=dict(empty='enter something'))
>>> ne.to_python('')
Traceback (most recent call last):
...
Invalid: enter something
>>> ne.to_python(0)
0
"""
not_empty = True
messages = dict(
empty=_('Please enter a value'))
def _validate_python(self, value, state):
if value == 0:
# This isn't "empty" for this definition.
return value
if not value:
raise Invalid(self.message('empty', state), value, state)
class Empty(FancyValidator):
"""
Invalid unless the value is empty. Use cleverly, if at all.
Examples::
>>> Empty.to_python(0)
Traceback (most recent call last):
...
Invalid: You cannot enter a value here
"""
messages = dict(
notEmpty=_('You cannot enter a value here'))
def _validate_python(self, value, state):
if value or value == 0:
raise Invalid(self.message('notEmpty', state), value, state)
class Regex(FancyValidator):
"""
Invalid if the value doesn't match the regular expression `regex`.
The regular expression can be a compiled re object, or a string
which will be compiled for you.
Use strip=True if you want to strip the value before validation,
and as a form of conversion (often useful).
Examples::
>>> cap = Regex(r'^[A-Z]+$')
>>> cap.to_python('ABC')
'ABC'
Note that ``.from_python()`` calls (in general) do not validate
the input::
>>> cap.from_python('abc')
'abc'
>>> cap(accept_python=False).from_python('abc')
Traceback (most recent call last):
...
Invalid: The input is not valid
>>> cap.to_python(1)
Traceback (most recent call last):
...
Invalid: The input must be a string (not a <type 'int'>: 1)
>>> Regex(r'^[A-Z]+$', strip=True).to_python(' ABC ')
'ABC'
>>> Regex(r'this', regexOps=('I',)).to_python('THIS')
'THIS'
"""
regexOps = ()
strip = False
regex = None
__unpackargs__ = ('regex',)
messages = dict(
invalid=_('The input is not valid'))
def __init__(self, *args, **kw):
FancyValidator.__init__(self, *args, **kw)
if isinstance(self.regex, str):
ops = 0
assert not isinstance(self.regexOps, str), (
"regexOps should be a list of options from the re module "
"(names, or actual values)")
for op in self.regexOps:
if isinstance(op, str):
ops |= getattr(re, op)
else:
ops |= op
self.regex = re.compile(self.regex, ops)
def _validate_python(self, value, state):
self.assert_string(value, state)
if self.strip and isinstance(value, str):
value = value.strip()
if not self.regex.search(value):
raise Invalid(self.message('invalid', state), value, state)
def _convert_to_python(self, value, state):
if self.strip and isinstance(value, str):
return value.strip()
return value
class PlainText(Regex):
"""
Test that the field contains only letters, numbers, underscore,
and the hyphen. Subclasses Regex.
Examples::
>>> PlainText.to_python('_this9_')
'_this9_'
>>> PlainText.from_python(' this ')
' this '
>>> PlainText(accept_python=False).from_python(' this ')
Traceback (most recent call last):
...
Invalid: Enter only letters, numbers, - (hyphen) or _ (underscore)
>>> PlainText(strip=True).to_python(' this ')
'this'
>>> PlainText(strip=True).from_python(' this ')
'this'
"""
regex = r"^[a-zA-Z_\-0-9]*$"
messages = dict(
invalid=_('Enter only letters, numbers, - (hyphen) or _ (underscore)'))
class OneOf(FancyValidator):
"""
Tests that the value is one of the members of a given list.
If ``testValueList=True``, then if the input value is a list or
tuple, all the members of the sequence will be checked (i.e., the
input must be a subset of the allowed values).
Use ``hideList=True`` to keep the list of valid values out of the
error message in exceptions.
Examples::
>>> oneof = OneOf([1, 2, 3])
>>> oneof.to_python(1)
1
>>> oneof.to_python(4)
Traceback (most recent call last):
...
Invalid: Value must be one of: 1; 2; 3 (not 4)
>>> oneof(testValueList=True).to_python([2, 3, [1, 2, 3]])
[2, 3, [1, 2, 3]]
>>> oneof.to_python([2, 3, [1, 2, 3]])
Traceback (most recent call last):
...
Invalid: Value must be one of: 1; 2; 3 (not [2, 3, [1, 2, 3]])
"""
list = None
testValueList = False
hideList = False
__unpackargs__ = ('list',)
messages = dict(
invalid=_('Invalid value'),
notIn=_('Value must be one of: %(items)s (not %(value)r)'))
def _validate_python(self, value, state):
if self.testValueList and isinstance(value, (list, tuple)):
for v in value:
self._validate_python(v, state)
else:
if value not in self.list:
if self.hideList:
raise Invalid(self.message('invalid', state), value, state)
else:
try:
items = '; '.join(map(str, self.list))
except UnicodeError:
items = '; '.join(map(str, self.list))
raise Invalid(
self.message('notIn', state,
items=items, value=value), value, state)
@property
def accept_iterator(self):
return self.testValueList
class DictConverter(FancyValidator):
"""
Converts values based on a dictionary which has values as keys for
the resultant values.
If ``allowNull`` is passed, it will not balk if a false value
(e.g., '' or None) is given (it will return None in these cases).
to_python takes keys and gives values, from_python takes values and
gives keys.
If you give hideDict=True, then the contents of the dictionary
will not show up in error messages.
Examples::
>>> dc = DictConverter({1: 'one', 2: 'two'})
>>> dc.to_python(1)
'one'
>>> dc.from_python('one')
1
>>> dc.to_python(3)
Traceback (most recent call last):
....
Invalid: Enter a value from: 1; 2
>>> dc2 = dc(hideDict=True)
>>> dc2.hideDict
True
>>> dc2.dict
{1: 'one', 2: 'two'}
>>> dc2.to_python(3)
Traceback (most recent call last):
....
Invalid: Choose something
>>> dc.from_python('three')
Traceback (most recent call last):
....
Invalid: Nothing in my dictionary goes by the value 'three'. Choose one of: 'one'; 'two'
"""
messages = dict(
keyNotFound=_('Choose something'),
chooseKey=_('Enter a value from: %(items)s'),
valueNotFound=_('That value is not known'),
chooseValue=_('Nothing in my dictionary goes by the value %(value)s.'
' Choose one of: %(items)s'))
dict = None
hideDict = False
__unpackargs__ = ('dict',)
def _convert_to_python(self, value, state):
try:
return self.dict[value]
except KeyError:
if self.hideDict:
raise Invalid(self.message('keyNotFound', state), value, state)
else:
items = sorted(self.dict)
items = '; '.join(map(repr, items))
raise Invalid(self.message('chooseKey',
state, items=items), value, state)
def _convert_from_python(self, value, state):
for k, v in self.dict.items():
if value == v:
return k
if self.hideDict:
raise Invalid(self.message('valueNotFound', state), value, state)
items = '; '.join(map(repr, self.dict.values()))
raise Invalid(
self.message('chooseValue', state,
value=repr(value), items=items), value, state)
class IndexListConverter(FancyValidator):
"""
Converts a index (which may be a string like '2') to the value in
the given list.
Examples::
>>> index = IndexListConverter(['zero', 'one', 'two'])
>>> index.to_python(0)
'zero'
>>> index.from_python('zero')
0
>>> index.to_python('1')
'one'
>>> index.to_python(5)
Traceback (most recent call last):
Invalid: Index out of range
>>> index(not_empty=True).to_python(None)
Traceback (most recent call last):
Invalid: Please enter a value
>>> index.from_python('five')
Traceback (most recent call last):
Invalid: Item 'five' was not found in the list
"""
list = None
__unpackargs__ = ('list',)
messages = dict(
integer=_('Must be an integer index'),
outOfRange=_('Index out of range'),
notFound=_('Item %(value)s was not found in the list'))
def _convert_to_python(self, value, state):
try:
value = int(value)
except (ValueError, TypeError):
raise Invalid(self.message('integer', state), value, state)
try:
return self.list[value]
except IndexError:
raise Invalid(self.message('outOfRange', state), value, state)
def _convert_from_python(self, value, state):
for i, v in enumerate(self.list):
if v == value:
return i
raise Invalid(
self.message('notFound', state, value=repr(value)), value, state)
class DateValidator(FancyValidator):
"""
Validates that a date is within the given range. Be sure to call
DateConverter first if you aren't expecting mxDateTime input.
``earliest_date`` and ``latest_date`` may be functions; if so,
they will be called each time before validating.
``after_now`` means a time after the current timestamp; note that
just a few milliseconds before now is invalid! ``today_or_after``
is more permissive, and ignores hours and minutes.
Examples::
>>> from datetime import datetime, timedelta
>>> d = DateValidator(earliest_date=datetime(2003, 1, 1))
>>> d.to_python(datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> d.to_python(datetime(2002, 1, 1))
Traceback (most recent call last):
...
Invalid: Date must be after Wednesday, 01 January 2003
>>> d.to_python(datetime(2003, 1, 1))
datetime.datetime(2003, 1, 1, 0, 0)
>>> d = DateValidator(after_now=True)
>>> now = datetime.now()
>>> d.to_python(now+timedelta(seconds=5)) == now+timedelta(seconds=5)
True
>>> d.to_python(now-timedelta(days=1))
Traceback (most recent call last):
...
Invalid: The date must be sometime in the future
>>> d.to_python(now+timedelta(days=1)) > now
True
>>> d = DateValidator(today_or_after=True)
>>> d.to_python(now) == now
True
"""
earliest_date = None
latest_date = None
after_now = False
# Like after_now, but just after this morning:
today_or_after = False
# Use None or 'datetime' for the datetime module in the standard lib,
# or 'mxDateTime' to force the mxDateTime module
datetime_module = None
messages = dict(
after=_('Date must be after %(date)s'),
before=_('Date must be before %(date)s'),
# Double %'s, because this will be substituted twice:
date_format=_('%%A, %%d %%B %%Y'),
future=_('The date must be sometime in the future'))
def _validate_python(self, value, state):
date_format = self.message('date_format', state)
if self.earliest_date:
if callable(self.earliest_date):
earliest_date = self.earliest_date()
else:
earliest_date = self.earliest_date
if value < earliest_date:
date_formatted = earliest_date.strftime(date_format)
raise Invalid(
self.message('after', state, date=date_formatted),
value, state)
if self.latest_date:
if callable(self.latest_date):
latest_date = self.latest_date()
else:
latest_date = self.latest_date
if value > latest_date:
date_formatted = latest_date.strftime(date_format)
raise Invalid(
self.message('before', state, date=date_formatted),
value, state)
if self.after_now:
dt_mod = import_datetime(self.datetime_module)
now = datetime_now(dt_mod)
if value < now:
date_formatted = now.strftime(date_format)
raise Invalid(
self.message('future', state, date=date_formatted),
value, state)
if self.today_or_after:
dt_mod = import_datetime(self.datetime_module)
now = datetime_now(dt_mod)
today = datetime_makedate(dt_mod,
now.year, now.month, now.day)
value_as_date = datetime_makedate(
dt_mod, value.year, value.month, value.day)
if value_as_date < today:
date_formatted = now.strftime(date_format)
raise Invalid(
self.message('future', state, date=date_formatted),
value, state)
class Bool(FancyValidator):
"""
Always Valid, returns True or False based on the value and the
existance of the value.
If you want to convert strings like ``'true'`` to booleans, then
use ``StringBool``.
Examples::
>>> Bool.to_python(0)
False
>>> Bool.to_python(1)
True
>>> Bool.to_python('')
False
>>> Bool.to_python(None)
False
"""
if_missing = False
def _convert_to_python(self, value, state):
return bool(value)
_convert_from_python = _convert_to_python
def empty_value(self, value):
return False
class RangeValidator(FancyValidator):
"""This is an abstract base class for Int and Number.
It verifies that a value is within range. It accepts min and max
values in the constructor.
(Since this is an abstract base class, the tests are in Int and Number.)
"""
messages = dict(
tooLow=_('Please enter a number that is %(min)s or greater'),
tooHigh=_('Please enter a number that is %(max)s or smaller'))
min = None
max = None
def _validate_python(self, value, state):
if self.min is not None:
if value < self.min:
msg = self.message('tooLow', state, min=self.min)
raise Invalid(msg, value, state)
if self.max is not None:
if value > self.max:
msg = self.message('tooHigh', state, max=self.max)
raise Invalid(msg, value, state)
class Int(RangeValidator):
"""Convert a value to an integer.
Example::
>>> Int.to_python('10')
10
>>> Int.to_python('ten')
Traceback (most recent call last):
...
Invalid: Please enter an integer value
>>> Int(min=5).to_python('6')
6
>>> Int(max=10).to_python('11')
Traceback (most recent call last):
...
Invalid: Please enter a number that is 10 or smaller
"""
messages = dict(
integer=_('Please enter an integer value'))
def _convert_to_python(self, value, state):
try:
return int(value)
except (ValueError, TypeError):
raise Invalid(self.message('integer', state), value, state)
_convert_from_python = _convert_to_python
class Number(RangeValidator):
"""Convert a value to a float or integer.
Tries to convert it to an integer if no information is lost.
Example::
>>> Number.to_python('10')
10
>>> Number.to_python('10.5')
10.5
>>> Number.to_python('ten')
Traceback (most recent call last):
...
Invalid: Please enter a number
>>> Number.to_python([1.2])
Traceback (most recent call last):
...
Invalid: Please enter a number
>>> Number(min=5).to_python('6.5')
6.5
>>> Number(max=10.5).to_python('11.5')
Traceback (most recent call last):
...
Invalid: Please enter a number that is 10.5 or smaller
"""
messages = dict(
number=_('Please enter a number'))
def _convert_to_python(self, value, state):
try:
value = float(value)
try:
int_value = int(value)
except OverflowError:
int_value = None
if value == int_value:
return int_value
return value
except (ValueError, TypeError):
raise Invalid(self.message('number', state), value, state)
class ByteString(FancyValidator):
"""Convert to byte string, treating empty things as the empty string.
Also takes a `max` and `min` argument, and the string length must fall
in that range.
Also you may give an `encoding` argument, which will encode any unicode
that is found. Lists and tuples are joined with `list_joiner`
(default ``', '``) in ``from_python``.
::
>>> ByteString(min=2).to_python('a')
Morty Proxy This is a proxified and sanitized view of the page, visit original site.