Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
514 lines (465 loc) · 19.3 KB
/
Copy pathparser.py
File metadata and controls
514 lines (465 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
from __future__ import annotations
import pathlib
import re
from functools import reduce
from typing import (
Any,
Callable,
DefaultDict,
Dict,
Iterable,
List,
Mapping,
Optional,
Pattern,
Sequence,
Set,
Type,
Union,
)
from urllib.parse import ParseResult
import stringcase
from datamodel_code_generator import (
DefaultPutDict,
LiteralType,
OpenAPIScope,
PythonVersion,
snooper_to_methods,
)
from datamodel_code_generator.imports import Import, Imports
from datamodel_code_generator.model import DataModel, DataModelFieldBase
from datamodel_code_generator.model import pydantic as pydantic_model
from datamodel_code_generator.model.pydantic import CustomRootType, DataModelField
from datamodel_code_generator.parser.jsonschema import JsonSchemaObject
from datamodel_code_generator.parser.openapi import MediaObject
from datamodel_code_generator.parser.openapi import OpenAPIParser as OpenAPIModelParser
from datamodel_code_generator.parser.openapi import (
ParameterLocation,
ParameterObject,
ReferenceObject,
RequestBodyObject,
ResponseObject,
)
from datamodel_code_generator.types import DataType, DataTypeManager, StrictTypes
from datamodel_code_generator.util import cached_property
from pydantic import BaseModel, ValidationInfo
RE_APPLICATION_JSON_PATTERN: Pattern[str] = re.compile(r'^application/.*json$')
class CachedPropertyModel(BaseModel):
class Config:
arbitrary_types_allowed = True
ignored_types = (cached_property,)
class Response(BaseModel):
status_code: str
description: Optional[str]
contents: Dict[str, JsonSchemaObject]
class Request(BaseModel):
description: Optional[str]
contents: Dict[str, JsonSchemaObject]
required: bool
class UsefulStr(str):
@classmethod
def __get_validators__(cls) -> Any:
yield cls.validate
@classmethod
def validate(cls, v: Any, info: ValidationInfo) -> Any:
return cls(v)
@property
def snakecase(self) -> str:
return stringcase.snakecase(self)
@property
def pascalcase(self) -> str:
return stringcase.pascalcase(self)
@property
def camelcase(self) -> str:
return stringcase.camelcase(self)
class Argument(CachedPropertyModel):
name: UsefulStr
type_hint: UsefulStr
default: Optional[UsefulStr] = None
default_value: Optional[UsefulStr] = None
required: bool
def __str__(self) -> str:
return self.argument
@cached_property
def argument(self) -> str:
if self.default is None and self.required:
return f'{self.name}: {self.type_hint}'
return f'{self.name}: {self.type_hint} = {self.default}'
class Operation(CachedPropertyModel):
method: UsefulStr
path: UsefulStr
operationId: Optional[UsefulStr] = None
description: Optional[str] = None
summary: Optional[str] = None
parameters: List[Dict[str, Any]] = []
responses: Dict[UsefulStr, Any] = {}
deprecated: bool = False
imports: List[Import] = []
security: Optional[List[Dict[str, List[str]]]] = None
tags: Optional[List[str]] = []
arguments: List[Argument] = []
plain_parameters: str = ''
plain_arguments: str = ''
snake_case_arguments: List[Argument] = []
request: Optional[Argument] = None
response: str = ''
additional_responses: Dict[Union[str, int], Dict[str, str]] = {}
return_type: str = ''
callbacks: Dict[UsefulStr, List["Operation"]] = {}
@cached_property
def type(self) -> UsefulStr:
"""
backwards compatibility
"""
return self.method
@cached_property
def root_path(self) -> UsefulStr:
paths = self.path.split("/")
return UsefulStr(paths[1] if len(paths) > 1 else '')
@cached_property
def snake_case_path(self) -> str:
return re.sub(
r"{([^\}]+)}", lambda m: stringcase.snakecase(m.group()), self.path
)
@cached_property
def function_name(self) -> str:
if self.operationId:
name: str = self.operationId
else:
path = re.sub(r'/{|/', '_', self.snake_case_path).replace('}', '')
name = f"{self.type}{path}"
return stringcase.snakecase(name)
@snooper_to_methods(max_variable_length=None)
class OpenAPIParser(OpenAPIModelParser):
def __init__(
self,
source: Union[str, pathlib.Path, List[pathlib.Path], ParseResult],
*,
data_model_type: Type[DataModel] = pydantic_model.BaseModel,
data_model_root_type: Type[DataModel] = pydantic_model.CustomRootType,
data_type_manager_type: Type[DataTypeManager] = pydantic_model.DataTypeManager,
data_model_field_type: Type[DataModelFieldBase] = pydantic_model.DataModelField,
base_class: Optional[str] = None,
custom_template_dir: Optional[pathlib.Path] = None,
extra_template_data: Optional[DefaultDict[str, Dict[str, Any]]] = None,
target_python_version: PythonVersion = PythonVersion.PY_37,
dump_resolve_reference_action: Optional[Callable[[Iterable[str]], str]] = None,
validation: bool = False,
field_constraints: bool = False,
snake_case_field: bool = False,
strip_default_none: bool = False,
aliases: Optional[Mapping[str, str]] = None,
allow_population_by_field_name: bool = False,
apply_default_values_for_required_fields: bool = False,
force_optional_for_required_fields: bool = False,
class_name: Optional[str] = None,
use_standard_collections: bool = False,
base_path: Optional[pathlib.Path] = None,
use_schema_description: bool = False,
reuse_model: bool = False,
encoding: str = 'utf-8',
enum_field_as_literal: Optional[LiteralType] = None,
set_default_enum_member: bool = False,
strict_nullable: bool = False,
use_generic_container_types: bool = False,
enable_faux_immutability: bool = False,
remote_text_cache: Optional[DefaultPutDict[str, str]] = None,
disable_appending_item_suffix: bool = False,
strict_types: Optional[Sequence[StrictTypes]] = None,
empty_enum_field_name: Optional[str] = None,
custom_class_name_generator: Optional[Callable[[str], str]] = None,
field_extra_keys: Optional[Set[str]] = None,
field_include_all_keys: bool = False,
):
super().__init__(
source=source,
data_model_type=data_model_type,
data_model_root_type=data_model_root_type,
data_type_manager_type=data_type_manager_type,
data_model_field_type=data_model_field_type,
base_class=base_class,
custom_template_dir=custom_template_dir,
extra_template_data=extra_template_data,
target_python_version=target_python_version,
dump_resolve_reference_action=dump_resolve_reference_action,
validation=validation,
field_constraints=field_constraints,
snake_case_field=snake_case_field,
strip_default_none=strip_default_none,
aliases=aliases,
allow_population_by_field_name=allow_population_by_field_name,
apply_default_values_for_required_fields=apply_default_values_for_required_fields,
force_optional_for_required_fields=force_optional_for_required_fields,
class_name=class_name,
use_standard_collections=use_standard_collections,
base_path=base_path,
use_schema_description=use_schema_description,
reuse_model=reuse_model,
encoding=encoding,
enum_field_as_literal=enum_field_as_literal,
set_default_enum_member=set_default_enum_member,
strict_nullable=strict_nullable,
use_generic_container_types=use_generic_container_types,
enable_faux_immutability=enable_faux_immutability,
remote_text_cache=remote_text_cache,
disable_appending_item_suffix=disable_appending_item_suffix,
strict_types=strict_types,
empty_enum_field_name=empty_enum_field_name,
custom_class_name_generator=custom_class_name_generator,
field_extra_keys=field_extra_keys,
field_include_all_keys=field_include_all_keys,
openapi_scopes=[OpenAPIScope.Schemas, OpenAPIScope.Paths],
)
self.operations: Dict[str, Operation] = {}
self._temporary_operation: Dict[str, Any] = {}
self.imports_for_fastapi: Imports = Imports()
self.data_types: List[DataType] = []
def parse_info(self) -> Optional[Dict[str, Any]]:
result = self.raw_obj.get('info', {}).copy()
servers = self.raw_obj.get('servers')
if servers:
result['servers'] = servers
return result or None
def parse_all_parameters(
self,
name: str,
parameters: List[Union[ReferenceObject, ParameterObject]],
path: List[str],
) -> None:
super().parse_all_parameters(name, parameters, path)
self._temporary_operation['_parameters'].extend(parameters)
def get_parameter_type(
self,
parameters: Union[ReferenceObject, ParameterObject],
snake_case: bool,
path: List[str],
) -> Optional[Argument]:
parameters = self.resolve_object(parameters, ParameterObject)
orig_name = parameters.name
if snake_case:
name = stringcase.snakecase(parameters.name)
else:
name = parameters.name
schema: Optional[JsonSchemaObject] = None
data_type: Optional[DataType] = None
for content in parameters.content.values():
if isinstance(content.schema_, ReferenceObject):
data_type = self.get_ref_data_type(content.schema_.ref)
ref_model = self.get_ref_model(content.schema_.ref)
schema = JsonSchemaObject.parse_obj(ref_model)
else:
schema = content.schema_
break
if not data_type:
if not schema:
schema = parameters.schema_
if schema is None:
raise RuntimeError("schema is None") # pragma: no cover
data_type = self.parse_schema(name, schema, [*path, name])
data_type = self._collapse_root_model(data_type)
if not schema:
return None
field = DataModelField(
name=name,
data_type=data_type,
required=parameters.required or parameters.in_ == ParameterLocation.path,
)
if orig_name != name:
if parameters.in_:
param_is = parameters.in_.value.lower().capitalize()
self.imports_for_fastapi.append(
Import(from_='fastapi', import_=param_is)
)
default: Optional[str] = (
f"{param_is}({'...' if field.required else repr(schema.default)}, alias='{orig_name}')"
)
else:
default = repr(schema.default) if schema.has_default else None
self.imports_for_fastapi.append(field.imports)
self.data_types.append(field.data_type)
if field.name is None:
raise RuntimeError("field.name is None") # pragma: no cover
return Argument(
name=UsefulStr(field.name),
type_hint=UsefulStr(field.type_hint),
default=default, # type: ignore
default_value=schema.default,
required=field.required,
)
def get_argument_list(self, snake_case: bool, path: List[str]) -> List[Argument]:
arguments: List[Argument] = []
parameters = self._temporary_operation.get('_parameters')
if parameters:
for parameter in parameters:
parameter_type = self.get_parameter_type(
parameter, snake_case, [*path, 'parameters']
)
if parameter_type:
arguments.append(parameter_type)
arguments.append(
Argument(
name='request', # type: ignore
type_hint='Request', # type: ignore
required=True,
)
)
self.imports_for_fastapi.append(Import.from_full_path("fastapi.Request"))
positional_argument: bool = False
for argument in arguments:
if positional_argument and argument.required and argument.default is None:
argument.default = UsefulStr('...')
positional_argument = (
argument.required
or (argument.default is not None)
or argument.type_hint.startswith('Optional[')
)
return arguments
def parse_request_body(
self,
name: str,
request_body: RequestBodyObject,
path: List[str],
) -> None:
super().parse_request_body(name, request_body, path)
arguments: List[Argument] = []
for media_obj in request_body.content.values():
if isinstance(media_obj.schema_, JsonSchemaObject) and (
media_obj.schema_.format == 'binary'
):
arguments.append(
Argument(
name='file', # type: ignore
type_hint='UploadFile', # type: ignore
required=True,
)
)
self.imports_for_fastapi.append(
Import.from_full_path("fastapi.UploadFile")
)
self._temporary_operation['_request'] = arguments
def parse_responses( # type: ignore[override]
self,
name: str,
responses: Dict[str, Union[ResponseObject, ReferenceObject]],
path: List[str],
) -> Dict[Union[str, int], Dict[str, DataType]]:
data_types = super().parse_responses(name, responses, path) # type: ignore[arg-type]
status_code_200 = data_types.get('200')
if status_code_200:
data_type = list(status_code_200.values())[0]
if data_type:
data_type = self._collapse_root_model(data_type)
self.data_types.append(data_type)
else:
data_type = DataType(type='None')
type_hint = data_type.type_hint # TODO: change to lazy loading
self._temporary_operation['response'] = type_hint
return_types = {type_hint: data_type}
for status_code, additional_responses in data_types.items():
if status_code != '200' and additional_responses: # 200 is processed above
data_type = list(additional_responses.values())[0]
if data_type:
self.data_types.append(data_type)
type_hint = data_type.type_hint # TODO: change to lazy loading
self._temporary_operation.setdefault('additional_responses', {})[
status_code
] = {'model': type_hint}
return_types[type_hint] = data_type
if len(return_types) == 1:
return_type = next(iter(return_types.values()))
else:
return_type = DataType(data_types=list(return_types.values()))
if return_type:
self.data_types.append(return_type)
self._temporary_operation['return_type'] = return_type.type_hint
return data_types
def parse_operation(
self,
raw_operation: Dict[str, Any],
path: List[str],
) -> None:
self._temporary_operation = {}
self._temporary_operation['_parameters'] = []
super().parse_operation(raw_operation, path)
resolved_path = self.model_resolver.resolve_ref(path)
path_name, method = path[-2:]
self._temporary_operation['arguments'] = self.get_argument_list(
snake_case=False, path=path
)
self._temporary_operation['snake_case_arguments'] = self.get_argument_list(
snake_case=True, path=path
)
self._temporary_operation['plain_arguments'] = ",".join(
map(lambda a: a.name, self._temporary_operation['snake_case_arguments'])
)
self._temporary_operation['plain_parameters'] = ",".join(
map(
lambda a: f'{a.name}{": " + a.type_hint if a.type_hint is not None else ""}',
self._temporary_operation['snake_case_arguments'],
)
)
main_operation = self._temporary_operation
# Handle callbacks. This iterates over callbacks, shifting each one
# into the `_temporary_operation` and parsing it. Parsing could be
# refactored into a recursive operation to simplify this routine.
cb_ctr = 0
callbacks: Dict[UsefulStr, list[Operation]] = {}
if 'callbacks' in raw_operation:
raw_callbacks = raw_operation.pop('callbacks')
for key, routes in raw_callbacks.items():
if key not in callbacks:
callbacks[key] = []
for route, methods in routes.items():
for method, cb_op in methods.items():
# Since the path is often generated dynamically from
# the contents of the original request (such as by
# passing a `callbackUrl`), it won't work to generate
# a function name from the path. Instead, inject a
# placeholder `operationId` in order to get a unique
# and reasonable function name for the operation.
if 'operationId' not in cb_op:
cb_op['operationId'] = f"{method}_{key}_{cb_ctr}"
cb_ctr += 1
self._temporary_operation = {'_parameters': []}
cb_path = path + ['callbacks', key, route, method]
super().parse_operation(cb_op, cb_path)
self._temporary_operation['arguments'] = self.get_arguments(
snake_case=False, path=cb_path
)
self._temporary_operation['snake_case_arguments'] = (
self.get_arguments(snake_case=True, path=cb_path)
)
callbacks[key].append(
Operation(
**cb_op,
**self._temporary_operation,
path=route,
method=method, # type: ignore
)
)
self.operations[resolved_path] = Operation(
**raw_operation,
**main_operation,
callbacks=callbacks,
path=f'/{path_name}', # type: ignore
method=method, # type: ignore
)
def _collapse_root_model(self, data_type: DataType) -> DataType:
reference = data_type.reference
import functools
if not (
reference
and (
len(reference.children) == 1
or functools.reduce(lambda a, b: a == b, reference.children)
)
):
return data_type
source = reference.source
if not isinstance(source, CustomRootType):
return data_type
data_type.remove_reference()
data_type = source.fields[0].data_type
if source in self.results:
self.results.remove(source)
return data_type