File: unmarshallers.py

package info (click to toggle)
python-openapi-core 0.19.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,008 kB
  • sloc: python: 18,868; makefile: 47
file content (311 lines) | stat: -rw-r--r-- 10,472 bytes parent folder | download
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
import logging
from typing import Any
from typing import Iterable
from typing import List
from typing import Mapping
from typing import Optional
from typing import Type
from typing import Union

from jsonschema_path import SchemaPath

from openapi_core.extensions.models.factories import ModelPathFactory
from openapi_core.schema.schemas import get_properties
from openapi_core.unmarshalling.schemas.datatypes import FormatUnmarshaller
from openapi_core.unmarshalling.schemas.datatypes import (
    FormatUnmarshallersDict,
)
from openapi_core.validation.schemas.validators import SchemaValidator

log = logging.getLogger(__name__)


class PrimitiveUnmarshaller:
    def __init__(
        self,
        schema: SchemaPath,
        schema_validator: SchemaValidator,
        schema_unmarshaller: "SchemaUnmarshaller",
    ) -> None:
        self.schema = schema
        self.schema_validator = schema_validator
        self.schema_unmarshaller = schema_unmarshaller

    def __call__(self, value: Any) -> Any:
        return value


class ArrayUnmarshaller(PrimitiveUnmarshaller):
    def __call__(self, value: Any) -> Optional[List[Any]]:
        return list(map(self.items_unmarshaller.unmarshal, value))

    @property
    def items_unmarshaller(self) -> "SchemaUnmarshaller":
        # sometimes we don't have any schema i.e. free-form objects
        items_schema = self.schema.get("items", SchemaPath.from_dict({}))
        return self.schema_unmarshaller.evolve(items_schema)


class ObjectUnmarshaller(PrimitiveUnmarshaller):
    def __call__(self, value: Any) -> Any:
        properties = self._unmarshal_properties(value)

        fields: Iterable[str] = properties and properties.keys() or []
        object_class = self.object_class_factory.create(self.schema, fields)

        return object_class(**properties)

    @property
    def object_class_factory(self) -> ModelPathFactory:
        return ModelPathFactory()

    def evolve(self, schema: SchemaPath) -> "ObjectUnmarshaller":
        cls = self.__class__

        return cls(
            schema,
            self.schema_validator.evolve(schema),
            self.schema_unmarshaller,
        )

    def _unmarshal_properties(
        self, value: Any, schema_only: bool = False
    ) -> Any:
        properties = {}

        one_of_schema = self.schema_validator.get_one_of_schema(value)
        if one_of_schema is not None:
            one_of_properties = self.evolve(
                one_of_schema
            )._unmarshal_properties(value, schema_only=True)
            properties.update(one_of_properties)

        any_of_schemas = self.schema_validator.iter_any_of_schemas(value)
        for any_of_schema in any_of_schemas:
            any_of_properties = self.evolve(
                any_of_schema
            )._unmarshal_properties(value, schema_only=True)
            properties.update(any_of_properties)

        all_of_schemas = self.schema_validator.iter_all_of_schemas(value)
        for all_of_schema in all_of_schemas:
            all_of_properties = self.evolve(
                all_of_schema
            )._unmarshal_properties(value, schema_only=True)
            properties.update(all_of_properties)

        for prop_name, prop_schema in get_properties(self.schema).items():
            try:
                prop_value = value[prop_name]
            except KeyError:
                if "default" not in prop_schema:
                    continue
                prop_value = prop_schema["default"]

            properties[prop_name] = self.schema_unmarshaller.evolve(
                prop_schema
            ).unmarshal(prop_value)

        if schema_only:
            return properties

        additional_properties = self.schema.getkey(
            "additionalProperties", True
        )
        if additional_properties is not False:
            # free-form object
            if additional_properties is True:
                additional_prop_schema = SchemaPath.from_dict(
                    {"nullable": True}
                )
            # defined schema
            else:
                additional_prop_schema = self.schema / "additionalProperties"
            additional_prop_unmarshaler = self.schema_unmarshaller.evolve(
                additional_prop_schema
            )
            for prop_name, prop_value in value.items():
                if prop_name in properties:
                    continue
                properties[prop_name] = additional_prop_unmarshaler.unmarshal(
                    prop_value
                )

        return properties


class MultiTypeUnmarshaller(PrimitiveUnmarshaller):
    def __call__(self, value: Any) -> Any:
        primitive_type = self.schema_validator.get_primitive_type(value)
        # OpenAPI 3.0: handle no type for None
        if primitive_type is None:
            return None
        unmarshaller = self.schema_unmarshaller.get_type_unmarshaller(
            primitive_type
        )
        return unmarshaller(value)


class AnyUnmarshaller(MultiTypeUnmarshaller):
    pass


