1
1
from enum import Enum
2
- from typing import Any , Dict , Set , Type , Union
2
+ from typing import Any , Callable , Dict , Set , Type , Union
3
3
4
+ import pydantic
4
5
from pydantic import BaseModel
5
6
6
- try :
7
+ if hasattr (pydantic , "VERSION" ) and pydantic .VERSION .startswith ("1." ):
8
+ PYDANTIC_VERSION = 1
7
9
from pydantic .schema import (
8
10
get_flat_models_from_models ,
9
11
model_process_schema ,
10
12
)
11
- except ImportError :
12
- # We assume this is due to the user having pydantic 2.x installed.
13
- from pydantic .v1 .schema import ( # type: ignore
14
- get_flat_models_from_models ,
15
- model_process_schema ,
16
- )
13
+ elif hasattr (pydantic , "VERSION" ) and pydantic .VERSION .startswith ("2." ):
14
+ PYDANTIC_VERSION = 2
15
+ else :
16
+ raise ImportError ("Unsupported pydantic version." )
17
17
18
18
19
19
REF_PREFIX = "#/components/schemas/"
20
20
21
21
22
- def get_model_definitions (request_schema : Type [BaseModel ], response_schema : Type [BaseModel ]) -> Dict [str , Any ]:
22
+ def get_model_definitions_v1 (request_schema : Type [BaseModel ], response_schema : Type [BaseModel ]) -> Dict [str , Any ]:
23
23
"""
24
24
Gets the model schemas in jsonschema format from a sequence of Pydantic BaseModels.
25
25
"""
@@ -29,6 +29,16 @@ def get_model_definitions(request_schema: Type[BaseModel], response_schema: Type
29
29
return get_model_definitions_from_flat_models (flat_models = flat_models , model_name_map = model_name_map )
30
30
31
31
32
+ def get_model_definitions_v2 (request_schema : Type [BaseModel ], response_schema : Type [BaseModel ]) -> Dict [str , Any ]:
33
+ return {"RequestSchema" : request_schema .model_json_schema (), "ResponseSchema" : response_schema .model_json_schema ()}
34
+
35
+
36
+ if PYDANTIC_VERSION == 1 :
37
+ get_model_definitions : Callable = get_model_definitions_v1
38
+ elif PYDANTIC_VERSION == 2 :
39
+ get_model_definitions : Callable = get_model_definitions_v2
40
+
41
+
32
42
def get_model_definitions_from_flat_models (
33
43
* ,
34
44
flat_models : Set [Union [Type [BaseModel ], Type [Enum ]]],
0 commit comments