| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
from typing import Any |
| 5 |
from datetime import date, datetime |
| 6 |
from collections import UserString |
| 7 |
from collections.abc import Set, Iterator, Sequence, MappingView |
| 8 |
from typing_extensions import override |
| 9 |
|
| 10 |
import pydantic |
| 11 |
|
| 12 |
from ._utils import is_mapping |
| 13 |
from .._files import is_base64_file_input |
| 14 |
from .._compat import model_dump |
| 15 |
|
| 16 |
# told apart by exact type alone, sparing the most common lists the slow abstract instance checks |
| 17 |
LIST_TYPES = frozenset((list, tuple, set, frozenset)) |
| 18 |
|
| 19 |
|
| 20 |
def openapi_dumps(obj: Any) -> bytes: |
| 21 |
""" |
| 22 |
Serialize an object to UTF-8 encoded JSON bytes. |
| 23 |
|
| 24 |
Extends the standard json.dumps with support for additional types |
| 25 |
commonly used in the SDK, such as `datetime`, `pydantic.BaseModel`, etc. |
| 26 |
""" |
| 27 |
return encoder.encode(obj).encode() |
| 28 |
|
| 29 |
|
| 30 |
def openapi_dumps_str(obj: Any) -> str: |
| 31 |
"""`openapi_dumps`, as a `str`; for transports that send text frames.""" |
| 32 |
return encoder.encode(obj) |
| 33 |
|
| 34 |
|
| 35 |
def is_sent_as_list(value: object) -> bool: |
| 36 |
"""Whether a value that is not a mapping is sent as a JSON array, or as `key[]=` entries in a query. |
| 37 |
|
| 38 |
Sequences, sets, dict views and iterators (generators, `map`, `iter(...)`) are. An object that |
| 39 |
merely defines `__iter__` is not iterated: it is left to the encoder in a body, and sent as |
| 40 |
its `str()` in a query. |
| 41 |
""" |
| 42 |
kind = type(value) |
| 43 |
if kind in LIST_TYPES: |
| 44 |
return True |
| 45 |
|
| 46 |
# sequences of characters or bytes, and file objects -- iterators over their lines |
| 47 |
if isinstance(value, (str, bytes, bytearray, memoryview, UserString)) or is_base64_file_input(value): |
| 48 |
return False |
| 49 |
|
| 50 |
return isinstance(value, (Sequence, Set, MappingView, Iterator)) |
| 51 |
|
| 52 |
|
| 53 |
def openapi_model_dump(model: pydantic.BaseModel) -> dict[str, Any]: |
| 54 |
"""Dump a model as it is sent in a request body, without the fields named in `__api_exclude__`.""" |
| 55 |
return model_dump( |
| 56 |
model, exclude_unset=True, mode="json", by_alias=True, exclude=getattr(model, "__api_exclude__", None) |
| 57 |
) |
| 58 |
|
| 59 |
|
| 60 |
class _CustomEncoder(json.JSONEncoder): |
| 61 |
@override |
| 62 |
def default(self, o: Any) -> Any: |
| 63 |
if isinstance(o, (datetime, date)): |
| 64 |
return o.isoformat() |
| 65 |
|
| 66 |
if isinstance(o, pydantic.BaseModel): |
| 67 |
return openapi_model_dump(o) |
| 68 |
|
| 69 |
if is_mapping(o): |
| 70 |
return dict(o) |
| 71 |
|
| 72 |
if is_sent_as_list(o): |
| 73 |
return list(o) |
| 74 |
|
| 75 |
return super().default(o) |
| 76 |
|
| 77 |
|
| 78 |
encoder = _CustomEncoder(ensure_ascii=False, separators=(",", ":"), allow_nan=False) |