_schema_generation_shared.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """Types and utility functions used by various other internal tools."""
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING, Any, Callable, Literal
  4. from pydantic_core import core_schema
  5. from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
  6. if TYPE_CHECKING:
  7. from ..json_schema import GenerateJsonSchema, JsonSchemaValue
  8. from ._core_utils import CoreSchemaOrField
  9. from ._generate_schema import GenerateSchema
  10. from ._namespace_utils import NamespacesTuple
  11. GetJsonSchemaFunction = Callable[[CoreSchemaOrField, GetJsonSchemaHandler], JsonSchemaValue]
  12. HandlerOverride = Callable[[CoreSchemaOrField], JsonSchemaValue]
  13. class GenerateJsonSchemaHandler(GetJsonSchemaHandler):
  14. """JsonSchemaHandler implementation that doesn't do ref unwrapping by default.
  15. This is used for any Annotated metadata so that we don't end up with conflicting
  16. modifications to the definition schema.
  17. Used internally by Pydantic, please do not rely on this implementation.
  18. See `GetJsonSchemaHandler` for the handler API.
  19. """
  20. def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: HandlerOverride | None) -> None:
  21. self.generate_json_schema = generate_json_schema
  22. self.handler = handler_override or generate_json_schema.generate_inner
  23. self.mode = generate_json_schema.mode
  24. def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
  25. return self.handler(core_schema)
  26. def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
  27. """Resolves `$ref` in the json schema.
  28. This returns the input json schema if there is no `$ref` in json schema.
  29. Args:
  30. maybe_ref_json_schema: The input json schema that may contains `$ref`.
  31. Returns:
  32. Resolved json schema.
  33. Raises:
  34. LookupError: If it can't find the definition for `$ref`.
  35. """
  36. if '$ref' not in maybe_ref_json_schema:
  37. return maybe_ref_json_schema
  38. ref = maybe_ref_json_schema['$ref']
  39. json_schema = self.generate_json_schema.get_schema_from_definitions(ref)
  40. if json_schema is None:
  41. raise LookupError(
  42. f'Could not find a ref for {ref}.'
  43. ' Maybe you tried to call resolve_ref_schema from within a recursive model?'
  44. )
  45. return json_schema
  46. class CallbackGetCoreSchemaHandler(GetCoreSchemaHandler):
  47. """Wrapper to use an arbitrary function as a `GetCoreSchemaHandler`.
  48. Used internally by Pydantic, please do not rely on this implementation.
  49. See `GetCoreSchemaHandler` for the handler API.
  50. """
  51. def __init__(
  52. self,
  53. handler: Callable[[Any], core_schema.CoreSchema],
  54. generate_schema: GenerateSchema,
  55. ref_mode: Literal['to-def', 'unpack'] = 'to-def',
  56. ) -> None:
  57. self._handler = handler
  58. self._generate_schema = generate_schema
  59. self._ref_mode = ref_mode
  60. def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
  61. schema = self._handler(source_type)
  62. if self._ref_mode == 'to-def':
  63. ref = schema.get('ref')
  64. if ref is not None:
  65. return self._generate_schema.defs.create_definition_reference_schema(schema)
  66. return schema
  67. else: # ref_mode = 'unpack'
  68. return self.resolve_ref_schema(schema)
  69. def _get_types_namespace(self) -> NamespacesTuple:
  70. return self._generate_schema._types_namespace
  71. def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
  72. return self._generate_schema.generate_schema(source_type)
  73. @property
  74. def field_name(self) -> str | None:
  75. return self._generate_schema.field_name_stack.get()
  76. def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
  77. """Resolves reference in the core schema.
  78. Args:
  79. maybe_ref_schema: The input core schema that may contains reference.
  80. Returns:
  81. Resolved core schema.
  82. Raises:
  83. LookupError: If it can't find the definition for reference.
  84. """
  85. if maybe_ref_schema['type'] == 'definition-ref':
  86. ref = maybe_ref_schema['schema_ref']
  87. definition = self._generate_schema.defs.get_schema_from_ref(ref)
  88. if definition is None:
  89. raise LookupError(
  90. f'Could not find a ref for {ref}.'
  91. ' Maybe you tried to call resolve_ref_schema from within a recursive model?'
  92. )
  93. return definition
  94. elif maybe_ref_schema['type'] == 'definitions':
  95. return self.resolve_ref_schema(maybe_ref_schema['schema'])
  96. return maybe_ref_schema