-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfields.py
1388 lines (1054 loc) · 42.5 KB
/
fields.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
"""
Fields for serializers.
"""
import re
try:
from typing import Mapping
except ImportError:
from collections import Mapping
import datetime
import json
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
import six
from rest_framework.exceptions import SkipError
from rest_framework.serializers.exceptions import ValidationError
from rest_framework.utils import html
from rest_framework.serializers.validators import (
RequiredValidator, MaxLengthValidator, MinLengthValidator, MaxValueValidator, MinValueValidator
)
MISSING_ERROR_MESSAGE = (
'Raise `ValidationError` exception for `{class_name}`, '
'not found key `{key}` in dict `error_messages`.'
) # Default error message, for situation not error key in error_messages dict.
# Default formats for parse, transformed datetime.
DEFAULT_DATE_FORMAT = '%Y-%m-%d'
DEFAULT_TIME_FORMAT = '%H:%M:%S'
DEFAULT_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DEFAULT_INPUT_DATE_FORMAT = '%Y-%m-%d'
DEFAULT_INPUT_TIME_FORMAT = '%H:%M:%S'
DEFAULT_INPUT_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
def get_attribute(obj, attr_name):
"""
Return object attribute. Can work with dictionaries.
:param object obj: Object for search attribute.
:param str attr_name: Attribute name.
:return: Found attribute or exception.
:rtype: object
:raise AttributeError: If attribute not found.
"""
# Search attribute.
if isinstance(obj, Mapping):
attr = obj[attr_name]
else:
attr = getattr(obj, attr_name)
# Return.
return attr
class Field(object):
"""
Base field.
"""
default_error_messages = {
'required': 'This field is required.',
'null': 'This field cannot be null.'
}
default_validators = [] # Default validators for field.
def __init__(self, required=True, default=None, label=None, validators=None,
error_messages=None, source=None):
"""
Base field.
:param bool required: This is required field?
:param object default: Default value. If set, then the field is optional.
:param str label: Field name.
:param list validators: Validators for field.
:param dict error_messages: Dictionary with custom error description.
:param str source: Source field_name, if field_name object other in serializer.
"""
self.label = label
self.default = default
self.source = source
self.required = bool(required) if self.default is None else False
# Added validator for check on required field.
self._src_validators = validators
self._validators = ([RequiredValidator()] if self.required else []) + (validators or [])[:]
# Make errors dict.
messages = {}
self._src_messages = messages
for cls in reversed(self.__class__.__mro__):
messages.update(getattr(cls, 'default_error_messages', {}))
messages.update(error_messages or {})
self.error_messages = messages
def __deepcopy__(self, memo={}):
return self.__class__(
required=self.required, default=self.default, label=self.label,
validators=self._src_validators, error_messages=self._src_messages
)
def bind(self, field_name, parent):
"""
Initialization field name and parent instance .
Called when a field is added to an instance of the parent..
:param str field_name: Field name.
:param Serializer parent: Serializer class on which the field is located.
"""
self.field_name = field_name
self.parent = parent
# We put the label ourselves if it's not there.
if self.label is None:
self.label = field_name.replace('_', ' ').capitalize()
@property
def validators(self):
"""
:return: List validators for this field.
:rtype: list
"""
if not hasattr(self, '_validators'):
self._validators = self.get_validators()
return self._validators
@validators.setter
def validators(self, validators):
"""
We give access to change the list of validators.
:param list validators: New list validators for this field.
"""
self._validators = validators
def get_validators(self):
"""
Return default validators.
Used to generate a list of validators if they are not explicitly defined.
:return: List default validators.
:rtype: list
"""
return self.default_validators[:]
def fail(self, key, **kwargs):
"""
We throw a normal error if something went wrong during data processing.
:param str key: Error type. Key for dict `self.default_error_messages`.
:param kwargs: Data to format error message.
:raise AssertionError: If you have not found the key in the `self.error_messages`.
:raise ValidationError: If you find the key in the `self.error_messages`.
"""
# Trying to get an error message.
try:
msg = self.error_messages[key]
except KeyError:
# If we could not talk about it, I use a general message.
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
raise AssertionError(msg)
# Format the message and throw an error.
message_string = msg.format(**kwargs)
raise ValidationError(detail=message_string, status=key)
def to_internal_value(self, data):
"""
Data transformation to python object.
:param object data: Data for transformation.
:return: Transformed data.
:rtype: object
"""
raise NotImplementedError('`to_internal_value()` must be implemented.')
def to_representation(self, value):
"""
Transformation an object to a valid JSON object.
:param object value: The object to transformation.
:return: Transformed data.
:rtype: object
"""
raise NotImplementedError('`to_representation()` must be implemented.')
def get_default(self):
"""
Return default value.
If necessary, initially call the callable object to get the default value..
:return: Default value.
:rtype: object
"""
if callable(self.default):
return self.default()
return self.default
def _get_field_name(self):
"""
Get field name for search attribute on object.
:return: Field name for search attribute.
:rtype: str
"""
return self.source or self.field_name
def _get_attribute(self, instance):
"""
Searches for and returns an attribute on an object..
:return: Object attribute value.
:rtype: object
:raise SkipError: If you could not find the field and the field is required.
:raise Exception: If an error occurred during the search.
"""
return get_attribute(instance, self._get_field_name())
def get_attribute(self, instance):
"""
Searches for and returns an attribute on an object..
:return: Object attribute value.
:rtype: object
:raise SkipError: If you could not find the field and the field is required.
:raise Exception: If an error occurred during the search.
"""
try:
# Trying to get an attribute.
return self._get_attribute(instance)
except (KeyError, AttributeError) as e:
# If there is a default value, then it.
if self.default is not None:
return self.get_default()
# If there is no default and the field is required, we swear.
if self.required:
raise SkipError(self.error_messages['required'])
# Otherwise, we report this incident to the developer..
msg = (
'Got {exc_type} when attempting to get a value for field '
'`{field}` on serializer `{serializer}`.\nThe serializer '
'field might by named incorrectly and not match '
'any attribute or key on the `{instance}` object.\n'
'Original exception text was: {exc}.'.format(
exc_type=type(e).__name__,
field=self.field_name,
serializer=self.parent.__name__,
instance=instance.__class__.__name__,
exc=e
)
)
raise type(e)(msg)
def validate_empty_values(self, data):
"""
Check if the value is empty.
:param object data: Data for check.
:return: The result of check, and current data.
If there is a default value and nothing is passed, returns the default.
Tuple: (is None, actual data)
:rtype: tuple
:raise ValidationError: If validation on an empty field did not pass.
"""
# Process.
is_empty, data = data is None, data if data is not None else self.default
# Validating.
if is_empty and not self.required:
return is_empty, data
# If empty and not necessary, then there is nothing to validate and transformed.
if is_empty:
raise ValidationError(detail=self.error_messages['required'])
# Return.
return is_empty, data
def run_validation(self, data):
"""
Starts data transformed, then validation..
:param object data: Data worth checking, transformed, etc..
:return: Transformed Validated Data.
:rtype: object
:raise ValidationError: If the field failed validation.
"""
# First, we validate to be bound.
is_empty, data = self.validate_empty_values(data)
# If empty data and field not required.
if is_empty and not self.required:
return data
# Process raw data.
value = self.to_internal_value(data)
# Run validators.
self.run_validators(value)
return value
def run_validators(self, value):
"""
Validates all field validators.
:param object value: Data for validation.
:raise ValidationError: If validation fails.
"""
errors = []
for validator in self.validators or []:
try:
# Run each validator.
validator(value)
except ValidationError as e:
errors.append(e.detail)
# Check on errors.
if errors:
raise ValidationError(detail=errors)
class CharField(Field):
"""
Field for text.
"""
default_error_messages = {
'invalid': 'Not a valid string.',
'blank': 'This field may not be blank.',
'min_length': 'Ensure this field has at least {min_length} characters.',
'max_length': 'Ensure this field has no more than {max_length} characters.'
}
def __init__(self, min_length=None, max_length=None, trim_whitespace=False, allow_blank=True, *args, **kwargs):
"""
Field for text.
:param int min_length: Minimum length string.
:param int max_length: Maximum length string.
:param bool trim_whitespace: Whether to trim spaces at the beginning and end of a line?
:param bool allow_blank: Allow empty string?
"""
super().__init__(*args, **kwargs)
self.max_length = max_length if max_length is None else int(max_length)
self.min_length = min_length if min_length is None else int(min_length)
self.trim_whitespace = trim_whitespace
self.allow_blank = allow_blank
# Added validators.
if self.max_length is not None:
message = self.error_messages['max_length'].format(max_length=self.max_length)
self.validators.append(MaxLengthValidator(max_length, message=message))
if self.min_length is not None:
message = self.error_messages['min_length'].format(min_length=self.min_length)
self.validators.append(MinLengthValidator(self.min_length, message=message))
def __deepcopy__(self, memo={}):
return self.__class__(
required=self.required, default=self.default, label=self.label,
validators=self._src_validators, error_messages=self._src_messages,
min_length=self.min_length, max_length=self.max_length,
trim_whitespace=self.trim_whitespace, allow_blank=self.allow_blank
)
def run_validation(self, data=None):
"""
We check for an empty string here, so that it does not fall into subclasses in `.to_internal_value ()`.
:param object data: Data for validation.
:return: Transformed Validated Data.
:rtype: str
"""
if data == '' or (self.trim_whitespace and six.text_type(data).strip() == ''):
if not self.allow_blank:
self.fail('blank')
return ''
return super(CharField, self).run_validation(data)
def to_internal_value(self, data):
"""
Data transformation to python object.
:param str data: Data for transformation.
:return: Transformed data.
:rtype: str
:raise ValidationError: If not valid data.
"""
# We skip numbers as strings, but bool as strings seems to be a developer error.
if isinstance(data, bool) or not isinstance(data, six.string_types + six.integer_types + (float,)):
self.fail('invalid')
val = six.text_type(data)
if self.trim_whitespace:
val = val.strip()
return val
def to_representation(self, value):
"""
Transformation an object to a valid JSON object.
:param str value: The object to transformation.
:return: Transformed data.
:rtype: str
"""
return six.text_type(value)
class IntegerField(Field):
"""
Field for integer number.
"""
default_error_messages = {
'invalid': 'A valid integer is required.',
'min_value': 'Ensure this value is greater than or equal to {min_value}.',
'max_value': 'Ensure this value is less than or equal to {max_value}.',
'max_string_length': 'String value too large.'
}
MAX_STRING_LENGTH = 1000 # We limit the maximum length.
re_decimal = re.compile(r'\.0*\s*$') # '1.0' is int, is not int '1.2'
def __init__(self, min_value=None, max_value=None, *args, **kwargs):
"""
Field for integer number.
:param int min_value: Minimum value.
:param int max_value: Maximum value.
"""
super().__init__(*args, **kwargs)
self.min_value = min_value if min_value is None else int(min_value)
self.max_value = max_value if max_value is None else int(max_value)
# Added validators.
if self.min_value is not None:
message = self.error_messages['min_value'].format(min_value=self.min_value)
self.validators.append(MinValueValidator(self.min_value, message=message))
if self.max_value is not None:
message = self.error_messages['max_value'].format(max_value=self.max_value)
self.validators.append(MaxValueValidator(self.max_value, message=message))
def __deepcopy__(self, memo={}):
return self.__class__(
required=self.required, default=self.default, label=self.label,
validators=self._src_validators, error_messages=self._src_messages,
min_value=self.min_value, max_value=self.max_value
)
def to_internal_value(self, data):
"""
Data transformation to python object.
:param Union[str, int, float] data: Data for transformation.
:return: Transformed data.
:rtype: int
:raise ValidationError: Id not valid data.
"""
# We look, do not want us to score a memory?
if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
self.fail('max_string_length')
try:
data = int(self.re_decimal.sub('', str(data)))
except (ValueError, TypeError):
self.fail('invalid')
return data
def to_representation(self, value):
"""
Transformation an object to a valid JSON object.
:param int value: The object to transformation.
:return: Transformed data.
:rtype: int
"""
return int(value)
class FloatField(Field):
"""
Field for floating number.
"""
default_error_messages = {
'invalid': 'A valid integer is required.',
'min_value': 'Ensure this value is greater than or equal to {min_value}.',
'max_value': 'Ensure this value is less than or equal to {max_value}.',
'max_string_length': 'String value too large.'
}
MAX_STRING_LENGTH = 1000 # We limit the maximum length.
def __init__(self, min_value=None, max_value=None, *args, **kwargs):
"""
Field for floating number.
:param float min_value: Minimum value.
:param float max_value: Maximum value.
"""
super().__init__(*args, **kwargs)
self.min_value = min_value if min_value is None else float(min_value)
self.max_value = max_value if max_value is None else float(max_value)
# Added validators.
if self.min_value is not None:
message = self.error_messages['min_value'].format(min_value=self.min_value)
self.validators.append(MinValueValidator(self.min_value, message=message))
if self.max_value is not None:
message = self.error_messages['max_value'].format(max_value=self.max_value)
self.validators.append(MaxValueValidator(self.max_value, message=message))
def __deepcopy__(self, memo={}):
return self.__class__(
required=self.required, default=self.default, label=self.label,
validators=self._src_validators, error_messages=self._src_messages,
min_value=self.min_value, max_value=self.max_value
)
def to_internal_value(self, data):
"""
Data transformation to python object.
:param Union[str, int, float] data: Data for transformation.
:return: Transformed data.
:rtype: float
:raise ValidationError: If not valid data.
"""
# We look, do not want us to score a memory?
if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
self.fail('max_string_length')
try:
return float(data)
except (TypeError, ValueError):
self.fail('invalid')
def to_representation(self, value):
"""
Transformation an object to a valid JSON object.
:param float value: The object to transformation.
:return: Transformed data.
:rtype: float
"""
return float(value)
class BooleanField(Field):
"""
Field for boolean type.
"""
default_error_messages = {
'invalid': '"{input}" must be a valid boolean type.'
}
TRUE_VALUES = {
't', 'T',
'y', 'Y', 'yes', 'YES', 'Yes',
'true', 'True', 'TRUE',
'on', 'On', 'ON',
'1', 1,
True
} # Dict with True options.
FALSE_VALUES = {
'f', 'F', 'n',
'N', 'no', 'NO', 'No',
'false', 'False', 'FALSE',
'off', 'Off', 'OFF',
'0', 0, 0.0,
False
} # Dictionary with False options.
def to_internal_value(self, data):
"""
Data transformation to python object.
:param Union[str, int, float, bool] data: Data for transformation.
:return: Transformed data.
:rtype: bool
:raise ValidationError: If not valid data.
"""
try:
if data in self.TRUE_VALUES:
return True
elif data in self.FALSE_VALUES:
return False
except TypeError: # If the non-hash type came.
pass
self.fail('invalid', input=data)
def to_representation(self, value):
"""
Transformation an object to a valid JSON object.
:param Union[str, int, float, bool] value: The object to transformation.
:return: Transformed data.
:rtype: bool
"""
# First we look for in the match table.
if value in self.TRUE_VALUES:
return True
elif value in self.FALSE_VALUES:
return False
# If not found, try to transform.
return bool(value)
class BooleanNullField(Field):
"""
Field for boolean type.
"""
default_error_messages = {
'invalid': '"{input}" must be a valid boolean type.'
}
TRUE_VALUES = {
't', 'T',
'y', 'Y', 'yes', 'YES', 'Yes',
'true', 'True', 'TRUE',
'on', 'On', 'ON',
'1', 1,
True
} # Dict with True options.
FALSE_VALUES = {
'f', 'F', 'n',
'N', 'no', 'NO', 'No',
'false', 'False', 'FALSE',
'off', 'Off', 'OFF',
'0', 0, 0.0,
False
} # Dictionary with False options.
NULL_VALUES = {'n', 'N', 'null', 'Null', 'NULL', '', None} # Dictionary with NULL options.
def to_internal_value(self, data):
"""
Data transformation to python object.
:param Union[str, int, float, bool] data: Data for transformation.
:return: Transformed data.
:rtype: bool
:raise ValidationError: If not valid data.
"""
try:
if data in self.TRUE_VALUES:
return True
elif data in self.FALSE_VALUES:
return False
elif data in self.NULL_VALUES:
return None
except TypeError: # If the non-hash type came.
pass
self.fail('invalid', input=data)
def to_representation(self, value):
"""
Transformation an object to a valid JSON object.
:param Union[str, int, float, bool] value: The object to transformation.
:return: Transformed data.
:rtype: bool
"""
# First we look for in the match table.
if value in self.NULL_VALUES:
return None
if value in self.TRUE_VALUES:
return True
elif value in self.FALSE_VALUES:
return False
# If not found, try to transform.
return bool(value)
class _UnvalidatedField(Field):
"""
Field, which is forwarding data as is.
"""
def __init__(self, *args, **kwargs):
"""
Field, which is forwarding data as is
"""
super(_UnvalidatedField, self).__init__(*args, **kwargs)
self.allow_blank = True
def to_internal_value(self, data):
"""
Data transformation to python object.
:param object data: Data for transformation.
:return: Source value.
:rtype: object
:raise ValidationError: If not valid data.
"""
return data
def to_representation(self, value):
"""
Transformation an object to a valid JSON object.
:param object value: The object to transformation.
:return: Source value.
:rtype: object
"""
return value
class ListField(Field):
"""
Field for list objects.
"""
default_error_messages = {
'not_a_list': 'Expected a list of items but got type "{input_type}".',
'empty': 'This list may not be empty.',
'min_length': 'Ensure this field has at least {min_length} elements.',
'max_length': 'Ensure this field has no more than {max_length} elements.'
}
child = _UnvalidatedField()
def __init__(self, child=None, min_length=None, max_length=None, allow_empty=False, *args, **kwargs):
"""
Field for list objects.
:param rest_framework.serializers.Field child: Field describing the type of array elements.
:param int min_length: Minimum length list.
:param int max_length: Maximum length list.
:param bool allow_empty: Allow empty array?
"""
super().__init__(*args, **kwargs)
self.child = child or self.child
self.min_length = min_length if min_length is None else int(min_length)
self.max_length = max_length if max_length is None else int(max_length)
self.allow_empty = bool(allow_empty)
# Check field `child`.
if all((not isinstance(child, Field), not isinstance(self.child, Field))):
raise ValueError('`child=` or `self.child` must be Field.')
self.child.bind(field_name='', parent=self) # Bind child field.
# Added validators.
if self.max_length is not None:
message = self.error_messages['max_length'].format(max_length=self.max_length)
self.validators.append(MaxLengthValidator(max_length, message=message))
if self.min_length is not None:
message = self.error_messages['min_length'].format(min_length=self.min_length)
self.validators.append(MinLengthValidator(self.min_length, message=message))
def __deepcopy__(self, memo={}):
return self.__class__(
required=self.required, default=self.default, label=self.label,
validators=self._src_validators, error_messages=self._src_messages,
child=self.child, min_length=self.min_length, max_length=self.max_length,
allow_empty=self.allow_empty
)
def to_internal_value(self, data):
"""
Data transformation to python list object.
:param iter data: Data for transformation.
:return: Transformed data.
:rtype: list
:raise ValidationError: If not valid data.
"""
if html.is_html_input(data):
data = html.parse_html_list(data)
if any((isinstance(data, type('')), isinstance(data, Mapping), not hasattr(data, '__iter__'))):
self.fail('not_a_list', input_type=type(data).__name__)
if not self.allow_empty and len(data) == 0:
self.fail('empty')
return [self.child.run_validation(item) for item in data]
def to_representation(self, value):
"""
Transformation an object to a valid JSON list object.
:param iter value: The object to transformation.
:return: Transformed data.
:rtype: list
"""
return [self.child.to_representation(item) if item is not None else None for item in (value or [])]
class DateField(Field):
"""
Field for date object.
"""
default_error_messages = {
'invalid': 'Date has wrong format. Use one of these formats instead: {format}.',
'datetime': 'Expected a date but got a datetime.',
}
datetime_parser = datetime.datetime.strptime
format = DEFAULT_DATE_FORMAT
input_format = DEFAULT_INPUT_DATE_FORMAT
def __init__(self, format=None, input_format=None, *args, **kwargs):
"""
Field for date object.
:param str format: Format for parse string date.
:param str input_format: Format for transformed object to string.
"""
if format is not None:
self.format = format
if input_format is not None:
self.input_format = input_format
super().__init__(*args, **kwargs)
def __deepcopy__(self, memo={}):
return self.__class__(
required=self.required, default=self.default, label=self.label,
validators=self._src_validators, error_messages=self._src_messages,
format=getattr(self, 'format'), input_format=getattr(self, 'input_format')
)
def to_internal_value(self, data):
"""
Data transformation to python datetime object.
:param str data: Data for transformation.
:return: Transformed data.
:rtype: datetime.date
:raise ValidationError: If not valid data.
"""
# Get the format.
input_format = getattr(self, 'input_format', DEFAULT_INPUT_DATE_FORMAT)
# Check on the datetime object.
if isinstance(data, datetime.datetime):
self.fail('datetime')
# Check on the date object.
if isinstance(data, datetime.date):
return data
# Parsed data value from string.
try:
parsed = self.datetime_parser(data, input_format)
except (ValueError, TypeError):
pass
else:
# Return value.
return parsed.date()
# Throw exception.
self.fail('invalid', format=data)
def to_representation(self, value):
"""
Transformation an object to a valid JSON date object.
:param datetime.date value: The object to transformation.
:return: Transformed data.
:rtype: str
"""
# Check on the empty.
if not value:
return None
# Check format and value type.
output_format = getattr(self, 'format', DEFAULT_DATE_FORMAT)
if output_format is None or isinstance(value, six.string_types):
return value
# Applying a `DateField` to a datetime value is almost always
# not a sensible thing to do, as it means naively dropping
# any explicit or implicit timezone info.
assert not isinstance(value, datetime.datetime), (
'Expected a `date`, but got a `datetime`. Refusing to coerce, '
'as this may mean losing timezone information. Use a custom '
'read-only field and deal with timezone issues explicitly.'
)
return value.strftime(output_format)
class TimeField(Field):
"""
Field for time object.
"""
default_error_messages = {
'invalid': 'Time has wrong format. Use one of these formats instead: {format}.',
}
datetime_parser = datetime.datetime.strptime
format = DEFAULT_TIME_FORMAT
input_format = DEFAULT_INPUT_TIME_FORMAT
def __init__(self, format=None, input_format=None, *args, **kwargs):
"""
Field for time object.
:param str format: Format for parse string time.
:param str input_format: Format for transformed object to string.
"""
if format is not None:
self.format = format
if input_format is not None:
self.input_format = input_format
super().__init__(*args, **kwargs)
def __deepcopy__(self, memo={}):
return self.__class__(
required=self.required, default=self.default, label=self.label,
validators=self._src_validators, error_messages=self._src_messages,
format=getattr(self, 'format', None), input_format=getattr(self, 'input_format')
)
def to_internal_value(self, data):
"""
Data transformation to python datetime object.