| 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
 | from django.core import validators
from django.core.exceptions import ValidationError
from django.utils.encoding import is_protected_type
from rest_framework.utils import html
import inspect
class empty:
    """
    This class is used to represent no data being provided for a given input
    or output value.
    It is required because `None` may be a valid input or output value.
    """
    pass
def is_simple_callable(obj):
    """
    True if the object is a callable that takes no arguments.
    """
    function = inspect.isfunction(obj)
    method = inspect.ismethod(obj)
    if not (function or method):
        return False
    args, _, _, defaults = inspect.getargspec(obj)
    len_args = len(args) if function else len(args) - 1
    len_defaults = len(defaults) if defaults else 0
    return len_args <= len_defaults
def get_attribute(instance, attrs):
    """
    Similar to Python's built in `getattr(instance, attr)`,
    but takes a list of nested attributes, instead of a single attribute.
    Also accepts either attribute lookup on objects or dictionary lookups.
    """
    for attr in attrs:
        try:
            instance = getattr(instance, attr)
        except AttributeError:
            return instance[attr]
    return instance
def set_value(dictionary, keys, value):
    """
    Similar to Python's built in `dictionary[key] = value`,
    but takes a list of nested keys instead of a single key.
    set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
    set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
    set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}}
    """
    if not keys:
        dictionary.update(value)
        return
    for key in keys[:-1]:
        if key not in dictionary:
            dictionary[key] = {}
        dictionary = dictionary[key]
    dictionary[keys[-1]] = value
class SkipField(Exception):
    pass
class Field(object):
    _creation_counter = 0
    MESSAGES = {
        'required': 'This field is required.'
    }
    _NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`'
    _NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`'
    _NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`'
    _NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`'
    _MISSING_ERROR_MESSAGE = (
        'ValidationError raised by `{class_name}`, but error key `{key}` does '
        'not exist in the `MESSAGES` dictionary.'
    )
    default_validators = []
    def __init__(self, read_only=False, write_only=False,
                 required=None, default=empty, initial=None, source=None,
                 label=None, style=None, error_messages=None, validators=[]):
        self._creation_counter = Field._creation_counter
        Field._creation_counter += 1
        # If `required` is unset, then use `True` unless a default is provided.
        if required is None:
            required = default is empty and not read_only
        # Some combinations of keyword arguments do not make sense.
        assert not (read_only and write_only), self._NOT_READ_ONLY_WRITE_ONLY
        assert not (read_only and required), self._NOT_READ_ONLY_REQUIRED
        assert not (read_only and default is not empty), self._NOT_READ_ONLY_DEFAULT
        assert not (required and default is not empty), self._NOT_REQUIRED_DEFAULT
        self.read_only = read_only
        self.write_only = write_only
        self.required = required
        self.default = default
        self.source = source
        self.initial = initial
        self.label = label
        self.style = {} if style is None else style
        self.validators = self.default_validators + validators
    def bind(self, field_name, parent, root):
        """
        Setup the context for the field instance.
        """
        self.field_name = field_name
        self.parent = parent
        self.root = root
        self.context = parent.context
        # `self.label` should deafult to being based on the field name.
        if self.label is None:
            self.label = self.field_name.replace('_', ' ').capitalize()
        # self.source should default to being the same as the field name.
        if self.source is None:
            self.source = field_name
        # self.source_attrs is a list of attributes that need to be looked up
        # when serializing the instance, or populating the validated data.
        if self.source == '*':
            self.source_attrs = []
        else:
            self.source_attrs = self.source.split('.')
    def get_initial(self):
        """
        Return a value to use when the field is being returned as a primative
        value, without any object instance.
        """
        return self.initial
    def get_value(self, dictionary):
        """
        Given the *incoming* primative data, return the value for this field
        that should be validated and transformed to a native value.
        """
        return dictionary.get(self.field_name, empty)
    def get_attribute(self, instance):
        """
        Given the *outgoing* object instance, return the value for this field
        that should be returned as a primative value.
        """
        return get_attribute(instance, self.source_attrs)
    def get_default(self):
        """
        Return the default value to use when validating data if no input
        is provided for this field.
        If a default has not been set for this field then this will simply
        return `empty`, indicating that no value should be set in the
        validated data for this field.
        """
        if self.default is empty:
            raise SkipField()
        return self.default
    def validate(self, data=empty):
        """
        Validate a simple representation and return the internal value.
        The provided data may be `empty` if no representation was included.
        May return `empty` if the field should not be included in the
        validated data.
        """
        if data is empty:
            if self.required:
                self.fail('required')
            return self.get_default()
        self.run_validators(data)
        return self.to_native(data)
    def run_validators(self, value):
        if value in validators.EMPTY_VALUES:
            return
        errors = []
        for validator in self.validators:
            try:
                validator(value)
            except ValidationError as exc:
                errors.extend(exc.messages)
        if errors:
            raise ValidationError(errors)
    def to_native(self, data):
        """
        Transform the *incoming* primative data into a native value.
        """
        return data
    def to_primative(self, value):
        """
        Transform the *outgoing* native value into primative data.
        """
        return value
    def fail(self, key, **kwargs):
        """
        A helper method that simply raises a validation error.
        """
        try:
            raise ValidationError(self.MESSAGES[key].format(**kwargs))
        except KeyError:
            class_name = self.__class__.__name__
            msg = self._MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
            raise AssertionError(msg)
    def __new__(cls, *args, **kwargs):
        instance = super(Field, cls).__new__(cls)
        instance._args = args
        instance._kwargs = kwargs
        return instance
    def __repr__(self):
        arg_string = ', '.join([repr(val) for val in self._args])
        kwarg_string = ', '.join([
            '%s=%s' % (key, repr(val)) for key, val in self._kwargs.items()
        ])
        if arg_string and kwarg_string:
            arg_string += ', '
        class_name = self.__class__.__name__
        return "%s(%s%s)" % (class_name, arg_string, kwarg_string)