class TypesUnmarshaller:
    unmarshallers: Mapping[str, Type[PrimitiveUnmarshaller]] = {}
    multi: Optional[Type[PrimitiveUnmarshaller]] = None

    def __init__(
        self,
        unmarshallers: Mapping[str, Type[PrimitiveUnmarshaller]],
        default: Type[PrimitiveUnmarshaller],
        multi: Optional[Type[PrimitiveUnmarshaller]] = None,
    ):
        self.unmarshallers = unmarshallers
        self.default = default
        self.multi = multi

    def get_types(self) -> List[str]:
        return list(self.unmarshallers.keys())

    def get_unmarshaller_cls(
        self,
        schema_type: Optional[Union[Iterable[str], str]],
    ) -> Type["PrimitiveUnmarshaller"]:
        if schema_type is None:
            return self.default
        if isinstance(schema_type, Iterable) and not isinstance(
            schema_type, str
        ):
            if self.multi is None:
                raise TypeError("Unmarshaller does not accept multiple types")
            return self.multi

        return self.unmarshallers[schema_type]


class FormatsUnmarshaller:
    def __init__(
        self,
        format_unmarshallers: Optional[FormatUnmarshallersDict] = None,
        extra_format_unmarshallers: Optional[FormatUnmarshallersDict] = None,
    ):
        if format_unmarshallers is None:
            format_unmarshallers = {}
        self.format_unmarshallers = format_unmarshallers
        if extra_format_unmarshallers is None:
            extra_format_unmarshallers = {}
        self.extra_format_unmarshallers = extra_format_unmarshallers

    def unmarshal(self, schema_format: str, value: Any) -> Any:
        format_unmarshaller = self.get_unmarshaller(schema_format)
        if format_unmarshaller is None:
            return value
        try:
            return format_unmarshaller(value)
        except (AttributeError, ValueError, TypeError):
            return value

    def get_unmarshaller(
        self, schema_format: str
    ) -> Optional[FormatUnmarshaller]:
        if schema_format in self.extra_format_unmarshallers:
            return self.extra_format_unmarshallers[schema_format]
        if schema_format in self.format_unmarshallers:
            return self.format_unmarshallers[schema_format]

        return None

    def __contains__(self, schema_format: str) -> bool:
        format_unmarshallers_dicts: List[Mapping[str, Any]] = [
            self.extra_format_unmarshallers,
            self.format_unmarshallers,
        ]
        for content in format_unmarshallers_dicts:
            if schema_format in content:
                return True
        return False


class SchemaUnmarshaller:
    def __init__(
        self,
        schema: SchemaPath,
        schema_validator: SchemaValidator,
        types_unmarshaller: TypesUnmarshaller,
        formats_unmarshaller: FormatsUnmarshaller,
    ):
        self.schema = schema
        self.schema_validator = schema_validator

        self.types_unmarshaller = types_unmarshaller
        self.formats_unmarshaller = formats_unmarshaller

    def unmarshal(self, value: Any) -> Any:
        self.schema_validator.validate(value)

        # skip unmarshalling for nullable in OpenAPI 3.0
        if value is None and self.schema.getkey("nullable", False):
            return value

        schema_type = self.schema.getkey("type")
        type_unmarshaller = self.get_type_unmarshaller(schema_type)
        typed = type_unmarshaller(value)
        # skip finding format for None
        if typed is None:
            return None
        schema_format = self.find_format(value)
        if schema_format is None:
            return typed
        # ignore incompatible formats
        if not (
            isinstance(value, str)
            or
            # Workaround allows bytes for binary and byte formats
            (isinstance(value, bytes) and schema_format in ["binary", "byte"])
        ):
            return typed

        format_unmarshaller = self.get_format_unmarshaller(schema_format)
        if format_unmarshaller is None:
            return typed
        try:
            return format_unmarshaller(typed)
        except (AttributeError, ValueError, TypeError):
            return typed

    def get_type_unmarshaller(
        self,
        schema_type: Optional[Union[Iterable[str], str]],
    ) -> PrimitiveUnmarshaller:
        klass = self.types_unmarshaller.get_unmarshaller_cls(schema_type)
        return klass(
            self.schema,
            self.schema_validator,
            self,
        )

    def get_format_unmarshaller(
        self,
        schema_format: str,
    ) -> Optional[FormatUnmarshaller]:
        return self.formats_unmarshaller.get_unmarshaller(schema_format)

    def evolve(self, schema: SchemaPath) -> "SchemaUnmarshaller":
        cls = self.__class__

        return cls(
            schema,
            self.schema_validator.evolve(schema),
            self.types_unmarshaller,
            self.formats_unmarshaller,
        )

    def find_format(self, value: Any) -> Optional[str]:
        for schema in self.schema_validator.iter_valid_schemas(value):
            schema_validator = self.schema_validator.evolve(schema)
            primitive_type = schema_validator.get_primitive_type(value)
            if primitive_type != "string":
                continue
            if "format" in schema:
                return str(schema.getkey("format"))
        return None