From 504ab7223f0f7f39237d9c3e8dce992925d0a857 Mon Sep 17 00:00:00 2001 From: sushichan044 Date: Wed, 16 Oct 2024 10:59:35 +0900 Subject: [PATCH 1/2] fix: add is_instance_schema to improve validation behavior --- common/birdxplorer_common/models.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/common/birdxplorer_common/models.py b/common/birdxplorer_common/models.py index 0e9801f..a561af4 100644 --- a/common/birdxplorer_common/models.py +++ b/common/birdxplorer_common/models.py @@ -741,9 +741,14 @@ def from_url(cls, url: HttpUrl) -> "LinkId": @classmethod def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: - return core_schema.no_info_plain_validator_function( - cls.validate, - serialization=core_schema.plain_serializer_function_ser_schema(cls.serialize, when_used="json"), + return core_schema.union_schema( + [ + core_schema.is_instance_schema(cls), + core_schema.no_info_plain_validator_function(cls.validate), + ], + serialization=core_schema.plain_serializer_function_ser_schema( + cls.serialize, info_arg=False, when_used="json" + ), ) @classmethod From e77fe1b37953975a92f3648e384258e52eca2266 Mon Sep 17 00:00:00 2001 From: sushichan044 Date: Wed, 16 Oct 2024 11:23:13 +0900 Subject: [PATCH 2/2] fix: json schema of LinkId --- common/birdxplorer_common/models.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/common/birdxplorer_common/models.py b/common/birdxplorer_common/models.py index a561af4..2a81b67 100644 --- a/common/birdxplorer_common/models.py +++ b/common/birdxplorer_common/models.py @@ -21,12 +21,14 @@ from pydantic import Field as PydanticField from pydantic import ( GetCoreSchemaHandler, + GetJsonSchemaHandler, HttpUrl, TypeAdapter, computed_field, model_validator, ) from pydantic.alias_generators import to_camel +from pydantic.json_schema import JsonSchemaValue from pydantic.main import IncEx from pydantic_core import core_schema @@ -751,6 +753,20 @@ def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: GetCoreSchema ), ) + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + json_schema = handler(core_schema) + json_schema = handler.resolve_ref_schema(json_schema) + # __get_pydantic_core_schema__ に is_instance_schema を追加したが、 + # APIから返却する際の実態は string (uuid) のみである + # この差分により、openapi specを自動生成する際に不要な anyOf: [] が生成されてしまうのを抑制する + del json_schema["anyOf"] + json_schema["type"] = "string" + json_schema["format"] = "uuid" + return json_schema + @classmethod def validate(cls, v: Any) -> "LinkId": return cls(v)