-
Notifications
You must be signed in to change notification settings - Fork 16
/
peewee_validates.py
1025 lines (818 loc) · 35.4 KB
/
peewee_validates.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
"""peewee-validates is a validator module designed to work with the Peewee ORM."""
import datetime
import re
from decimal import Decimal
from decimal import InvalidOperation
from inspect import isgeneratorfunction
from inspect import isgenerator
from collections import Iterable
import peewee
from dateutil.parser import parse as dateutil_parse
try:
from playhouse.fields import ManyToManyField
except ImportError:
from peewee import ManyToManyField
__version__ = '1.0.8'
__all__ = [
'Field', 'Validator', 'ModelValidator', 'ValidationError', 'StringField', 'FloatField',
'IntegerField', 'DecimalField', 'DateField', 'TimeField', 'DateTimeField', 'BooleanField',
'ModelChoiceField', 'ManyModelChoiceField',
]
PEEWEE3 = peewee.__version__ >= '3.0.0'
DEFAULT_MESSAGES = {
'required': 'This field is required.',
'empty': 'This field must not be blank.',
'one_of': 'Must be one of the choices: {choices}.',
'none_of': 'Must not be one of the choices: {choices}.',
'equal': 'Must be equal to {other}.',
'regexp': 'Must match the pattern {pattern}.',
'matches': 'Must match the field {other}.',
'email': 'Must be a valid email address.',
'function': 'Failed validation for {function}.',
'length_high': 'Must be at most {high} characters.',
'length_low': 'Must be at least {low} characters.',
'length_between': 'Must be between {low} and {high} characters.',
'length_equal': 'Must be exactly {equal} characters.',
'range_high': 'Must be at most {high}.',
'range_low': 'Must be at least {low}.',
'range_between': 'Must be between {low} and {high}.',
'coerce_decimal': 'Must be a valid decimal.',
'coerce_date': 'Must be a valid date.',
'coerce_time': 'Must be a valid time.',
'coerce_datetime': 'Must be a valid datetime.',
'coerce_float': 'Must be a valid float.',
'coerce_int': 'Must be a valid integer.',
'related': 'Unable to find object with {field} = {values}.',
'list': 'Must be a list of values',
'unique': 'Must be a unique value.',
'index': 'Fields must be unique together.',
}
class ValidationError(Exception):
"""An exception class that should be raised when a validation error occurs on data."""
def __init__(self, key, *args, **kwargs):
self.key = key
self.kwargs = kwargs
super().__init__(*args)
def validate_required():
"""
Validate that a field is present in the data.
:raises: ``ValidationError('required')``
"""
def required_validator(field, data):
if field.value is None:
raise ValidationError('required')
return required_validator
def validate_not_empty():
"""
Validate that a field is not empty (blank string).
:raises: ``ValidationError('empty')``
"""
def empty_validator(field, data):
if isinstance(field.value, str) and not field.value.strip():
raise ValidationError('empty')
return empty_validator
def validate_length(low=None, high=None, equal=None):
"""
Validate the length of a field with either low, high, or equal.
Should work with anything that supports len().
:param low: Smallest length required.
:param high: Longest length required.
:param equal: Exact length required.
:raises: ``ValidationError('length_low')``
:raises: ``ValidationError('length_high')``
:raises: ``ValidationError('length_between')``
:raises: ``ValidationError('length_equal')``
"""
def length_validator(field, data):
if field.value is None:
return
if equal is not None and len(field.value) != equal:
raise ValidationError('length_equal', equal=equal)
if low is not None and len(field.value) < low:
key = 'length_low' if high is None else 'length_between'
raise ValidationError(key, low=low, high=high)
if high is not None and len(field.value) > high:
key = 'length_high' if low is None else 'length_between'
raise ValidationError(key, low=low, high=high)
return length_validator
def validate_one_of(values):
"""
Validate that a field is in one of the given values.
:param values: Iterable of valid values.
:raises: ``ValidationError('one_of')``
"""
def one_of_validator(field, data):
if field.value is None:
return
options = values
if callable(options):
options = options()
if field.value not in options:
raise ValidationError('one_of', choices=', '.join(map(str, options)))
return one_of_validator
def validate_none_of(values):
"""
Validate that a field is not in one of the given values.
:param values: Iterable of invalid values.
:raises: ``ValidationError('none_of')``
"""
def none_of_validator(field, data):
options = values
if callable(options):
options = options()
if field.value in options:
raise ValidationError('none_of', choices=str.join(', ', options))
return none_of_validator
def validate_range(low=None, high=None):
"""
Validate the range of a field with either low, high, or equal.
Should work with anything that supports '>' and '<' operators.
:param low: Smallest value required.
:param high: Longest value required.
:raises: ``ValidationError('range_low')``
:raises: ``ValidationError('range_high')``
:raises: ``ValidationError('range_between')``
"""
def range_validator(field, data):
if field.value is None:
return
if low is not None and field.value < low:
key = 'range_low' if high is None else 'range_between'
raise ValidationError(key, low=low, high=high)
if high is not None and field.value > high:
key = 'range_high' if high is None else 'range_between'
raise ValidationError(key, low=low, high=high)
return range_validator
def validate_equal(value):
"""
Validate the field value is equal to the given value.
Should work with anything that supports '==' operator.
:param value: Value to compare.
:raises: ``ValidationError('equal')``
"""
def equal_validator(field, data):
if field.value is None:
return
if not (field.value == value):
raise ValidationError('equal', other=value)
return equal_validator
def validate_matches(other):
"""
Validate the field value is equal to another field in the data.
Should work with anything that supports '==' operator.
:param value: Field key to compare.
:raises: ``ValidationError('matches')``
"""
def matches_validator(field, data):
if field.value is None:
return
if not (field.value == data.get(other)):
raise ValidationError('matches', other=other)
return matches_validator
def validate_regexp(pattern, flags=0):
"""
Validate the field matches the given regular expression.
Should work with anything that supports '==' operator.
:param pattern: Regular expresion to match. String or regular expression instance.
:param pattern: Flags for the regular expression.
:raises: ``ValidationError('equal')``
"""
regex = re.compile(pattern, flags) if isinstance(pattern, str) else pattern
def regexp_validator(field, data):
if field.value is None:
return
if regex.match(str(field.value)) is None:
raise ValidationError('regexp', pattern=pattern)
return regexp_validator
def validate_function(method, **kwargs):
"""
Validate the field matches the result of calling the given method. Example::
def myfunc(value, name):
return value == name
validator = validate_function(myfunc, name='tim')
Essentially creates a validator that only accepts the name 'tim'.
:param method: Method to call.
:param kwargs: Additional keyword arguments passed to the method.
:raises: ``ValidationError('function')``
"""
def function_validator(field, data):
if field.value is None:
return
if not method(field.value, **kwargs):
raise ValidationError('function', function=method.__name__)
return function_validator
def validate_email():
"""
Validate the field is a valid email address.
:raises: ``ValidationError('email')``
"""
user_regex = re.compile(
r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$"
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
r'|\\[\001-\011\013\014\016-\177])*"$)', re.IGNORECASE | re.UNICODE)
domain_regex = re.compile(
r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$'
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 | re.UNICODE)
domain_whitelist = ('localhost',)
def email_validator(field, data):
if field.value is None:
return
value = str(field.value)
if '@' not in value:
raise ValidationError('email')
user_part, domain_part = value.rsplit('@', 1)
if not user_regex.match(user_part):
raise ValidationError('email')
if domain_part in domain_whitelist:
return
if not domain_regex.match(domain_part):
raise ValidationError('email')
return email_validator
def validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None):
"""
Validate the field is a unique, given a queryset and lookup_field. Example::
validator = validate_model_unique(User.email, User.select())
Creates a validator that can validate the uniqueness of an email address.
:param lookup_field: Peewee model field that should be used for checking existing values.
:param queryset: Queryset to use for lookup.
:param pk_field: Field instance to use when excluding existing instance.
:param pk_value: Field value to use when excluding existing instance.
:raises: ``ValidationError('unique')``
"""
def unique_validator(field, data):
# If we have a PK, ignore it because it represents the current record.
query = queryset.where(lookup_field == field.value)
if pk_field and pk_value:
query = query.where(~(pk_field == pk_value))
if query.count():
raise ValidationError('unique')
return unique_validator
def coerce_single_instance(lookup_field, value):
"""
Convert from whatever value is given to a scalar value for lookup_field.
If value is a dict, then lookup_field.name is used to get the value from the dict. Example:
lookup_field.name = 'id'
value = {'id': 123, 'name': 'tim'}
returns = 123
If value is a model, then lookup_field.name is extracted from the model. Example:
lookup_field.name = 'id'
value = <User id=123 name='tim'>
returns = 123
Otherwise the value is returned as-is.
:param lookup_field: Peewee model field used for getting name from value.
:param value: Some kind of value (usually a dict, Model instance, or scalar).
"""
if isinstance(value, dict):
return value.get(lookup_field.name)
if isinstance(value, peewee.Model):
return getattr(value, lookup_field.name)
return value
def isiterable_notstring(value):
"""
Returns True if the value is iterable but not a string. Otherwise returns False.
:param value: Value to check.
"""
if isinstance(value, str):
return False
return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value)
class Field:
"""
Base class from which all other fields should be derived.
:param default: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, default=None, validators=None):
self.default = default
self.value = None
self.validators = validators or []
if required:
self.validators.append(validate_required())
def coerce(self, value):
"""
Coerce the given value into some type. By default a no-op.
Used by sub-classes to enforce specific types.
If there is a problem with the coersion, raise ValidationError.
:param value: Value to coerce.
:raises: ValidationError
:return: The updated value.
:rtype: any
"""
return value
def get_value(self, name, data):
"""
Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
:return: The value of this field.
:rtype: any
"""
if name in data:
return data.get(name)
if self.default:
if callable(self.default):
return self.default()
return self.default
return None
def validate(self, name, data):
"""
Check to make sure ths data for this field is valid.
Usually runs all validators in self.validators list.
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
self.value = self.get_value(name, data)
if self.value is not None:
self.value = self.coerce(self.value)
for method in self.validators:
method(self, data)
class StringField(Field):
"""
A field that will try to coerce value to a string.
:param required: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
:param max_length: Maximum length that should be enfocred.
:param min_length: Minimum length that should be enfocred.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, max_length=None, min_length=None, default=None, validators=None):
validators = validators or []
if max_length or min_length:
validators.append(validate_length(high=max_length, low=min_length))
super().__init__(required=required, default=default, validators=validators)
def coerce(self, value):
return str(value)
class FloatField(Field):
"""
A field that will try to coerce value to a float.
:param required: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
:param low: Lowest value that should be enfocred.
:param high: Highest value that should be enfocred.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, low=None, high=None, default=None, validators=None):
validators = validators or []
if low or high:
validators.append(validate_range(low=low, high=high))
super().__init__(required=required, default=default, validators=validators)
def coerce(self, value):
try:
return float(value) if value else None
except (TypeError, ValueError):
raise ValidationError('coerce_float')
class IntegerField(Field):
"""
A field that will try to coerce value to an integer.
:param required: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
:param low: Lowest value that should be enfocred.
:param high: Highest value that should be enfocred.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, low=None, high=None, default=None, validators=None):
validators = validators or []
if low or high:
validators.append(validate_range(low=low, high=high))
super().__init__(required=required, default=default, validators=validators)
def coerce(self, value):
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
raise ValidationError('coerce_int')
class DecimalField(Field):
"""
A field that will try to coerce value to a decimal.
:param required: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
:param low: Lowest value that should be enfocred.
:param high: Highest value that should be enfocred.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, low=None, high=None, default=None, validators=None):
validators = validators or []
if low or high:
validators.append(validate_range(low=low, high=high))
super().__init__(required=required, default=default, validators=validators)
def coerce(self, value):
try:
return Decimal(value) if value else None
except (TypeError, ValueError, InvalidOperation):
raise ValidationError('coerce_decimal')
class DateField(Field):
"""
A field that will try to coerce value to a date.
Can accept a date object, string, or anything else that can be converted
by `dateutil.parser.parse`.
:param required: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
:param low: Lowest value that should be enfocred.
:param high: Highest value that should be enfocred.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, low=None, high=None, default=None, validators=None):
validators = validators or []
if low or high:
validators.append(validate_range(low=low, high=high))
super().__init__(required=required, default=default, validators=validators)
def coerce(self, value):
if not value or isinstance(value, datetime.date):
return value
try:
return dateutil_parse(value).date()
except (TypeError, ValueError):
raise ValidationError('coerce_date')
class TimeField(Field):
"""
A field that will try to coerce value to a time.
Can accept a time object, string, or anything else that can be converted
by `dateutil.parser.parse`.
:param required: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
:param low: Lowest value that should be enfocred.
:param high: Highest value that should be enfocred.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, low=None, high=None, default=None, validators=None):
validators = validators or []
if low or high:
validators.append(validate_range(low=low, high=high))
super().__init__(required=required, default=default, validators=validators)
def coerce(self, value):
if not value or isinstance(value, datetime.time):
return value
try:
return dateutil_parse(value).time()
except (TypeError, ValueError):
raise ValidationError('coerce_time')
class DateTimeField(Field):
"""
A field that will try to coerce value to a datetime.
Can accept a datetime object, string, or anything else that can be converted
by `dateutil.parser.parse`.
:param required: Is this field required?
:param default: Default value to be used if no incoming value is provided.
:param validators: List of validator functions to run.
:param low: Lowest value that should be enfocred.
:param high: Highest value that should be enfocred.
"""
__slots__ = ('value', 'required', 'default', 'validators')
def __init__(self, required=False, low=None, high=None, default=None, validators=None):
validators = validators or []
if low or high:
validators.append(validate_range(low=low, high=high))
super().__init__(required=required, default=default, validators=validators)
def coerce(self, value):
if not value or isinstance(value, datetime.datetime):
return value
try:
return dateutil_parse(value)
except (TypeError, ValueError):
raise ValidationError('coerce_datetime')
class BooleanField(Field):
"""
A field that will try to coerce value to a boolean.
By default the values is converted to string first, then compared to these values:
values which are considered False: ('0', '{}', 'none', 'false')
And everything else is True.
"""
__slots__ = ('value', 'required', 'default', 'validators')
false_values = ('0', '{}', '[]', 'none', 'false')
def coerce(self, value):
return not str(value).lower() in self.false_values
class ModelChoiceField(Field):
"""
A field that allows for a single value based on a model query and lookup field.
:param query: Query to use for lookup.
:param lookup_field: Field that will be queried for the value.
"""
__slots__ = ('query', 'lookup_field', 'value', 'required', 'default', 'validators')
def __init__(self, query, lookup_field, required=False, **kwargs):
self.query = query
self.lookup_field = lookup_field
super().__init__(required=required, **kwargs)
def coerce(self, value):
"""Convert from whatever is given to a scalar value for lookup_field."""
return coerce_single_instance(self.lookup_field, value)
def validate(self, name, data):
"""
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
super().validate(name, data)
if self.value is not None:
try:
self.value = self.query.get(self.lookup_field == self.value)
except (AttributeError, ValueError, peewee.DoesNotExist):
raise ValidationError('related', field=self.lookup_field.name, values=self.value)
class ManyModelChoiceField(Field):
"""
A field that allows for multiple values based on a model query and lookup field.
:param query: Query to use for lookup.
:param lookup_field: Field that will be queried for the value.
"""
__slots__ = ('query', 'lookup_field', 'value', 'required', 'default', 'validators')
def __init__(self, query, lookup_field, required=False, **kwargs):
self.query = query
self.lookup_field = lookup_field
super().__init__(required=required, **kwargs)
def coerce(self, value):
"""Convert from whatever is given to a list of scalars for the lookup_field."""
if isinstance(value, dict):
value = [value]
if not isiterable_notstring(value):
value = [value]
return [coerce_single_instance(self.lookup_field, v) for v in value]
def validate(self, name, data):
"""
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
super().validate(name, data)
if self.value is not None:
try:
# self.query could be a query like "User.select()" or a model like "User"
# so ".select().where()" handles both cases.
self.value = [self.query.select().where(self.lookup_field == v).get() for v in self.value if v]
except (AttributeError, ValueError, peewee.DoesNotExist):
raise ValidationError('related', field=self.lookup_field.name, values=self.value)
class ValidatorOptions:
def __init__(self, obj):
self.fields = {}
self.messages = {}
self.only = []
self.exclude = []
class Validator:
"""
A validator class. Can have many fields attached to it to perform validation on data.
"""
class Meta:
"""
A meta class to specify options for the validator. Uses the following fields:
``messages = {}``
``only = []``
``exclues = []``
"""
pass
__slots__ = ('data', 'errors', '_meta')
def __init__(self):
self.errors = {}
self.data = {}
self._meta = ValidatorOptions(self)
self._meta.__dict__.update(self.Meta.__dict__)
self.initialize_fields()
def add_error(self, name, error):
message = self._meta.messages.get('{}.{}'.format(name, error.key))
if not message:
message = self._meta.messages.get(error.key)
if not message:
message = DEFAULT_MESSAGES.get(error.key, 'Validation failed.')
self.errors[name] = message.format(**error.kwargs)
def initialize_fields(self):
"""
The dict self.base_fields is a model instance at this point.
Turn it into an instance attribute on this meta class.
Also intitialize any other special fields if needed in sub-classes.
:return: None
"""
for field in dir(self):
obj = getattr(self, field)
if isinstance(obj, Field):
self._meta.fields[field] = obj
def validate(self, data=None, only=None, exclude=None):
"""
Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
This is usually the method you want to call after creating the validator instance.
:param data: Dictionary of data to validate.
:param only: List or tuple of fields to validate.
:param exclude: List or tuple of fields to exclude from validation.
:return: True if validation was successful. Otherwise False.
"""
only = only or []
exclude = exclude or []
data = data or {}
self.errors = {}
self.data = {}
# Validate individual fields.
for name, field in self._meta.fields.items():
if name in exclude or (only and name not in only):
continue
try:
field.validate(name, data)
except ValidationError as err:
self.add_error(name, err)
continue
self.data[name] = field.value
# Clean individual fields.
if not self.errors:
self.clean_fields(self.data)
# Then finally clean the whole data dict.
if not self.errors:
try:
self.data = self.clean(self.data)
except ValidationError as err:
self.add_error('__base__', err)
return (not self.errors)
def clean_fields(self, data):
"""
For each field, check to see if there is a clean_<name> method.
If so, run that method and set the returned value on the self.data dict.
This happens after all validations so that each field can act on the
cleaned data of other fields if needed.
:param data: Dictionary of data to clean.
:return: None
"""
for name, value in data.items():
try:
method = getattr(self, 'clean_{}'.format(name), None)
if method:
self.data[name] = method(value)
except ValidationError as err:
self.add_error(name, err)
continue
def clean(self, data):
"""
Clean the data dictionary and return the cleaned values.
:param data: Dictionary of data for all fields.
:return: Dictionary of "clean" values.
:rtype: dict
"""
return data
class ModelValidator(Validator):
"""
A validator class based on a Peewee model instance.
Fields are automatically added based on the model instance, but can be customized.
:param instance: Peewee model instance to use for data lookups and field generation.
"""
__slots__ = ('data', 'errors', '_meta', 'instance', 'pk_field', 'pk_value')
FIELD_MAP = {
'smallint': IntegerField,
'bigint': IntegerField,
'bool': BooleanField,
'date': DateField,
'datetime': DateTimeField,
'decimal': DecimalField,
'double': FloatField,
'float': FloatField,
'int': IntegerField,
'time': TimeField,
}
def __init__(self, instance):
if not isinstance(instance, peewee.Model):
message = 'First argument to {} must be an instance of peewee.Model.'
raise AttributeError(message.format(type(self).__name__))
self.instance = instance
self.pk_field = self.instance._meta.primary_key
if PEEWEE3:
self.pk_value = self.instance.get_id()
else:
self.pk_value = self.instance._get_pk_value()
super().__init__()
def initialize_fields(self):
"""
Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None
"""
# # Pull all the "normal" fields off the model instance meta.
for name, field in self.instance._meta.fields.items():
if getattr(field, 'primary_key', False):
continue
self._meta.fields[name] = self.convert_field(name, field)
# Many-to-many fields are not stored in the meta fields dict.
# Pull them directly off the class.
for name in dir(type(self.instance)):
field = getattr(type(self.instance), name, None)
if isinstance(field, ManyToManyField):
self._meta.fields[name] = self.convert_field(name, field)
super().initialize_fields()
def convert_field(self, name, field):
"""
Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field.
"""
if PEEWEE3:
field_type = field.field_type.lower()
else:
field_type = field.db_field
pwv_field = ModelValidator.FIELD_MAP.get(field_type, StringField)
validators = []
required = not bool(getattr(field, 'null', True))
choices = getattr(field, 'choices', ())
default = getattr(field, 'default', None)
max_length = getattr(field, 'max_length', None)
unique = getattr(field, 'unique', False)
if required:
validators.append(validate_required())
if choices:
validators.append(validate_one_of([c[0] for c in choices]))
if max_length:
validators.append(validate_length(high=max_length))
if unique:
validators.append(validate_model_unique(field, self.instance.select(), self.pk_field, self.pk_value))
if isinstance(field, peewee.ForeignKeyField):
if PEEWEE3:
rel_field = field.rel_field
else:
rel_field = field.to_field
return ModelChoiceField(field.rel_model, rel_field, default=default, validators=validators)
if isinstance(field, ManyToManyField):
return ManyModelChoiceField(
field.rel_model, field.rel_model._meta.primary_key,
default=default, validators=validators)
return pwv_field(default=default, validators=validators)
def validate(self, data=None, only=None, exclude=None):
"""
Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
If data for a field is not provided in ``data`` then this validator will check against the
provided model instance.
This is usually the method you want to call after creating the validator instance.
:param data: Dictionary of data to validate.
:param only: List or tuple of fields to validate.
:param exclude: List or tuple of fields to exclude from validation.
:return: True if validation is successful, otherwise False.
"""
data = data or {}
only = only or self._meta.only
exclude = exclude or self._meta.exclude
for name, field in self.instance._meta.fields.items():
if name in exclude or (only and name not in only):
continue
try:
data.setdefault(name, getattr(self.instance, name, None))
except (peewee.DoesNotExist):
if PEEWEE3:
instance_data = self.instance.__data__
else:
instance_data = self.instance._data
data.setdefault(name, instance_data.get(name, None))
# This will set self.data which we should use from now on.
super().validate(data=data, only=only, exclude=exclude)
if not self.errors:
self.perform_index_validation(self.data)
return (not self.errors)
def perform_index_validation(self, data):
"""
Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None
"""
# Build a list of dict containing query values for each unique index.
index_data = []
for columns, unique in self.instance._meta.indexes:
if not unique:
continue
index_data.append({col: data.get(col, None) for col in columns})
# Then query for each unique index to see if the value is unique.
for index in index_data:
query = self.instance.filter(**index)
# If we have a primary key, need to exclude the current record from the check.
if self.pk_field and self.pk_value:
query = query.where(~(self.pk_field == self.pk_value))
if query.count():
err = ValidationError('index', fields=str.join(', ', index.keys()))
for col in index.keys():
self.add_error(col, err)
def save(self, force_insert=False):
"""