Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

344 rindas
11 KiB

  1. import dataclasses
  2. import datetime
  3. from collections import defaultdict, deque
  4. from decimal import Decimal
  5. from enum import Enum
  6. from ipaddress import (
  7. IPv4Address,
  8. IPv4Interface,
  9. IPv4Network,
  10. IPv6Address,
  11. IPv6Interface,
  12. IPv6Network,
  13. )
  14. from pathlib import Path, PurePath
  15. from re import Pattern
  16. from types import GeneratorType
  17. from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
  18. from uuid import UUID
  19. from fastapi.types import IncEx
  20. from pydantic import BaseModel
  21. from pydantic.color import Color
  22. from pydantic.networks import AnyUrl, NameEmail
  23. from pydantic.types import SecretBytes, SecretStr
  24. from typing_extensions import Annotated, Doc
  25. from ._compat import PYDANTIC_V2, UndefinedType, Url, _model_dump
  26. # Taken from Pydantic v1 as is
  27. def isoformat(o: Union[datetime.date, datetime.time]) -> str:
  28. return o.isoformat()
  29. # Taken from Pydantic v1 as is
  30. # TODO: pv2 should this return strings instead?
  31. def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
  32. """
  33. Encodes a Decimal as int of there's no exponent, otherwise float
  34. This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
  35. where a integer (but not int typed) is used. Encoding this as a float
  36. results in failed round-tripping between encode and parse.
  37. Our Id type is a prime example of this.
  38. >>> decimal_encoder(Decimal("1.0"))
  39. 1.0
  40. >>> decimal_encoder(Decimal("1"))
  41. 1
  42. """
  43. if dec_value.as_tuple().exponent >= 0: # type: ignore[operator]
  44. return int(dec_value)
  45. else:
  46. return float(dec_value)
  47. ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
  48. bytes: lambda o: o.decode(),
  49. Color: str,
  50. datetime.date: isoformat,
  51. datetime.datetime: isoformat,
  52. datetime.time: isoformat,
  53. datetime.timedelta: lambda td: td.total_seconds(),
  54. Decimal: decimal_encoder,
  55. Enum: lambda o: o.value,
  56. frozenset: list,
  57. deque: list,
  58. GeneratorType: list,
  59. IPv4Address: str,
  60. IPv4Interface: str,
  61. IPv4Network: str,
  62. IPv6Address: str,
  63. IPv6Interface: str,
  64. IPv6Network: str,
  65. NameEmail: str,
  66. Path: str,
  67. Pattern: lambda o: o.pattern,
  68. SecretBytes: str,
  69. SecretStr: str,
  70. set: list,
  71. UUID: str,
  72. Url: str,
  73. AnyUrl: str,
  74. }
  75. def generate_encoders_by_class_tuples(
  76. type_encoder_map: Dict[Any, Callable[[Any], Any]],
  77. ) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:
  78. encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(
  79. tuple
  80. )
  81. for type_, encoder in type_encoder_map.items():
  82. encoders_by_class_tuples[encoder] += (type_,)
  83. return encoders_by_class_tuples
  84. encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)
  85. def jsonable_encoder(
  86. obj: Annotated[
  87. Any,
  88. Doc(
  89. """
  90. The input object to convert to JSON.
  91. """
  92. ),
  93. ],
  94. include: Annotated[
  95. Optional[IncEx],
  96. Doc(
  97. """
  98. Pydantic's `include` parameter, passed to Pydantic models to set the
  99. fields to include.
  100. """
  101. ),
  102. ] = None,
  103. exclude: Annotated[
  104. Optional[IncEx],
  105. Doc(
  106. """
  107. Pydantic's `exclude` parameter, passed to Pydantic models to set the
  108. fields to exclude.
  109. """
  110. ),
  111. ] = None,
  112. by_alias: Annotated[
  113. bool,
  114. Doc(
  115. """
  116. Pydantic's `by_alias` parameter, passed to Pydantic models to define if
  117. the output should use the alias names (when provided) or the Python
  118. attribute names. In an API, if you set an alias, it's probably because you
  119. want to use it in the result, so you probably want to leave this set to
  120. `True`.
  121. """
  122. ),
  123. ] = True,
  124. exclude_unset: Annotated[
  125. bool,
  126. Doc(
  127. """
  128. Pydantic's `exclude_unset` parameter, passed to Pydantic models to define
  129. if it should exclude from the output the fields that were not explicitly
  130. set (and that only had their default values).
  131. """
  132. ),
  133. ] = False,
  134. exclude_defaults: Annotated[
  135. bool,
  136. Doc(
  137. """
  138. Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define
  139. if it should exclude from the output the fields that had the same default
  140. value, even when they were explicitly set.
  141. """
  142. ),
  143. ] = False,
  144. exclude_none: Annotated[
  145. bool,
  146. Doc(
  147. """
  148. Pydantic's `exclude_none` parameter, passed to Pydantic models to define
  149. if it should exclude from the output any fields that have a `None` value.
  150. """
  151. ),
  152. ] = False,
  153. custom_encoder: Annotated[
  154. Optional[Dict[Any, Callable[[Any], Any]]],
  155. Doc(
  156. """
  157. Pydantic's `custom_encoder` parameter, passed to Pydantic models to define
  158. a custom encoder.
  159. """
  160. ),
  161. ] = None,
  162. sqlalchemy_safe: Annotated[
  163. bool,
  164. Doc(
  165. """
  166. Exclude from the output any fields that start with the name `_sa`.
  167. This is mainly a hack for compatibility with SQLAlchemy objects, they
  168. store internal SQLAlchemy-specific state in attributes named with `_sa`,
  169. and those objects can't (and shouldn't be) serialized to JSON.
  170. """
  171. ),
  172. ] = True,
  173. ) -> Any:
  174. """
  175. Convert any object to something that can be encoded in JSON.
  176. This is used internally by FastAPI to make sure anything you return can be
  177. encoded as JSON before it is sent to the client.
  178. You can also use it yourself, for example to convert objects before saving them
  179. in a database that supports only JSON.
  180. Read more about it in the
  181. [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).
  182. """
  183. custom_encoder = custom_encoder or {}
  184. if custom_encoder:
  185. if type(obj) in custom_encoder:
  186. return custom_encoder[type(obj)](obj)
  187. else:
  188. for encoder_type, encoder_instance in custom_encoder.items():
  189. if isinstance(obj, encoder_type):
  190. return encoder_instance(obj)
  191. if include is not None and not isinstance(include, (set, dict)):
  192. include = set(include)
  193. if exclude is not None and not isinstance(exclude, (set, dict)):
  194. exclude = set(exclude)
  195. if isinstance(obj, BaseModel):
  196. # TODO: remove when deprecating Pydantic v1
  197. encoders: Dict[Any, Any] = {}
  198. if not PYDANTIC_V2:
  199. encoders = getattr(obj.__config__, "json_encoders", {}) # type: ignore[attr-defined]
  200. if custom_encoder:
  201. encoders.update(custom_encoder)
  202. obj_dict = _model_dump(
  203. obj,
  204. mode="json",
  205. include=include,
  206. exclude=exclude,
  207. by_alias=by_alias,
  208. exclude_unset=exclude_unset,
  209. exclude_none=exclude_none,
  210. exclude_defaults=exclude_defaults,
  211. )
  212. if "__root__" in obj_dict:
  213. obj_dict = obj_dict["__root__"]
  214. return jsonable_encoder(
  215. obj_dict,
  216. exclude_none=exclude_none,
  217. exclude_defaults=exclude_defaults,
  218. # TODO: remove when deprecating Pydantic v1
  219. custom_encoder=encoders,
  220. sqlalchemy_safe=sqlalchemy_safe,
  221. )
  222. if dataclasses.is_dataclass(obj):
  223. obj_dict = dataclasses.asdict(obj)
  224. return jsonable_encoder(
  225. obj_dict,
  226. include=include,
  227. exclude=exclude,
  228. by_alias=by_alias,
  229. exclude_unset=exclude_unset,
  230. exclude_defaults=exclude_defaults,
  231. exclude_none=exclude_none,
  232. custom_encoder=custom_encoder,
  233. sqlalchemy_safe=sqlalchemy_safe,
  234. )
  235. if isinstance(obj, Enum):
  236. return obj.value
  237. if isinstance(obj, PurePath):
  238. return str(obj)
  239. if isinstance(obj, (str, int, float, type(None))):
  240. return obj
  241. if isinstance(obj, UndefinedType):
  242. return None
  243. if isinstance(obj, dict):
  244. encoded_dict = {}
  245. allowed_keys = set(obj.keys())
  246. if include is not None:
  247. allowed_keys &= set(include)
  248. if exclude is not None:
  249. allowed_keys -= set(exclude)
  250. for key, value in obj.items():
  251. if (
  252. (
  253. not sqlalchemy_safe
  254. or (not isinstance(key, str))
  255. or (not key.startswith("_sa"))
  256. )
  257. and (value is not None or not exclude_none)
  258. and key in allowed_keys
  259. ):
  260. encoded_key = jsonable_encoder(
  261. key,
  262. by_alias=by_alias,
  263. exclude_unset=exclude_unset,
  264. exclude_none=exclude_none,
  265. custom_encoder=custom_encoder,
  266. sqlalchemy_safe=sqlalchemy_safe,
  267. )
  268. encoded_value = jsonable_encoder(
  269. value,
  270. by_alias=by_alias,
  271. exclude_unset=exclude_unset,
  272. exclude_none=exclude_none,
  273. custom_encoder=custom_encoder,
  274. sqlalchemy_safe=sqlalchemy_safe,
  275. )
  276. encoded_dict[encoded_key] = encoded_value
  277. return encoded_dict
  278. if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):
  279. encoded_list = []
  280. for item in obj:
  281. encoded_list.append(
  282. jsonable_encoder(
  283. item,
  284. include=include,
  285. exclude=exclude,
  286. by_alias=by_alias,
  287. exclude_unset=exclude_unset,
  288. exclude_defaults=exclude_defaults,
  289. exclude_none=exclude_none,
  290. custom_encoder=custom_encoder,
  291. sqlalchemy_safe=sqlalchemy_safe,
  292. )
  293. )
  294. return encoded_list
  295. if type(obj) in ENCODERS_BY_TYPE:
  296. return ENCODERS_BY_TYPE[type(obj)](obj)
  297. for encoder, classes_tuple in encoders_by_class_tuples.items():
  298. if isinstance(obj, classes_tuple):
  299. return encoder(obj)
  300. try:
  301. data = dict(obj)
  302. except Exception as e:
  303. errors: List[Exception] = []
  304. errors.append(e)
  305. try:
  306. data = vars(obj)
  307. except Exception as e:
  308. errors.append(e)
  309. raise ValueError(errors) from e
  310. return jsonable_encoder(
  311. data,
  312. include=include,
  313. exclude=exclude,
  314. by_alias=by_alias,
  315. exclude_unset=exclude_unset,
  316. exclude_defaults=exclude_defaults,
  317. exclude_none=exclude_none,
  318. custom_encoder=custom_encoder,
  319. sqlalchemy_safe=sqlalchemy_safe,
  320. )