File: deserializers.py

package info (click to toggle)
python-openapi-core 0.22.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,104 kB
  • sloc: python: 19,979; makefile: 44
file content (47 lines) | stat: -rw-r--r-- 1,579 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
import warnings
from typing import Any
from typing import Mapping
from typing import Optional

from jsonschema_path import SchemaPath

from openapi_core.casting.schemas.casters import SchemaCaster
from openapi_core.casting.schemas.exceptions import CastError
from openapi_core.deserializing.exceptions import DeserializeError
from openapi_core.deserializing.styles.datatypes import DeserializerCallable


class StyleDeserializer:
    def __init__(
        self,
        style: str,
        explode: bool,
        name: str,
        schema: SchemaPath,
        caster: SchemaCaster,
        deserializer_callable: Optional[DeserializerCallable] = None,
    ):
        self.style = style
        self.explode = explode
        self.name = name
        self.schema = schema
        self.schema_type = schema.getkey("type", "")
        self.caster = caster
        self.deserializer_callable = deserializer_callable

    def deserialize(self, location: Mapping[str, Any]) -> Any:
        if self.deserializer_callable is None:
            warnings.warn(f"Unsupported {self.style} style")
            return location[self.name]

        try:
            value = self.deserializer_callable(
                self.explode, self.name, self.schema_type, location
            )
        except (ValueError, TypeError, AttributeError) as exc:
            raise DeserializeError(self.style, self.name) from exc

        try:
            return self.caster.cast(value)
        except (ValueError, TypeError, AttributeError) as exc:
            raise CastError(value, self.schema_type) from exc