1
1
""" Loaders Module """
2
+ from __future__ import annotations
3
+
2
4
import difflib
3
5
import json
4
6
import pathlib
5
7
from json import dumps , loads
6
- from typing import Callable , Dict , List , Optional , Tuple , cast
7
- from urllib .parse import ParseResult , urlparse
8
+ from typing import TYPE_CHECKING , cast
9
+ from urllib .parse import urlparse
8
10
9
11
import yaml
10
- from django .urls import Resolver404 , ResolverMatch , resolve
12
+ from django .urls import Resolver404 , resolve
11
13
from django .utils .functional import cached_property
12
14
from openapi_spec_validator import openapi_v2_spec_validator , openapi_v3_spec_validator
13
-
14
- # noinspection PyProtectedMember
15
15
from prance .util .resolver import RefResolver
16
-
17
- # noinspection PyProtectedMember
18
16
from rest_framework .schemas .generators import BaseSchemaGenerator , EndpointEnumerator
19
17
from rest_framework .settings import api_settings
18
+ from rest_framework .views import APIView
19
+
20
+ if TYPE_CHECKING :
21
+ from typing import Callable
22
+ from urllib .parse import ParseResult
20
23
21
- import openapi_tester . type_declarations as td
24
+ from django . urls import ResolverMatch
22
25
23
26
24
27
def handle_recursion_limit (schema : dict ) -> Callable :
@@ -47,12 +50,12 @@ class BaseSchemaLoader:
47
50
"""
48
51
49
52
base_path = "/"
50
- field_key_map : Dict [str , str ]
51
- schema : Optional [ dict ] = None
53
+ field_key_map : dict [str , str ]
54
+ schema : dict | None = None
52
55
53
- def __init__ (self , field_key_map : Optional [ Dict [ str , str ]] = None ):
56
+ def __init__ (self , field_key_map : dict [ str , str ] | None = None ):
54
57
super ().__init__ ()
55
- self .schema : Optional [ dict ] = None
58
+ self .schema : dict | None = None
56
59
self .field_key_map = field_key_map or {}
57
60
58
61
def load_schema (self ) -> dict :
@@ -82,8 +85,8 @@ def de_reference_schema(self, schema: dict) -> dict:
82
85
resolver .resolve_references ()
83
86
return resolver .specs
84
87
85
- def normalize_schema_paths (self , schema : dict ) -> Dict [str , dict ]:
86
- normalized_paths : Dict [str , dict ] = {}
88
+ def normalize_schema_paths (self , schema : dict ) -> dict [str , dict ]:
89
+ normalized_paths : dict [str , dict ] = {}
87
90
for key , value in schema ["paths" ].items ():
88
91
try :
89
92
parameterized_path , _ = self .resolve_path (endpoint_path = key , method = list (value .keys ())[0 ])
@@ -109,13 +112,13 @@ def set_schema(self, schema: dict) -> None:
109
112
self .schema = self .normalize_schema_paths (de_referenced_schema )
110
113
111
114
@cached_property
112
- def endpoints (self ) -> List [str ]: # pylint: disable=no-self-use
115
+ def endpoints (self ) -> list [str ]: # pylint: disable=no-self-use
113
116
"""
114
117
Returns a list of endpoint paths.
115
118
"""
116
119
return list ({endpoint [0 ] for endpoint in EndpointEnumerator ().get_api_endpoints ()})
117
120
118
- def resolve_path (self , endpoint_path : str , method : str ) -> Tuple [str , ResolverMatch ]:
121
+ def resolve_path (self , endpoint_path : str , method : str ) -> tuple [str , ResolverMatch ]:
119
122
"""
120
123
Resolves a Django path.
121
124
"""
@@ -147,12 +150,12 @@ def resolve_path(self, endpoint_path: str, method: str) -> Tuple[str, ResolverMa
147
150
raise ValueError (message )
148
151
149
152
@staticmethod
150
- def handle_pk_parameter (resolved_route : ResolverMatch , path : str , method : str ) -> Tuple [str , ResolverMatch ]:
153
+ def handle_pk_parameter (resolved_route : ResolverMatch , path : str , method : str ) -> tuple [str , ResolverMatch ]:
151
154
"""
152
155
Handle the DRF conversion of params called {pk} into a named parameter based on Model field
153
156
"""
154
157
coerced_path = BaseSchemaGenerator ().coerce_path (
155
- path = path , method = method , view = cast (td . APIView , resolved_route .func )
158
+ path = path , method = method , view = cast (APIView , resolved_route .func )
156
159
)
157
160
pk_field_name = "" .join (
158
161
entry .replace ("+ " , "" ) for entry in difflib .Differ ().compare (path , coerced_path ) if "+ " in entry
@@ -167,7 +170,7 @@ class DrfYasgSchemaLoader(BaseSchemaLoader):
167
170
Loads OpenAPI schema generated by drf_yasg.
168
171
"""
169
172
170
- def __init__ (self , field_key_map : Optional [ Dict [ str , str ]] = None ) -> None :
173
+ def __init__ (self , field_key_map : dict [ str , str ] | None = None ) -> None :
171
174
super ().__init__ (field_key_map = field_key_map )
172
175
from drf_yasg .generators import OpenAPISchemaGenerator
173
176
from drf_yasg .openapi import Info
@@ -181,7 +184,7 @@ def load_schema(self) -> dict:
181
184
odict_schema = self .schema_generator .get_schema (None , True )
182
185
return loads (dumps (odict_schema .as_odict ()))
183
186
184
- def resolve_path (self , endpoint_path : str , method : str ) -> Tuple [str , ResolverMatch ]:
187
+ def resolve_path (self , endpoint_path : str , method : str ) -> tuple [str , ResolverMatch ]:
185
188
de_parameterized_path , resolved_path = super ().resolve_path (endpoint_path = endpoint_path , method = method )
186
189
path_prefix = self .schema_generator .determine_path_prefix (self .endpoints )
187
190
trim_length = len (path_prefix ) if path_prefix != "/" else 0
@@ -193,7 +196,7 @@ class DrfSpectacularSchemaLoader(BaseSchemaLoader):
193
196
Loads OpenAPI schema generated by drf_spectacular.
194
197
"""
195
198
196
- def __init__ (self , field_key_map : Optional [ Dict [ str , str ]] = None ) -> None :
199
+ def __init__ (self , field_key_map : dict [ str , str ] | None = None ) -> None :
197
200
super ().__init__ (field_key_map = field_key_map )
198
201
from drf_spectacular .generators import SchemaGenerator
199
202
@@ -205,7 +208,7 @@ def load_schema(self) -> dict:
205
208
"""
206
209
return loads (dumps (self .schema_generator .get_schema (public = True )))
207
210
208
- def resolve_path (self , endpoint_path : str , method : str ) -> Tuple [str , ResolverMatch ]:
211
+ def resolve_path (self , endpoint_path : str , method : str ) -> tuple [str , ResolverMatch ]:
209
212
from drf_spectacular .settings import spectacular_settings
210
213
211
214
de_parameterized_path , resolved_path = super ().resolve_path (endpoint_path = endpoint_path , method = method )
@@ -220,7 +223,7 @@ class StaticSchemaLoader(BaseSchemaLoader):
220
223
Loads OpenAPI schema from a static file.
221
224
"""
222
225
223
- def __init__ (self , path : str , field_key_map : Optional [ Dict [ str , str ]] = None ):
226
+ def __init__ (self , path : str , field_key_map : dict [ str , str ] | None = None ):
224
227
super ().__init__ (field_key_map = field_key_map )
225
228
self .path = path if not isinstance (path , pathlib .PosixPath ) else str (path )
226
229
0 commit comments