| 1 |
import abc |
| 2 |
import contextlib |
| 3 |
|
| 4 |
from marshmallow import Schema, ValidationError |
| 5 |
from marshmallow.fields import Field |
| 6 |
|
| 7 |
|
| 8 |
class PolyFieldBase(Field, metaclass=abc.ABCMeta): |
| 9 |
def __init__(self, many=False, **metadata): |
| 10 |
super().__init__(**metadata) |
| 11 |
self.many = many |
| 12 |
|
| 13 |
def _deserialize(self, value, attr, parent, partial=None, **kwargs): |
| 14 |
if not self.many: |
| 15 |
value = [value] |
| 16 |
|
| 17 |
results = [] |
| 18 |
for v in value: |
| 19 |
deserializer = None |
| 20 |
try: |
| 21 |
deserializer = self.deserialization_schema_selector(v, parent) |
| 22 |
if isinstance(deserializer, type): |
| 23 |
deserializer = deserializer() |
| 24 |
if not isinstance(deserializer, (Field, Schema)): |
| 25 |
raise Exception('Invalid deserializer type') |
| 26 |
except TypeError as te: |
| 27 |
raise ValidationError(str(te)) from te |
| 28 |
except ValidationError: |
| 29 |
raise |
| 30 |
except Exception as err: |
| 31 |
class_type = None |
| 32 |
if deserializer: |
| 33 |
class_type = str(type(deserializer)) |
| 34 |
|
| 35 |
raise ValidationError( |
| 36 |
"Unable to use schema. Error: {err}\n" |
| 37 |
"Ensure there is a deserialization_schema_selector" |
| 38 |
" and then it returns a field or a schema when the function is passed in " |
| 39 |
"{value_passed}. This is the class I got. " |
| 40 |
"Make sure it is a field or a schema: {class_type}".format( |
| 41 |
err=err, |
| 42 |
value_passed=v, |
| 43 |
class_type=class_type |
| 44 |
) |
| 45 |
) from err |
| 46 |
|
| 47 |
|
| 48 |
if isinstance(deserializer, Field): |
| 49 |
data = deserializer.deserialize(v, attr, parent) |
| 50 |
else: |
| 51 |
deserializer.context.update(getattr(self, 'context', {})) |
| 52 |
data = deserializer.load(v, partial=partial) |
| 53 |
|
| 54 |
results.append(data) |
| 55 |
|
| 56 |
if self.many: |
| 57 |
return results |
| 58 |
else: |
| 59 |
|
| 60 |
return results[0] |
| 61 |
|
| 62 |
def _serialize(self, value, key, obj, **kwargs): |
| 63 |
if value is None: |
| 64 |
return None |
| 65 |
try: |
| 66 |
if self.many: |
| 67 |
res = [] |
| 68 |
for v in value: |
| 69 |
schema = self.serialization_schema_selector(v, obj) |
| 70 |
if isinstance(schema, type): |
| 71 |
schema = schema() |
| 72 |
with contextlib.suppress(AttributeError, TypeError): |
| 73 |
schema.context.update(getattr(self, 'context', {})) |
| 74 |
serialized = (schema.dump(v) |
| 75 |
if hasattr(schema, 'dump') |
| 76 |
else schema._serialize(v, None, None)) |
| 77 |
res.append(serialized) |
| 78 |
return res |
| 79 |
else: |
| 80 |
schema = self.serialization_schema_selector(value, obj) |
| 81 |
if isinstance(schema, type): |
| 82 |
schema = schema() |
| 83 |
with contextlib.suppress(AttributeError, TypeError): |
| 84 |
schema.context.update(getattr(self, 'context', {})) |
| 85 |
return (schema.dump(value) |
| 86 |
if hasattr(schema, 'dump') |
| 87 |
else schema._serialize(value, None, None)) |
| 88 |
except Exception as err: |
| 89 |
raise TypeError( |
| 90 |
'Failed to serialize object. Error: {0}\n' |
| 91 |
' Ensure the serialization_schema_selector exists and ' |
| 92 |
' returns a Schema and that schema' |
| 93 |
' can serialize this value {1}'.format(err, value)) |
| 94 |
|
| 95 |
@abc.abstractmethod |
| 96 |
def serialization_schema_selector(self, value, obj): |
| 97 |
raise NotImplementedError |
| 98 |
|
| 99 |
@abc.abstractmethod |
| 100 |
def deserialization_schema_selector(self, value, obj): |
| 101 |
raise NotImplementedError |
| 102 |
|
| 103 |
|
| 104 |
class PolyField(PolyFieldBase): |
| 105 |
""" |
| 106 |
A field that (de)serializes to one of many types. Passed in functions |
| 107 |
are called to disambiguate what schema to use for the (de)serialization |
| 108 |
Intended to assist in working with fields that can contain any subclass |
| 109 |
of a base type |
| 110 |
""" |
| 111 |
def __init__( |
| 112 |
self, |
| 113 |
serialization_schema_selector=None, |
| 114 |
deserialization_schema_selector=None, |
| 115 |
many=False, |
| 116 |
**metadata |
| 117 |
): |
| 118 |
""" |
| 119 |
:param serialization_schema_selector: Function that takes in either |
| 120 |
an object representing that object, it's parent object |
| 121 |
and returns the appropriate schema. |
| 122 |
:param deserialization_schema_selector: Function that takes in either |
| 123 |
an a dict representing that object, dict representing it's parent dict |
| 124 |
and returns the appropriate schema |
| 125 |
|
| 126 |
""" |
| 127 |
super().__init__(many=many, **metadata) |
| 128 |
self._serialization_schema_selector_arg = serialization_schema_selector |
| 129 |
self._deserialization_schema_selector_arg = deserialization_schema_selector |
| 130 |
|
| 131 |
def serialization_schema_selector(self, value, obj): |
| 132 |
return self._serialization_schema_selector_arg(value, obj) |
| 133 |
|
| 134 |
def deserialization_schema_selector(self, value, obj): |
| 135 |
return self._deserialization_schema_selector_arg(value, obj) |