| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
jsonable_encoder converts a Python object to a JSON-friendly dict |
| 5 |
(e.g. datetimes to strings, Pydantic models to dicts). |
| 6 |
|
| 7 |
Taken from FastAPI, and made a bit simpler |
| 8 |
https://github.com/tiangolo/fastapi/blob/master/fastapi/encoders.py |
| 9 |
""" |
| 10 |
|
| 11 |
import base64 |
| 12 |
import dataclasses |
| 13 |
import datetime as dt |
| 14 |
from enum import Enum |
| 15 |
from pathlib import PurePath |
| 16 |
from types import GeneratorType |
| 17 |
from typing import Any, Callable, Dict, List, Optional, Set, Union |
| 18 |
|
| 19 |
import pydantic |
| 20 |
from .datetime_utils import serialize_datetime |
| 21 |
from .pydantic_utilities import ( |
| 22 |
IS_PYDANTIC_V2, |
| 23 |
encode_by_type, |
| 24 |
to_jsonable_with_fallback, |
| 25 |
) |
| 26 |
|
| 27 |
SetIntStr = Set[Union[int, str]] |
| 28 |
DictIntStrAny = Dict[Union[int, str], Any] |
| 29 |
|
| 30 |
|
| 31 |
def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: |
| 32 |
custom_encoder = custom_encoder or {} |
| 33 |
|
| 34 |
|
| 35 |
if obj is Ellipsis: |
| 36 |
return None |
| 37 |
if custom_encoder: |
| 38 |
if type(obj) in custom_encoder: |
| 39 |
return custom_encoder[type(obj)](obj) |
| 40 |
else: |
| 41 |
for encoder_type, encoder_instance in custom_encoder.items(): |
| 42 |
if isinstance(obj, encoder_type): |
| 43 |
return encoder_instance(obj) |
| 44 |
if isinstance(obj, pydantic.BaseModel): |
| 45 |
if IS_PYDANTIC_V2: |
| 46 |
encoder = getattr(obj.model_config, "json_encoders", {}) |
| 47 |
else: |
| 48 |
encoder = getattr(obj.__config__, "json_encoders", {}) |
| 49 |
if custom_encoder: |
| 50 |
encoder.update(custom_encoder) |
| 51 |
obj_dict = obj.dict(by_alias=True) |
| 52 |
if "__root__" in obj_dict: |
| 53 |
obj_dict = obj_dict["__root__"] |
| 54 |
if "root" in obj_dict: |
| 55 |
obj_dict = obj_dict["root"] |
| 56 |
return jsonable_encoder(obj_dict, custom_encoder=encoder) |
| 57 |
if dataclasses.is_dataclass(obj): |
| 58 |
obj_dict = dataclasses.asdict(obj) |
| 59 |
return jsonable_encoder(obj_dict, custom_encoder=custom_encoder) |
| 60 |
if isinstance(obj, bytes): |
| 61 |
return base64.b64encode(obj).decode("utf-8") |
| 62 |
if isinstance(obj, Enum): |
| 63 |
return obj.value |
| 64 |
if isinstance(obj, PurePath): |
| 65 |
return str(obj) |
| 66 |
if isinstance(obj, (str, int, float, type(None))): |
| 67 |
return obj |
| 68 |
if isinstance(obj, dt.datetime): |
| 69 |
return serialize_datetime(obj) |
| 70 |
if isinstance(obj, dt.date): |
| 71 |
return str(obj) |
| 72 |
if isinstance(obj, dict): |
| 73 |
encoded_dict = {} |
| 74 |
allowed_keys = set(obj.keys()) |
| 75 |
for key, value in obj.items(): |
| 76 |
if key in allowed_keys: |
| 77 |
if value is Ellipsis: |
| 78 |
continue |
| 79 |
encoded_key = jsonable_encoder(key, custom_encoder=custom_encoder) |
| 80 |
encoded_value = jsonable_encoder(value, custom_encoder=custom_encoder) |
| 81 |
encoded_dict[encoded_key] = encoded_value |
| 82 |
return encoded_dict |
| 83 |
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)): |
| 84 |
encoded_list = [] |
| 85 |
for item in obj: |
| 86 |
if item is Ellipsis: |
| 87 |
continue |
| 88 |
encoded_list.append(jsonable_encoder(item, custom_encoder=custom_encoder)) |
| 89 |
return encoded_list |
| 90 |
|
| 91 |
def fallback_serializer(o: Any) -> Any: |
| 92 |
attempt_encode = encode_by_type(o) |
| 93 |
if attempt_encode is not None: |
| 94 |
return attempt_encode |
| 95 |
|
| 96 |
try: |
| 97 |
data = dict(o) |
| 98 |
except Exception as e: |
| 99 |
errors: List[Exception] = [] |
| 100 |
errors.append(e) |
| 101 |
try: |
| 102 |
data = vars(o) |
| 103 |
except Exception as e: |
| 104 |
errors.append(e) |
| 105 |
raise ValueError(errors) from e |
| 106 |
return jsonable_encoder(data, custom_encoder=custom_encoder) |
| 107 |
|
| 108 |
return to_jsonable_with_fallback(obj, fallback_serializer) |
| 109 |
|
| 110 |
|
| 111 |
def encode_path_param(obj: Any) -> str: |
| 112 |
"""Encode a value for use in a URL path segment. |
| 113 |
|
| 114 |
Ensures proper string conversion for all types, including |
| 115 |
booleans which need lowercase 'true'/'false' rather than |
| 116 |
Python's 'True'/'False'. |
| 117 |
""" |
| 118 |
if isinstance(obj, bool): |
| 119 |
return "true" if obj else "false" |
| 120 |
return str(jsonable_encoder(obj)) |