|
| 1 | +""" |
| 2 | +This file adapted from FastAPI's encoders. |
| 3 | + |
| 4 | +Licensed under the MIT License (MIT). |
| 5 | + |
| 6 | +Copyright (c) 2018 Sebastián Ramírez |
| 7 | + |
| 8 | +Permission is hereby granted, free of charge, to any person obtaining a copy |
| 9 | +of this software and associated documentation files (the "Software"), to deal |
| 10 | +in the Software without restriction, including without limitation the rights |
| 11 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 12 | +copies of the Software, and to permit persons to whom the Software is |
| 13 | +furnished to do so, subject to the following conditions: |
| 14 | + |
| 15 | +The above copyright notice and this permission notice shall be included in |
| 16 | +all copies or substantial portions of the Software. |
| 17 | + |
| 18 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 19 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 20 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 21 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 22 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 23 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 24 | +THE SOFTWARE. |
| 25 | +""" |
| 26 | + |
| 27 | +import dataclasses |
| 28 | +from collections import defaultdict |
| 29 | +from enum import Enum |
| 30 | +from pathlib import PurePath |
| 31 | +from types import GeneratorType |
| 32 | +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union |
| 33 | + |
| 34 | +from pydantic import BaseModel |
| 35 | +from pydantic.json import ENCODERS_BY_TYPE |
| 36 | + |
| 37 | + |
| 38 | +SetIntStr = Set[Union[int, str]] |
| 39 | +DictIntStrAny = Dict[Union[int, str], Any] |
| 40 | + |
| 41 | + |
| 42 | +def generate_encoders_by_class_tuples( |
| 43 | + type_encoder_map: Dict[Any, Callable[[Any], Any]] |
| 44 | +) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: |
| 45 | + encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( |
| 46 | + tuple |
| 47 | + ) |
| 48 | + for type_, encoder in type_encoder_map.items(): |
| 49 | + encoders_by_class_tuples[encoder] += (type_,) |
| 50 | + return encoders_by_class_tuples |
| 51 | + |
| 52 | + |
| 53 | +encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE) |
| 54 | + |
| 55 | + |
| 56 | +def jsonable_encoder( |
| 57 | + obj: Any, |
| 58 | + include: Optional[Union[SetIntStr, DictIntStrAny]] = None, |
| 59 | + exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, |
| 60 | + by_alias: bool = True, |
| 61 | + exclude_unset: bool = False, |
| 62 | + exclude_defaults: bool = False, |
| 63 | + exclude_none: bool = False, |
| 64 | + custom_encoder: Dict[Any, Callable[[Any], Any]] = {}, |
| 65 | + sqlalchemy_safe: bool = True, |
| 66 | +) -> Any: |
| 67 | + if include and not isinstance(include, (set, dict)): |
| 68 | + include = set(include) |
| 69 | + if exclude and not isinstance(exclude, (set, dict)): |
| 70 | + exclude = set(exclude) |
| 71 | + |
| 72 | + if isinstance(obj, BaseModel): |
| 73 | + encoder = getattr(obj.__config__, "json_encoders", {}) |
| 74 | + if custom_encoder: |
| 75 | + encoder.update(custom_encoder) |
| 76 | + obj_dict = obj.dict( |
| 77 | + include=include, # type: ignore # in Pydantic |
| 78 | + exclude=exclude, # type: ignore # in Pydantic |
| 79 | + by_alias=by_alias, |
| 80 | + exclude_unset=exclude_unset, |
| 81 | + exclude_none=exclude_none, |
| 82 | + exclude_defaults=exclude_defaults, |
| 83 | + ) |
| 84 | + if "__root__" in obj_dict: |
| 85 | + obj_dict = obj_dict["__root__"] |
| 86 | + return jsonable_encoder( |
| 87 | + obj_dict, |
| 88 | + exclude_none=exclude_none, |
| 89 | + exclude_defaults=exclude_defaults, |
| 90 | + custom_encoder=encoder, |
| 91 | + sqlalchemy_safe=sqlalchemy_safe, |
| 92 | + ) |
| 93 | + if dataclasses.is_dataclass(obj): |
| 94 | + return dataclasses.asdict(obj) |
| 95 | + if isinstance(obj, Enum): |
| 96 | + return obj.value |
| 97 | + if isinstance(obj, PurePath): |
| 98 | + return str(obj) |
| 99 | + if isinstance(obj, (str, int, float, type(None))): |
| 100 | + return obj |
| 101 | + if isinstance(obj, dict): |
| 102 | + encoded_dict = {} |
| 103 | + for key, value in obj.items(): |
| 104 | + if ( |
| 105 | + ( |
| 106 | + not sqlalchemy_safe |
| 107 | + or (not isinstance(key, str)) |
| 108 | + or (not key.startswith("_sa")) |
| 109 | + ) |
| 110 | + and (value or not exclude_none) |
| 111 | + and ((include and key in include) or not exclude or key not in exclude) |
| 112 | + ): |
| 113 | + encoded_key = jsonable_encoder( |
| 114 | + key, |
| 115 | + by_alias=by_alias, |
| 116 | + exclude_unset=exclude_unset, |
| 117 | + exclude_none=exclude_none, |
| 118 | + custom_encoder=custom_encoder, |
| 119 | + sqlalchemy_safe=sqlalchemy_safe, |
| 120 | + ) |
| 121 | + encoded_value = jsonable_encoder( |
| 122 | + value, |
| 123 | + by_alias=by_alias, |
| 124 | + exclude_unset=exclude_unset, |
| 125 | + exclude_none=exclude_none, |
| 126 | + custom_encoder=custom_encoder, |
| 127 | + sqlalchemy_safe=sqlalchemy_safe, |
| 128 | + ) |
| 129 | + encoded_dict[encoded_key] = encoded_value |
| 130 | + return encoded_dict |
| 131 | + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)): |
| 132 | + encoded_list = [] |
| 133 | + for item in obj: |
| 134 | + encoded_list.append( |
| 135 | + jsonable_encoder( |
| 136 | + item, |
| 137 | + include=include, |
| 138 | + exclude=exclude, |
| 139 | + by_alias=by_alias, |
| 140 | + exclude_unset=exclude_unset, |
| 141 | + exclude_defaults=exclude_defaults, |
| 142 | + exclude_none=exclude_none, |
| 143 | + custom_encoder=custom_encoder, |
| 144 | + sqlalchemy_safe=sqlalchemy_safe, |
| 145 | + ) |
| 146 | + ) |
| 147 | + return encoded_list |
| 148 | + |
| 149 | + if custom_encoder: |
| 150 | + if type(obj) in custom_encoder: |
| 151 | + return custom_encoder[type(obj)](obj) |
| 152 | + else: |
| 153 | + for encoder_type, encoder in custom_encoder.items(): |
| 154 | + if isinstance(obj, encoder_type): |
| 155 | + return encoder(obj) |
| 156 | + |
| 157 | + if type(obj) in ENCODERS_BY_TYPE: |
| 158 | + return ENCODERS_BY_TYPE[type(obj)](obj) |
| 159 | + for encoder, classes_tuple in encoders_by_class_tuples.items(): |
| 160 | + if isinstance(obj, classes_tuple): |
| 161 | + return encoder(obj) |
| 162 | + |
| 163 | + errors: List[Exception] = [] |
| 164 | + try: |
| 165 | + data = dict(obj) |
| 166 | + except Exception as e: |
| 167 | + errors.append(e) |
| 168 | + try: |
| 169 | + data = vars(obj) |
| 170 | + except Exception as e: |
| 171 | + errors.append(e) |
| 172 | + raise ValueError(errors) |
| 173 | + return jsonable_encoder( |
| 174 | + data, |
| 175 | + by_alias=by_alias, |
| 176 | + exclude_unset=exclude_unset, |
| 177 | + exclude_defaults=exclude_defaults, |
| 178 | + exclude_none=exclude_none, |
| 179 | + custom_encoder=custom_encoder, |
| 180 | + sqlalchemy_safe=sqlalchemy_safe, |
| 181 | + ) |
0 commit comments