class BooleanField(Field):
    MESSAGES = {
        'required': 'This field is required.',
        'invalid_value': '`{input}` is not a valid boolean.'
    }
    TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True}
    FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False}
    def get_value(self, dictionary):
        if html.is_html_input(dictionary):
            # HTML forms do not send a `False` value on an empty checkbox,
            # so we override the default empty value to be False.
            return dictionary.get(self.field_name, False)
        return dictionary.get(self.field_name, empty)
    def to_native(self, data):
        if data in self.TRUE_VALUES:
            return True
        elif data in self.FALSE_VALUES:
            return False
        self.fail('invalid_value', input=data)
class CharField(Field):
    MESSAGES = {
        'required': 'This field is required.',
        'blank': 'This field may not be blank.'
    }
    def __init__(self, **kwargs):
        self.allow_blank = kwargs.pop('allow_blank', False)
        self.max_length = kwargs.pop('max_length', None)
        self.min_length = kwargs.pop('min_length', None)
        super(CharField, self).__init__(**kwargs)
    def to_native(self, data):
        if data == '' and not self.allow_blank:
            self.fail('blank')
        return str(data)
class ChoiceField(Field):
    MESSAGES = {
        'required': 'This field is required.',
        'invalid_choice': '`{input}` is not a valid choice.'
    }
    coerce_to_type = str
    def __init__(self, **kwargs):
        choices = kwargs.pop('choices')
        assert choices, '`choices` argument is required and may not be empty'
        # Allow either single or paired choices style:
        # choices = [1, 2, 3]
        # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]
        pairs = [
            isinstance(item, (list, tuple)) and len(item) == 2
            for item in choices
        ]
        if all(pairs):
            self.choices = {key: val for key, val in choices}
        else:
            self.choices = {item: item for item in choices}
        # Map the string representation of choices to the underlying value.
        # Allows us to deal with eg. integer choices while supporting either
        # integer or string input, but still get the correct datatype out.
        self.choice_strings_to_values = {
            str(key): key for key in self.choices.keys()
        }
        super(ChoiceField, self).__init__(**kwargs)
    def to_native(self, data):
        try:
            return self.choice_strings_to_values[str(data)]
        except KeyError:
            self.fail('invalid_choice', input=data)
