-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.py
1043 lines (859 loc) · 31.3 KB
/
validator.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
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
# -*- coding:utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2014 Samuel Lucidi
"""
validator.py
A library for validating that dictionary
values fit inside of certain sets of parameters.
Author: Samuel Lucidi <sam@samlucidi.com>
url: https://github.com/mansam/validator.py
"""
__doc__ = "入参校验装饰器"
__version__ = "1.2.8"
import re
import copy
import datetime
import traceback
from functools import wraps
from collections import namedtuple, defaultdict, OrderedDict
from abc import ABCMeta, abstractmethod
from inspect import getargspec # , getfullargspec , signature
from flask import jsonify, request
from werkzeug.datastructures import MultiDict
try:
# python 3
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
ValidationResult = namedtuple('ValidationResult', ['valid', 'errors'])
# Taken from https://github.com/kvesteri/validators/blob/master/validators/email.py
USER_REGEX = re.compile(
# dot-atom
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+"
r"(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$"
# quoted-string
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|'
r"""\\[\001-\011\013\014\016-\177])*"$)""",
re.IGNORECASE
)
DOMAIN_REGEX = re.compile(
# domain
r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?$)'
# literal form, ipv4 address (SMTP 4.1.3)
r'|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)'
r'(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$',
re.IGNORECASE)
def is_str(s):
"""
Python 2/3 compatible check to see
if an object is a string type.
"""
try:
return isinstance(s, str)
except NameError:
return isinstance(s, basestring)
# def ChangeType(instance, new_type):
# try:
# instance = new_type(instance)
# return instance
# except Exception as e:
# return False
class Validator(object):
"""
Abstract class that advanced
validators can inherit from in order
to set custom error messages and such.
"""
__metaclass__ = ABCMeta
err_message = "failed validation"
not_message = "failed validation"
@abstractmethod
def __call__(self, *args, **kwargs):
raise NotImplementedError
class Isalnum(Validator):
"""判断字符串中只能由字母和数字的组合,不能有特殊符号"""
def __init__(self):
self.err_message = "must be numbers and letters"
self.not_message = "must not be numbers and letters"
def __call__(self, value):
if is_str(value):
return value.isalnum()
else:
return False
class Isalpha(Validator):
"""字符串里面都是字母,并且至少是一个字母,结果就为真,(汉字也可以)其他情况为假"""
def __init__(self):
self.err_message = "must be all letters"
self.not_message = "must not be all letters"
def __call__(self, value):
if is_str(value):
# if isinstance(value, str) or isinstance(value, unicode):
return value.isalpha()
else:
return False
class Isdigit(Validator):
"""函数判断是否全为数字"""
def __init__(self):
self.err_message = "must be all numbers"
self.not_message = "must not be all numbers"
def __call__(self, value):
if is_str(value):
return value.isdigit()
else:
return False
class Email(Validator):
"""Verify that the value is an Email or not.
"""
def __init__(self):
self.err_message = "Invalid Email"
self.not_message = "Invalid Email"
def __call__(self, value):
try:
if not value or "@" not in value:
return False
user_part, domain_part = value.rsplit('@', 1)
if not (USER_REGEX.match(user_part) and DOMAIN_REGEX.match(domain_part)):
return False
return True
except:
return False
class Datetime(Validator):
"""Validate that the value matches the datetime format."""
DEFAULT_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
def __init__(self, format=None):
self.format = format or self.DEFAULT_FORMAT
self.err_message = "Invalid Datetime format"
self.not_message = "Invalid Datetime format"
def __call__(self, v):
try:
datetime.datetime.strptime(v, self.format)
except (TypeError, ValueError):
return False
return True
def __repr__(self):
return 'Datetime(format=%s)' % self.format
class Date(Validator):
"""Validate that the value matches the date format."""
DEFAULT_FORMAT = '%Y-%m-%d'
def __init__(self, format=None):
self.format = format or self.DEFAULT_FORMAT
self.err_message = "Invalid Date format"
self.not_message = "Invalid Date format"
def __call__(self, v):
try:
datetime.datetime.strptime(v, self.format)
except (TypeError, ValueError):
return False
return True
def __repr__(self):
return 'Date(format=%s)' % self.format
class In(Validator):
"""
Use to specify that the
value of the key being
validated must exist
within the collection
passed to this validator.
# Example:
validations = {
"field": [In([1, 2, 3])]
}
passes = {"field":1}
fails = {"field":4}
"""
def __init__(self, collection):
self.collection = collection
self.err_message = "must be one of %r" % collection
self.not_message = "must not be one of %r" % collection
def __call__(self, value):
return (value in self.collection)
class Not(Validator):
"""
Use to negate the requirement
of another validator. Does not
work with Required.
"""
def __init__(self, validator):
self.validator = validator
self.err_message = getattr(validator, "not_message", "failed validation")
self.not_message = getattr(validator, "err_message", "failed validation")
def __call__(self, value):
return not self.validator(value)
class Range(Validator):
"""
Use to specify that the value of the
key being validated must fall between
the start and end values. By default
the range is inclusive, though the
range can be made excusive by setting
inclusive to false.
# Example:
validations = {
"field": [Range(0, 10)]
}
passes = {"field": 10}
fails = {"field" : 11}
"""
def __init__(self, start, end, reverse=True, auto=True):
self.start = start
self.end = end
self.reverse = reverse
self.auto = auto
self.err_message = "must fall between %s and %s" % (start, end)
self.not_message = "must not fall between %s and %s" % (start, end)
def __call__(self, value):
if self.auto:
value = float(value)
if self.reverse:
return self.start <= value <= self.end
else:
return self.start < value < self.end
class GreaterThan(Validator):
"""
Use to specify that the value of the
key being validated must be greater
than a given value. By default the
bound is exclusive, though the bound
can be made inclusive by setting
inclusive to true.
# Example:
validations = {
"field": [GreaterThan(10)]
}
passes = {"field": 11}
fails = {"field" : 10}
"""
def __init__(self, lower_bound, reverse=False, auto=True):
self.lower_bound = lower_bound
self.reverse = reverse
self.auto = auto
self.err_message = "must be greater than %s" % lower_bound
self.not_message = "must not be greater than %s" % lower_bound
def __call__(self, value):
if self.auto:
value = float(value)
if self.reverse:
return self.lower_bound <= value
else:
return self.lower_bound < value
class Equals(Validator):
"""
Use to specify that the
value of the key being
validated must be equal to
the value that was passed
to this validator.
# Example:
validations = {
"field": [Equals(1)]
}
passes = {"field":1}
fails = {"field":4}
"""
def __init__(self, obj):
self.obj = obj
self.err_message = "must be equal to %r" % obj
self.not_message = "must not be equal to %r" % obj
def __call__(self, value):
return value == self.obj
class Blank(Validator):
"""
Use to specify that the
value of the key being
validated must be equal to
the empty string.
This is a shortcut for saying
Equals("").
# Example:
validations = {
"field": [Blank()]
}
passes = {"field":""}
fails = {"field":"four"}
"""
def __init__(self):
self.err_message = "must be an empty string"
self.not_message = "must not be an empty string"
def __call__(self, value):
return value == ""
class Truthy(Validator):
"""
Use to specify that the
value of the key being
validated must be truthy,
i.e. would cause an if statement
to evaluate to True.
# Example:
validations = {
"field": [Truthy()]
}
passes = {"field": 1}
fails = {"field": 0}
"""
def __init__(self):
self.err_message = "must be True-equivalent value"
self.not_message = "must be False-equivalent value"
def __call__(self, value):
if value:
return True
else:
return False
def Required(field, dictionary):
"""
When added to a list of validations
for a dictionary key indicates that
the key must be present. This
should not be called, just inserted
into the list of validations.
# Example:
validations = {
"field": [Required, Equals(2)]
}
By default, keys are considered
optional and their validations
will just be ignored if the field
is not present in the dictionary
in question.
"""
return (field in dictionary)
class InstanceOf(Validator):
"""
Use to specify that the
value of the key being
validated must be an instance
of the passed in base class
or its subclasses.
# Example:
validations = {
"field": [InstanceOf(basestring)]
}
passes = {"field": ""} # is a <'str'>, subclass of basestring
fails = {"field": str} # is a <'type'>
"""
def __init__(self, base_class):
self.base_class = base_class
self.err_message = "must be an instance of %s or its subclasses" % base_class.__name__
self.not_message = "must not be an instance of %s or its subclasses" % base_class.__name__
def __call__(self, value):
return isinstance(value, self.base_class)
class SubclassOf(Validator):
"""
Use to specify that the
value of the key being
validated must be a subclass
of the passed in base class.
# Example:
validations = {
"field": [SubclassOf(basestring)]
}
passes = {"field": str} # is a subclass of basestring
fails = {"field": int}
"""
def __init__(self, base_class):
self.base_class = base_class
self.err_message = "must be a subclass of %s" % base_class.__name__
self.not_message = "must not be a subclass of %s" % base_class.__name__
def __call__(self, class_):
return issubclass(class_, self.base_class)
class Pattern(Validator):
"""
Use to specify that the
value of the key being
validated must match the
pattern provided to the
validator.
# Example:
validations = {
"field": [Pattern('\d\d\%')]
}
passes = {"field": "30%"}
fails = {"field": "30"}
"""
def __init__(self, pattern):
self.pattern = pattern
self.err_message = "must match regex pattern %s" % pattern
self.not_message = "must not match regex pattern %s" % pattern
self.compiled = re.compile(pattern)
def __call__(self, value):
return self.compiled.match(value)
class Then(Validator):
"""
Special validator for use as
part of the If rule.
If the conditional part of the validation
passes, then this is used to apply another
set of dependent rules.
# Example:
validations = {
"foo": [If(Equals(1), Then({"bar": [Equals(2)]}))]
}
passes = {"foo": 1, "bar": 2}
also_passes = {"foo": 2, "bar": 3}
fails = {"foo": 1, "bar": 3}
"""
def __init__(self, validation):
self.validation = validation
def __call__(self, dictionary):
return validate(self.validation, dictionary)
class If(Validator):
"""
Special conditional validator.
If the validator passed as the first
parameter to this function passes,
then a second set of rules will be
applied to the dictionary.
# Example:
validations = {
"foo": [If(Equals(1), Then({"bar": [Equals(2)]}))]
}
passes = {"foo": 1, "bar": 2}
also_passes = {"foo": 2, "bar": 3}
fails = {"foo": 1, "bar": 3}
"""
def __init__(self, validator, then_clause):
self.validator = validator
self.then_clause = then_clause
def __call__(self, value, dictionary):
conditional = False
dependent = None
if self.validator(value):
conditional = True
dependent = self.then_clause(dictionary)
return conditional, dependent
class Length(Validator):
"""
Use to specify that the
value of the key being
validated must have at least
`minimum` elements and optionally
at most `maximum` elements.
At least one of the parameters
to this validator must be non-zero,
and neither may be negative.
# Example:
validations = {
"field": [Length(0, maximum=5)]
}
passes = {"field": "hello"}
fails = {"field": "hello world"}
"""
err_messages = {
"maximum": "must be at most {0} elements in length",
"minimum": "must be at least {0} elements in length",
"range": "must{0}be between {1} and {2} elements in length"
}
def __init__(self, minimum, maximum=0):
if not minimum and not maximum:
raise ValueError("Length must have a non-zero minimum or maximum parameter.")
if minimum < 0 or maximum < 0:
raise ValueError("Length cannot have negative parameters.")
self.minimum = minimum
self.maximum = maximum
if minimum and maximum:
self.err_message = self.err_messages["range"].format(' ', minimum, maximum)
self.not_message = self.err_messages["range"].format(' not ', minimum, maximum)
elif minimum:
self.err_message = self.err_messages["minimum"].format(minimum)
self.not_message = self.err_messages["maximum"].format(minimum - 1)
elif maximum:
self.err_message = self.err_messages["maximum"].format(maximum)
self.not_message = self.err_messages["minimum"].format(maximum + 1)
def __call__(self, value):
if self.maximum:
return self.minimum <= len(value) <= self.maximum
else:
return self.minimum <= len(value)
class Contains(Validator):
"""
Use to ensure that the value of the key
being validated contains the value passed
into the Contains validator. Works with
any type that supports the 'in' syntax.
# Example:
validations = {
"field": [Contains(3)]
}
passes = {"field": [1, 2, 3]}
fails = {"field": [4, 5, 6]}
"""
def __init__(self, contained):
self.contained = contained
self.err_message = "must contain {0}".format(contained)
self.not_message = "must not contain {0}".format(contained)
def __call__(self, container):
return self.contained in container
class Each(Validator):
"""
Use to ensure that
If Each is passed a list of validators, it
just applies each of them to each element in
the list.
If it's instead passed a *dictionary*, it treats
it as a validation to be applied to each element in
the dictionary.
"""
def __init__(self, validations):
assert isinstance(validations, (list, tuple, set, dict))
self.validations = validations
def __call__(self, container):
assert isinstance(container, (list, tuple, set))
# handle the "apply simple validation to each in list"
# use case
if isinstance(self.validations, (list, tuple, set)):
errors = []
for item in container:
for v in self.validations:
valid = v(item)
if not valid:
errors.append("all values " + v.err_message)
# handle the somewhat messier list of dicts case
if isinstance(self.validations, dict):
errors = defaultdict(list)
for index, item in enumerate(container):
valid, err = validate(self.validations, item)
if not valid:
errors[index] = err
errors = dict(errors)
return (len(errors) == 0, errors)
class Url(Validator):
"""
Use to specify that the
value of the key being
validated must be a Url.
This is a shortcut for saying
Url().
# Example:
validations = {
"field": [Url()]
}
passes = {"field":"http://vk.com"}
fails = {"field":"/1https://vk.com"}
"""
def __init__(self):
self.err_message = "must be a valid URL"
self.not_message = "must not be a valid URL"
def __call__(self, value):
try:
result = urlparse(value)
return all([result.scheme, result.netloc])
except:
return False
class DoUtil:
@classmethod
def do_default(cls, args_dict, default):
"""
入参时写入到数据库不好看,转换成None
:param args_dict:
:param default:
:return:
"""
if default[0]:
for x in args_dict:
if args_dict[x] == "":
args_dict[x] = default[1]
@classmethod
def do_rules(cls, args_dict, rules):
"""
参数校验的核心
:param args_dict:
:param rules:
:return:
"""
if not args_dict:
return True, None
result, err = validate(rules, args_dict)
return result, err
@classmethod
def do_func(cls, args_dict, diy_func, modify=True):
"""
执行自定义函数,一般用来修正某些入参
:param args_dict:
:param diy_func:
:param modify:
:return:
"""
if not args_dict:
return True, None
if modify:
for k in args_dict:
if k in diy_func:
args_dict[k] = diy_func[k](args_dict[k])
@classmethod
def do_strip(cls, args_dict, modify=True):
"""
检测字符串前后空格,modify=True就自动剔除前后空格,否则就检测并报错
:param args_dict:
:param modify:
:return:
"""
if modify:
for k in args_dict:
if args_dict[k] and is_str(args_dict[k]):
if args_dict[k][0] == " " or args_dict[k][-1] == " ":
args_dict[k] = args_dict[k].strip()
else:
for k in args_dict:
if args_dict[k] and is_str(args_dict[k]):
if args_dict[k][0] == " " or args_dict[k][-1] == " ":
return False, "%s should not contain spaces" % k
return True, None
class _UtilHandler:
@classmethod
def limits(cls, dict_args, strip, modify, default, diy_func, rules):
data = None
if dict_args.get("json", False):
data = request.json
result, err = cls.check(data, strip, modify, default, diy_func, rules)
if not result:
return result, err
if dict_args.get("args", True) or dict_args.get("values", False):
data = request.args
result, err = cls.check(data, strip, modify, default, diy_func, rules)
if not result:
return result, err
if dict_args.get("form", False) or dict_args.get("values", False):
data = request.form
result, err = cls.check(data, strip, modify, default, diy_func, rules)
if not result:
return result, err
return True, data
@classmethod
def check(cls, data, strip, modify, default, diy_func, rules):
if strip:
result, err = DoUtil.do_strip(data, modify=modify)
if not result:
return result, err
if diy_func:
DoUtil.do_func(data, diy_func, modify=modify)
if rules:
result, err = DoUtil.do_rules(data, rules)
if not result:
return result, err
DoUtil.do_default(data, default)
return True, None
@classmethod
def arrange_args(cls, args, kwargs, f):
"""
参数规整
:param args: 位置和可变长参数
:param kwargs: 字典参数
:param f: 函数
:return: 解析后的位置参数和字典参数
"""
args_dict = OrderedDict()
kwargs_dict = OrderedDict()
args_template = getargspec(f)
kwargs_dict.update(kwargs)
# 多退少补
index_of_defaults = 0
index_of_args = 0
for i, k in enumerate(args_template.args):
try:
args_dict[k] = args[i]
except IndexError as e:
args_dict[k] = args_template.defaults[index_of_defaults]
index_of_defaults += 1
index_of_args += 1
if args_template.varargs:
args_dict[args_template.varargs] = args[index_of_args:]
return args_dict, kwargs_dict
@classmethod
def _validate_and_store_errs(cls, validator, dictionary, key, errors):
# Validations shouldn't throw exceptions because of
# type mismatches and the like. If the rule is 'Length(5)' and
# the value in the field is 5, that should be a validation failure,
# not a TypeError because you can't call len() on an int.
# It's not ideal to have to hide exceptions like this because
# there could be actual problems with a validator, but we're just going
# to have to rely on tests preventing broken things.
try:
valid = validator(dictionary[key])
except Exception:
# Since we caught an exception while trying to validate,
# treat it as a failure and return the normal error message
# for that validator.
valid = (False, validator.err_message)
if isinstance(valid, tuple):
valid, errs = valid
if errs and isinstance(errs, list):
errors[key] += errs
elif errs:
errors[key].append(errs)
elif not valid:
# set a default error message for things like lambdas
# and other callables that won't have an err_message set.
msg = getattr(validator, "err_message", "failed validation")
errors[key].append(msg)
@classmethod
def _validate_list_helper(cls, validation, dictionary, key, errors):
for v in validation[key]:
# don't break on optional keys
if key in dictionary:
# Ok, need to deal with nested
# validations.
if isinstance(v, dict):
_, nested_errors = validate(v, dictionary[key])
if nested_errors:
errors[key].append(nested_errors)
continue
# Done with that, on to the actual
# validating bit.
# Skip Required, since it was already
# handled before this point.
if not v == Required:
# special handling for the
# If(Then()) form
if isinstance(v, If):
conditional, dependent = v(dictionary[key], dictionary)
# if the If() condition passed and there were errors
# in the second set of rules, then add them to the
# list of errors for the key with the condtional
# as a nested dictionary of errors.
if conditional and dependent[1]:
errors[key].append(dependent[1])
# handling for normal validators
else:
cls._validate_and_store_errs(v, dictionary, key, errors)
def validate(validation, dictionary):
"""
Validate that a dictionary passes a set of
key-based validators. If all of the keys
in the dictionary are within the parameters
specified by the validation mapping, then
the validation passes.
:param validation: a mapping of keys to validators
:type validation: dict
:param dictionary: dictionary to be validated
:type dictionary: dict
:return: a tuple containing a bool indicating
success or failure and a mapping of fields
to error messages.
"""
errors = defaultdict(list)
for key in validation:
if isinstance(validation[key], (list, tuple)):
if Required in validation[key]:
if not Required(key, dictionary):
errors[key] = "must be present"
continue
_UtilHandler._validate_list_helper(validation, dictionary, key, errors)
else:
v = validation[key]
if v == Required:
if not Required(key, dictionary):
errors[key] = "must be present"
else:
_UtilHandler._validate_and_store_errs(v, dictionary, key, errors)
if len(errors) > 0:
# `errors` gets downgraded from defaultdict to dict
# because it makes for prettier output
return ValidationResult(valid=False, errors=dict(errors))
else:
return ValidationResult(valid=True, errors={})
# hook func
def validator_func(rules, strip=True, default=(False, None), diy_func=None, release=False):
"""针对普通函数的参数校验的装饰器 --- arbitrary argument lists(任意长参数)
:param rules:参数的校验规则,map
:param strip:对字段进行前后过滤空格
:param default:将"" 装换成None
:param diy_func:自定义的对某一参数的校验函数格式: {key:func},类似check, diy_func={"a": lambda x: x + "aa"})
:param release:发生参数校验异常后是否依然让参数进入主流程函数
"""
def decorator(f):
@wraps(f)
def decorated_func(*args, **kwargs):
if release:
args_bak = args[:]
kwargs_bak = copy.deepcopy(kwargs) # 下面流程异常时,是否直接使用 原参数传入f # fixme
try:
args_dict, kwargs_dict = _UtilHandler.arrange_args(args, kwargs, f)
# strip
if strip:
DoUtil.do_strip(args_dict, modify=True)
DoUtil.do_strip(kwargs_dict, modify=True)
DoUtil.do_default(args_dict, default)
# diy_func
if diy_func:
DoUtil.do_func(args_dict, diy_func, modify=True)
DoUtil.do_func(kwargs_dict, diy_func, modify=True)
# rules
if rules:
args_dict_bak = copy.deepcopy(args_dict)
args_dict_bak.update(kwargs_dict)
result, err = validate(rules, args_dict_bak)
if not result:
return False, err
except Exception as e:
print("validator_arbitrary_args catch err: ", traceback.format_exc())
if release:
return f(*args_bak, **kwargs_bak)
else:
return False, str(e)
return f(*args_dict.values(), **kwargs_dict)
return decorated_func
return decorator
def validator_sub(rules, strip=True, default=(False, None), diy_func=None, release=False):
"""返回dict,代替request.values/request.json使用,这个方法比较low ...
:param rules:参数的校验规则,map
:param strip:对字段进行前后过滤空格
:param default:将"" 装换成None
:param diy_func:自定义的对某一参数的校验函数格式: {key:func},类似check, diy_func={"a": lambda x: x + "aa"})
:param release:发生参数校验异常后是否依然让参数进入主流程函数
"""
args_dict = OrderedDict()
try:
if request.values:
args_dict.update(request.values)
if request.json:
args_dict.update(request.json)
if release:
args_dict_copy = copy.deepcopy(args_dict) # 下面流程异常时,是否直接使用 原参数传入f # fixme
# strip
if strip:
DoUtil.do_strip(args_dict, modify=True)
# default
DoUtil.do_default(args_dict, default)
# diy_func
if diy_func:
DoUtil.do_func(args_dict, diy_func, modify=True)
# rules
if rules:
result, err = DoUtil.do_rules(args_dict, rules)