aphilippov/python-server-api
0
1from typing import Any, Dict, Optional, Tuple, Type, Union, get_args2 3from pydantic import BaseModel4from pydantic.version import VERSION as PYDANTIC_VERSION5from typing_extensions import get_origin6 7__all__ = ("JsonSchemaValue", "model_dump", "model_dump_json", "type2schema", "evaluate_forwardref")8 9PYDANTIC_V1 = PYDANTIC_VERSION.startswith("1.")10 11if not PYDANTIC_V1:12 from pydantic import TypeAdapter13 from pydantic._internal._typing_extra import eval_type_lenient as evaluate_forwardref14 from pydantic.json_schema import JsonSchemaValue15 16 def type2schema(t: Optional[Type]) -> JsonSchemaValue:17 """Convert a type to a JSON schema18 19 Args:20 t (Type): The type to convert21 22 Returns:23 JsonSchemaValue: The JSON schema24 """25 return TypeAdapter(t).json_schema()26 27 def model_dump(model: BaseModel) -> Dict[str, Any]:28 """Convert a pydantic model to a dict29 30 Args:31 model (BaseModel): The model to convert32 33 Returns:34 Dict[str, Any]: The dict representation of the model35 36 """37 return model.model_dump()38 39 def model_dump_json(model: BaseModel) -> str:40 """Convert a pydantic model to a JSON string41 42 Args:43 model (BaseModel): The model to convert44 45 Returns:46 str: The JSON string representation of the model47 """48 return model.model_dump_json()49 50 51# Remove this once we drop support for pydantic 1.x52else: # pragma: no cover53 from pydantic import schema_of54 from pydantic.typing import evaluate_forwardref as evaluate_forwardref55 56 JsonSchemaValue = Dict[str, Any]57 58 def type2schema(t: Optional[Type]) -> JsonSchemaValue:59 """Convert a type to a JSON schema60 61 Args:62 t (Type): The type to convert63 64 Returns:65 JsonSchemaValue: The JSON schema66 """67 if PYDANTIC_V1:68 if t is None:69 return {"type": "null"}70 elif get_origin(t) is Union:71 return {"anyOf": [type2schema(tt) for tt in get_args(t)]}72 elif get_origin(t) in [Tuple, tuple]:73 prefixItems = [type2schema(tt) for tt in get_args(t)]74 return {75 "maxItems": len(prefixItems),76 "minItems": len(prefixItems),77 "prefixItems": prefixItems,78 "type": "array",79 }80 81 d = schema_of(t)82 if "title" in d:83 d.pop("title")84 if "description" in d:85 d.pop("description")86 87 return d88 89 def model_dump(model: BaseModel) -> Dict[str, Any]:90 """Convert a pydantic model to a dict91 92 Args:93 model (BaseModel): The model to convert94 95 Returns:96 Dict[str, Any]: The dict representation of the model97 98 """99 return model.dict()100 101 def model_dump_json(model: BaseModel) -> str:102 """Convert a pydantic model to a JSON string103 104 Args:105 model (BaseModel): The model to convert106 107 Returns:108 str: The JSON string representation of the model109 """110 return model.json()111 