class MultipleChoiceField(ChoiceField):
    MESSAGES = {
        'required': 'This field is required.',
        'invalid_choice': '`{input}` is not a valid choice.',
        'not_a_list': 'Expected a list of items but got type `{input_type}`'
    }
    def to_native(self, data):
        if not hasattr(data, '__iter__'):
            self.fail('not_a_list', input_type=type(data).__name__)
        return set([
            super(MultipleChoiceField, self).to_native(item)
            for item in data
        ])
class IntegerField(Field):
    MESSAGES = {
        'required': 'This field is required.',
        'invalid_integer': 'A valid integer is required.'
    }
    def __init__(self, **kwargs):
        max_value = kwargs.pop('max_value', None)
        min_value = kwargs.pop('min_value', None)
        super(IntegerField, self).__init__(**kwargs)
        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value))
    def to_native(self, data):
        try:
            data = int(str(data))
        except (ValueError, TypeError):
            self.fail('invalid_integer')
        return data
    def to_primative(self, value):
        if value is None:
            return None
        return int(value)
class EmailField(CharField):
    pass  # TODO
class URLField(CharField):
    pass  # TODO
class RegexField(CharField):
    def __init__(self, **kwargs):
        self.regex = kwargs.pop('regex')
        super(CharField, self).__init__(**kwargs)
class DateField(CharField):
    def __init__(self, **kwargs):
        self.input_formats = kwargs.pop('input_formats', None)
        super(DateField, self).__init__(**kwargs)
class TimeField(CharField):
    def __init__(self, **kwargs):
        self.input_formats = kwargs.pop('input_formats', None)
        super(TimeField, self).__init__(**kwargs)
class DateTimeField(CharField):
    def __init__(self, **kwargs):
        self.input_formats = kwargs.pop('input_formats', None)
        super(DateTimeField, self).__init__(**kwargs)
class FileField(Field):
    pass  # TODO
class ReadOnlyField(Field):
    def to_primative(self, value):
        if is_simple_callable(value):
            return value()
        return value
class MethodField(Field):
    def __init__(self, **kwargs):
        kwargs['source'] = '*'
        kwargs['read_only'] = True
        super(MethodField, self).__init__(**kwargs)
    def to_primative(self, value):
        attr = 'get_{field_name}'.format(field_name=self.field_name)
        method = getattr(self.parent, attr)
        return method(value)
class ModelField(Field):
    """
    A generic field that can be used against an arbitrary model field.
    """
    def __init__(self, *args, **kwargs):
        try:
            self.model_field = kwargs.pop('model_field')
        except KeyError:
            raise ValueError("ModelField requires 'model_field' kwarg")
        self.min_length = kwargs.pop('min_length',
                                     getattr(self.model_field, 'min_length', None))
        self.max_length = kwargs.pop('max_length',
                                     getattr(self.model_field, 'max_length', None))
        self.min_value = kwargs.pop('min_value',
                                    getattr(self.model_field, 'min_value', None))
        self.max_value = kwargs.pop('max_value',
                                    getattr(self.model_field, 'max_value', None))
        super(ModelField, self).__init__(*args, **kwargs)
        if self.min_length is not None:
            self.validators.append(validators.MinLengthValidator(self.min_length))
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length))
        if self.min_value is not None:
            self.validators.append(validators.MinValueValidator(self.min_value))
        if self.max_value is not None:
            self.validators.append(validators.MaxValueValidator(self.max_value))
    def get_attribute(self, instance):
        return get_attribute(instance, self.source_attrs[:-1])
    def to_native(self, data):
        rel = getattr(self.model_field, 'rel', None)
        if rel is not None:
            return rel.to._meta.get_field(rel.field_name).to_python(data)
        return self.model_field.to_python(data)
    def to_primative(self, obj):
        value = self.model_field._get_val_from_obj(obj)
        if is_protected_type(value):
            return value
        return self.model_field.value_to_string(obj)
 |