@autorest/python 5.15.0 → 5.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/ChangeLog.md +20 -0
  2. package/autorest/__init__.py +1 -2
  3. package/autorest/black/__init__.py +12 -5
  4. package/autorest/codegen/__init__.py +145 -73
  5. package/autorest/codegen/models/__init__.py +29 -18
  6. package/autorest/codegen/models/base_builder.py +48 -11
  7. package/autorest/codegen/models/base_model.py +6 -4
  8. package/autorest/codegen/models/base_schema.py +19 -18
  9. package/autorest/codegen/models/client.py +65 -21
  10. package/autorest/codegen/models/code_model.py +107 -61
  11. package/autorest/codegen/models/constant_schema.py +25 -13
  12. package/autorest/codegen/models/credential_model.py +23 -15
  13. package/autorest/codegen/models/credential_schema.py +18 -14
  14. package/autorest/codegen/models/credential_schema_policy.py +11 -15
  15. package/autorest/codegen/models/dictionary_schema.py +20 -17
  16. package/autorest/codegen/models/enum_schema.py +35 -25
  17. package/autorest/codegen/models/imports.py +70 -41
  18. package/autorest/codegen/models/list_schema.py +25 -13
  19. package/autorest/codegen/models/lro_operation.py +58 -22
  20. package/autorest/codegen/models/lro_paging_operation.py +2 -3
  21. package/autorest/codegen/models/object_schema.py +99 -49
  22. package/autorest/codegen/models/operation.py +236 -117
  23. package/autorest/codegen/models/operation_group.py +64 -34
  24. package/autorest/codegen/models/paging_operation.py +45 -18
  25. package/autorest/codegen/models/parameter.py +151 -83
  26. package/autorest/codegen/models/parameter_list.py +183 -162
  27. package/autorest/codegen/models/primitive_schemas.py +84 -55
  28. package/autorest/codegen/models/property.py +44 -26
  29. package/autorest/codegen/models/request_builder.py +65 -30
  30. package/autorest/codegen/models/request_builder_parameter.py +47 -23
  31. package/autorest/codegen/models/request_builder_parameter_list.py +77 -108
  32. package/autorest/codegen/models/schema_request.py +16 -6
  33. package/autorest/codegen/models/schema_response.py +18 -13
  34. package/autorest/codegen/models/utils.py +5 -2
  35. package/autorest/codegen/serializers/__init__.py +182 -91
  36. package/autorest/codegen/serializers/builder_serializer.py +667 -331
  37. package/autorest/codegen/serializers/client_serializer.py +98 -37
  38. package/autorest/codegen/serializers/general_serializer.py +61 -26
  39. package/autorest/codegen/serializers/import_serializer.py +93 -31
  40. package/autorest/codegen/serializers/metadata_serializer.py +73 -24
  41. package/autorest/codegen/serializers/model_base_serializer.py +35 -15
  42. package/autorest/codegen/serializers/model_generic_serializer.py +1 -4
  43. package/autorest/codegen/serializers/model_init_serializer.py +5 -1
  44. package/autorest/codegen/serializers/model_python3_serializer.py +7 -6
  45. package/autorest/codegen/serializers/operation_groups_serializer.py +20 -9
  46. package/autorest/codegen/serializers/operations_init_serializer.py +23 -11
  47. package/autorest/codegen/serializers/patch_serializer.py +4 -1
  48. package/autorest/codegen/serializers/{rest_serializer.py → request_builders_serializer.py} +29 -12
  49. package/autorest/codegen/serializers/utils.py +35 -21
  50. package/autorest/codegen/templates/init.py.jinja2 +2 -2
  51. package/autorest/codegen/templates/lro_operation.py.jinja2 +5 -7
  52. package/autorest/codegen/templates/lro_paging_operation.py.jinja2 +5 -7
  53. package/autorest/codegen/templates/metadata.json.jinja2 +7 -6
  54. package/autorest/codegen/templates/operation.py.jinja2 +7 -9
  55. package/autorest/codegen/templates/operation_group.py.jinja2 +2 -8
  56. package/autorest/codegen/templates/operation_groups_container.py.jinja2 +1 -1
  57. package/autorest/codegen/templates/paging_operation.py.jinja2 +7 -8
  58. package/autorest/codegen/templates/request_builder.py.jinja2 +18 -11
  59. package/autorest/jsonrpc/__init__.py +7 -12
  60. package/autorest/jsonrpc/localapi.py +4 -3
  61. package/autorest/jsonrpc/server.py +13 -6
  62. package/autorest/jsonrpc/stdstream.py +13 -6
  63. package/autorest/m2r/__init__.py +5 -8
  64. package/autorest/multiapi/__init__.py +24 -14
  65. package/autorest/multiapi/models/client.py +21 -11
  66. package/autorest/multiapi/models/code_model.py +23 -10
  67. package/autorest/multiapi/models/config.py +4 -1
  68. package/autorest/multiapi/models/constant_global_parameter.py +1 -0
  69. package/autorest/multiapi/models/global_parameter.py +2 -1
  70. package/autorest/multiapi/models/global_parameters.py +14 -8
  71. package/autorest/multiapi/models/imports.py +24 -17
  72. package/autorest/multiapi/models/mixin_operation.py +5 -5
  73. package/autorest/multiapi/models/operation_group.py +2 -1
  74. package/autorest/multiapi/models/operation_mixin_group.py +21 -10
  75. package/autorest/multiapi/serializers/__init__.py +18 -23
  76. package/autorest/multiapi/serializers/import_serializer.py +47 -17
  77. package/autorest/multiapi/serializers/multiapi_serializer.py +17 -17
  78. package/autorest/multiapi/templates/multiapi_operations_mixin.py.jinja2 +1 -1
  79. package/autorest/multiapi/utils.py +3 -3
  80. package/autorest/namer/__init__.py +2 -4
  81. package/autorest/namer/name_converter.py +200 -103
  82. package/autorest/namer/python_mappings.py +10 -22
  83. package/package.json +2 -2
  84. package/run-python3.js +2 -3
  85. package/venvtools.py +1 -1
  86. package/autorest/codegen/models/rest.py +0 -42
@@ -10,6 +10,7 @@ from collections import defaultdict
10
10
  from abc import abstractmethod, ABC
11
11
  from typing import Any, List, TypeVar, Dict, Union, Optional, cast
12
12
 
13
+
13
14
  from ..models import (
14
15
  Operation,
15
16
  CodeModel,
@@ -27,79 +28,54 @@ from ..models import (
27
28
  SchemaResponse,
28
29
  IOSchema,
29
30
  ParameterStyle,
30
- ParameterLocation
31
+ ParameterLocation,
32
+ ParameterMethodLocation,
31
33
  )
32
34
  from . import utils
33
35
 
34
36
  T = TypeVar("T")
35
37
  OrderedSet = Dict[T, None]
36
38
 
39
+
37
40
  def _escape_str(input_str: str) -> str:
38
41
  replace = input_str.replace("'", "\\'")
39
42
  return f'"{replace}"'
40
43
 
44
+
41
45
  def _improve_json_string(template_representation: str) -> Any:
42
- origin = template_representation.split('\n')
46
+ origin = template_representation.split("\n")
43
47
  final = []
44
48
  for line in origin:
45
- idx0 = line.find('#')
49
+ idx0 = line.find("#")
46
50
  idx1 = line.rfind('"')
47
51
  modified_line = ""
48
52
  if idx0 > -1 and idx1 > -1:
49
- modified_line = line[:idx0] + line[idx1:] + ' ' + line[idx0:idx1] + '\n'
53
+ modified_line = line[:idx0] + line[idx1:] + " " + line[idx0:idx1] + "\n"
50
54
  else:
51
- modified_line = line + '\n'
55
+ modified_line = line + "\n"
52
56
  modified_line = modified_line.replace('"', "").replace("\\", '"')
53
57
  final.append(modified_line)
54
- return ''.join(final)
58
+ return "".join(final)
59
+
55
60
 
56
61
  def _json_dumps_template(template_representation: Any) -> Any:
57
62
  # only for template use, since it wraps everything in strings
58
- return _improve_json_string(json.dumps(template_representation, sort_keys=True, indent=4))
59
-
60
- def _serialize_files_or_data_dict(multipart_parameters: List[Parameter]) -> str:
61
- # only for template use
62
- template = {
63
- f'"{param.serialized_name}"': param.schema.get_files_and_data_template_representation(
64
- optional=not param.required,
65
- description=param.description,
66
- )
67
- for param in multipart_parameters
68
- }
69
- return _json_dumps_template(template)
70
-
71
- def _get_files_example_template(builder) -> List[str]:
72
- multipart_params = builder.parameters.multipart
73
- if multipart_params:
74
- retval = [
75
- "# multipart input template you can fill out and use as your `files` input.",
76
- ]
77
- retval.extend(f"files = {_serialize_files_or_data_dict(multipart_params)}".splitlines())
78
- return retval
79
- raise ValueError(
80
- "You're trying to get a template for your multipart params, but you don't have multipart params"
63
+ return _improve_json_string(
64
+ json.dumps(template_representation, sort_keys=True, indent=4)
81
65
  )
82
66
 
83
- def _get_data_example_template(builder) -> List[str]:
84
- data_inputs = builder.parameters.data_inputs
85
- if data_inputs:
86
- retval = [
87
- "# form-encoded input template you can fill out and use as your `data` input."
88
- ]
89
- retval.extend(f"data = {_serialize_files_or_data_dict(data_inputs)}".splitlines())
90
- return retval
91
- raise ValueError(
92
- "You're trying to get a template for your form-encoded params, but you don't have form-encoded params"
93
- )
94
67
 
95
68
  def _content_type_error_check(builder) -> List[str]:
96
69
  retval = ["else:"]
97
70
  retval.append(" raise ValueError(")
98
- retval.append(" \"The content_type '{}' is not one of the allowed values: \"")
71
+ retval.append(
72
+ " \"The content_type '{}' is not one of the allowed values: \""
73
+ )
99
74
  retval.append(f' "{builder.parameters.content_types}".format(content_type)')
100
75
  retval.append(" )")
101
76
  return retval
102
77
 
78
+
103
79
  def _serialize_files_and_data_body(builder, param_name: str) -> List[str]:
104
80
  retval: List[str] = []
105
81
  # we have to construct our form data before passing to the request as well
@@ -110,12 +86,14 @@ def _serialize_files_and_data_body(builder, param_name: str) -> List[str]:
110
86
  retval.append("}")
111
87
  return retval
112
88
 
89
+
113
90
  def _serialize_grouped_body(builder) -> List[str]:
114
91
  retval: List[str] = []
115
92
  for grouped_parameter in builder.parameters.grouped:
116
93
  retval.append(f"{grouped_parameter.serialized_name} = None")
117
94
  for grouper_name, grouped_parameters in groupby(
118
- builder.parameters.grouped, key=lambda a: cast(Parameter, a.grouped_by).serialized_name
95
+ builder.parameters.grouped,
96
+ key=lambda a: cast(Parameter, a.grouped_by).serialized_name,
119
97
  ):
120
98
  retval.append(f"if {grouper_name} is not None:")
121
99
  for grouped_parameter in grouped_parameters:
@@ -125,6 +103,7 @@ def _serialize_grouped_body(builder) -> List[str]:
125
103
  )
126
104
  return retval
127
105
 
106
+
128
107
  def _serialize_flattened_body(builder) -> List[str]:
129
108
  retval: List[str] = []
130
109
  if not builder.parameters.is_flattened:
@@ -136,8 +115,10 @@ def _serialize_flattened_body(builder) -> List[str]:
136
115
  lambda parameter: parameter.in_method_code
137
116
  )
138
117
  parameter_string = ", ".join(
139
- [f"{param.target_property_name}={param.serialized_name}"
140
- for param in parameters if param.target_property_name
118
+ [
119
+ f"{param.target_property_name}={param.serialized_name}"
120
+ for param in parameters
121
+ if param.target_property_name
141
122
  ]
142
123
  )
143
124
  object_schema = cast(ObjectSchema, builder.parameters.body[0].schema)
@@ -146,23 +127,26 @@ def _serialize_flattened_body(builder) -> List[str]:
146
127
  )
147
128
  return retval
148
129
 
130
+
149
131
  def _content_type_docstring(builder) -> str:
150
132
  content_types = [f'"{c}"' for c in builder.parameters.content_types]
151
133
  if len(content_types) == 2:
152
134
  possible_values_str = " or ".join(content_types)
153
135
  else:
154
- possible_values_str = ", ".join(
155
- content_types[: len(content_types) - 1]
156
- ) + f", and {content_types[-1]}"
136
+ possible_values_str = (
137
+ ", ".join(content_types[: len(content_types) - 1])
138
+ + f", and {content_types[-1]}"
139
+ )
157
140
  default_value = next(
158
141
  p for p in builder.parameters.method if p.rest_api_name == "Content-Type"
159
142
  ).default_value_declaration
160
143
  return (
161
- ":keyword content_type: Media type of the body sent to the API. " +
162
- f"Known values are: {possible_values_str}. " +
163
- f"Default value is {default_value}."
144
+ ":keyword content_type: Media type of the body sent to the API. "
145
+ + f"Known values are: {possible_values_str}. "
146
+ + f"Default value is {default_value}."
164
147
  )
165
148
 
149
+
166
150
  class _BuilderSerializerProtocol(ABC):
167
151
  @property
168
152
  @abstractmethod
@@ -188,7 +172,9 @@ class _BuilderSerializerProtocol(ABC):
188
172
  ...
189
173
 
190
174
  @abstractmethod
191
- def _response_type_annotation(self, builder, modify_if_head_as_boolean: bool = True) -> str:
175
+ def _response_type_annotation(
176
+ self, builder, modify_if_head_as_boolean: bool = True
177
+ ) -> str:
192
178
  """The mypy type annotation for the response"""
193
179
  ...
194
180
 
@@ -207,7 +193,14 @@ class _BuilderSerializerProtocol(ABC):
207
193
  ...
208
194
 
209
195
  @abstractmethod
210
- def method_signature_and_response_type_annotation(self, builder) -> str:
196
+ def decorators(self, builder, async_mode: bool) -> List[str]:
197
+ """Decorators for the method"""
198
+ ...
199
+
200
+ @abstractmethod
201
+ def method_signature_and_response_type_annotation(
202
+ self, builder, async_mode: bool, *, want_decorators: Optional[bool] = True
203
+ ) -> str:
211
204
  """Combines the method signature + the response type annotation together"""
212
205
  ...
213
206
 
@@ -237,13 +230,6 @@ class _BuilderSerializerProtocol(ABC):
237
230
  def _has_json_example_template(self, builder) -> bool:
238
231
  ...
239
232
 
240
- @abstractmethod
241
- def _has_files_example_template(self, builder) -> bool:
242
- ...
243
- @abstractmethod
244
- def _has_data_example_template(self, builder) -> bool:
245
- ...
246
-
247
233
  @abstractmethod
248
234
  def _json_example_param_name(self, builder) -> str:
249
235
  ...
@@ -253,57 +239,98 @@ class _BuilderSerializerProtocol(ABC):
253
239
  ...
254
240
 
255
241
  @abstractmethod
256
- def _get_json_response_template_to_status_codes(self, builder) -> Dict[str, List[str]]:
242
+ def _get_json_response_template_to_status_codes(
243
+ self, builder
244
+ ) -> Dict[str, List[str]]:
257
245
  ...
258
246
 
259
247
  @abstractmethod
260
248
  def _get_kwargs_to_pop(self, builder) -> List[Parameter]:
261
249
  ...
262
250
 
263
- class _BuilderBaseSerializer(_BuilderSerializerProtocol): # pylint: disable=abstract-method
251
+
252
+ class _BuilderBaseSerializer(
253
+ _BuilderSerializerProtocol
254
+ ): # pylint: disable=abstract-method
264
255
  def __init__(self, code_model: CodeModel) -> None:
265
256
  self.code_model = code_model
266
257
 
267
258
  @property
268
259
  def _cls_docstring_rtype(self) -> str:
269
- return "" if self.code_model.options["version_tolerant"] else " or the result of cls(response)"
260
+ return (
261
+ ""
262
+ if self.code_model.options["version_tolerant"]
263
+ else " or the result of cls(response)"
264
+ )
265
+
266
+ def decorators(self, builder, async_mode: bool) -> List[str]:
267
+ """Decorators for the method"""
268
+ retval: List[str] = []
269
+ if self.code_model.options["tracing"] and builder.want_tracing:
270
+ retval.append(f"@distributed_trace{'_async' if async_mode else ''}")
271
+ return retval
270
272
 
271
- def _method_signature(self, builder: Operation, response_type_annotation: str) -> str:
273
+ def _method_signature(
274
+ self, builder: Operation, response_type_annotation: str
275
+ ) -> str:
272
276
  return utils.serialize_method(
273
277
  function_def=self._function_definition,
274
278
  method_name=builder.name,
275
279
  is_in_class=self._is_in_class,
276
- method_param_signatures=builder.parameters.method_signature(self._want_inline_type_hints),
277
- ignore_inconsistent_return_statements=(response_type_annotation == "None")
280
+ method_param_signatures=builder.method_signature(
281
+ self._want_inline_type_hints
282
+ ),
283
+ ignore_inconsistent_return_statements=(response_type_annotation == "None"),
278
284
  )
279
285
 
280
286
  def _response_type_annotation_wrapper(self, builder) -> List[str]:
281
287
  return []
282
288
 
283
- def method_signature_and_response_type_annotation(self, builder) -> str:
289
+ def method_signature_and_response_type_annotation(
290
+ self, builder, async_mode: bool, *, want_decorators: Optional[bool] = True
291
+ ) -> str:
284
292
  response_type_annotation = self._response_type_annotation(builder)
285
293
  # want pre-wrapped response type. As long as it's None, pylint will get mad about inconsistent return types
286
294
  method_signature = self._method_signature(builder, response_type_annotation)
287
295
  for wrapper in self._response_type_annotation_wrapper(builder)[::-1]:
288
296
  response_type_annotation = f"{wrapper}[{response_type_annotation}]"
289
- return self._method_signature_and_response_type_annotation_template(method_signature, response_type_annotation)
297
+ decorators = self.decorators(builder, async_mode)
298
+ decorators_str = ""
299
+ if decorators and want_decorators:
300
+ decorators_str = "\n".join(decorators) + "\n"
301
+ return (
302
+ decorators_str
303
+ + self._method_signature_and_response_type_annotation_template(
304
+ method_signature, response_type_annotation
305
+ )
306
+ )
290
307
 
291
308
  def description_and_summary(self, builder) -> List[str]:
292
309
  description_list: List[str] = []
293
- description_list.append(f"{ builder.summary.strip() if builder.summary else builder.description.strip() }")
310
+ description_list.append(
311
+ f"{ builder.summary.strip() if builder.summary else builder.description.strip() }"
312
+ )
294
313
  if builder.summary and builder.description:
295
314
  description_list.append("")
296
315
  description_list.append(builder.description.strip())
297
316
  description_list.append("")
298
317
  return description_list
299
318
 
300
- def param_description(self, builder: Union[RequestBuilder, Operation]) -> List[str]: # pylint: disable=no-self-use
319
+ def param_description( # pylint: disable=no-self-use
320
+ self, builder: Union[RequestBuilder, Operation]
321
+ ) -> List[str]:
301
322
  description_list: List[str] = []
302
- for param in [m for m in builder.parameters.method if not m.is_hidden]:
323
+ for param in [
324
+ m
325
+ for m in builder.parameters.method
326
+ if m.method_location != ParameterMethodLocation.HIDDEN_KWARG
327
+ ]:
303
328
  description_list.extend(
304
329
  f":{param.description_keyword} { param.serialized_name }: { param.description }".replace(
305
330
  "\n", "\n "
306
- ).split("\n")
331
+ ).split(
332
+ "\n"
333
+ )
307
334
  )
308
335
  description_list.append(
309
336
  f":{param.docstring_type_keyword} { param.serialized_name }: { param.docstring_type }"
@@ -311,34 +338,43 @@ class _BuilderBaseSerializer(_BuilderSerializerProtocol): # pylint: disable=abs
311
338
 
312
339
  if len(builder.parameters.content_types) > 1:
313
340
  description_list = [
314
- _content_type_docstring(builder) if l.startswith(":keyword content_type:") else l
341
+ _content_type_docstring(builder)
342
+ if l.startswith(":keyword content_type:")
343
+ else l
315
344
  for l in description_list
316
345
  ]
317
- if not any(l for l in description_list if l.startswith(":keyword content_type:")):
346
+ if not any(
347
+ l for l in description_list if l.startswith(":keyword content_type:")
348
+ ):
318
349
  description_list.append(_content_type_docstring(builder))
319
350
  return description_list
320
351
 
321
352
  def param_description_and_response_docstring(self, builder) -> List[str]:
353
+ if builder.abstract:
354
+ return []
322
355
  return self.param_description(builder) + self.response_docstring(builder)
323
356
 
324
- def _get_json_response_template_to_status_codes(self, builder) -> Dict[str, List[str]]:
357
+ def _get_json_response_template_to_status_codes(
358
+ self, builder
359
+ ) -> Dict[str, List[str]]:
325
360
  # successful status codes of responses that have bodies
326
361
  responses = [
327
362
  response
328
363
  for response in builder.responses
329
- if any(code in builder.success_status_code for code in response.status_codes)
364
+ if any(
365
+ code in builder.success_status_code for code in response.status_codes
366
+ )
330
367
  and isinstance(
331
- response.schema, (
332
- DictionarySchema,
333
- ListSchema,
334
- ObjectSchema,
335
- EnumSchema
336
- ))
368
+ response.schema,
369
+ (DictionarySchema, ListSchema, ObjectSchema, EnumSchema),
370
+ )
337
371
  ]
338
372
  retval = defaultdict(list)
339
373
  for response in responses:
340
374
  status_codes = [str(status_code) for status_code in response.status_codes]
341
- response_json = _json_dumps_template(cast(BaseSchema, response.schema).get_json_template_representation())
375
+ response_json = _json_dumps_template(
376
+ cast(BaseSchema, response.schema).get_json_template_representation()
377
+ )
342
378
  retval[response_json].extend(status_codes)
343
379
  return retval
344
380
 
@@ -347,12 +383,6 @@ class _BuilderBaseSerializer(_BuilderSerializerProtocol): # pylint: disable=abs
347
383
  if self._has_json_example_template(builder):
348
384
  template.append("")
349
385
  template += self._get_json_example_template(builder)
350
- if self._has_files_example_template(builder):
351
- template.append("")
352
- template += _get_files_example_template(builder)
353
- if self._has_data_example_template(builder):
354
- template.append("")
355
- template += _get_data_example_template(builder)
356
386
  if self._get_json_response_template_to_status_codes(builder):
357
387
  template.append("")
358
388
  template += self._get_json_response_template(builder)
@@ -369,7 +399,11 @@ class _BuilderBaseSerializer(_BuilderSerializerProtocol): # pylint: disable=abs
369
399
  discriminator_name = None
370
400
  subtype_map = None
371
401
  if subtype_map:
372
- template.append("{} = '{}'".format(discriminator_name, "' or '".join(subtype_map.values())))
402
+ template.append(
403
+ "{} = '{}'".format(
404
+ discriminator_name, "' or '".join(subtype_map.values())
405
+ )
406
+ )
373
407
  template.append("")
374
408
 
375
409
  try:
@@ -382,21 +416,30 @@ class _BuilderBaseSerializer(_BuilderSerializerProtocol): # pylint: disable=abs
382
416
  for s in self.code_model.sorted_schemas
383
417
  if s.name in property_with_discriminator.schema.subtype_map.values()
384
418
  ]
385
- num_schemas = min(self.code_model.options["polymorphic_examples"], len(polymorphic_schemas))
419
+ num_schemas = min(
420
+ self.code_model.options["polymorphic_examples"],
421
+ len(polymorphic_schemas),
422
+ )
386
423
  for i in range(num_schemas):
387
424
  schema = polymorphic_schemas[i]
388
425
  polymorphic_property = _json_dumps_template(
389
426
  schema.get_json_template_representation(),
390
427
  )
391
- template.extend(f"{property_with_discriminator.name} = {polymorphic_property}".splitlines())
428
+ template.extend(
429
+ f"{property_with_discriminator.name} = {polymorphic_property}".splitlines()
430
+ )
392
431
  if i != num_schemas - 1:
393
432
  template.append("# OR")
394
433
  template.append("")
395
- template.append("# JSON input template you can fill out and use as your body input.")
434
+ template.append(
435
+ "# JSON input template you can fill out and use as your body input."
436
+ )
396
437
  json_template = _json_dumps_template(
397
438
  builder.parameters.json_body.get_json_template_representation(),
398
439
  )
399
- template.extend(f"{self._json_example_param_name(builder)} = {json_template}".splitlines())
440
+ template.extend(
441
+ f"{self._json_example_param_name(builder)} = {json_template}".splitlines()
442
+ )
400
443
  return template
401
444
 
402
445
  @property
@@ -404,28 +447,31 @@ class _BuilderBaseSerializer(_BuilderSerializerProtocol): # pylint: disable=abs
404
447
  def serializer_name(self) -> str:
405
448
  ...
406
449
 
407
- def _serialize_parameter(
408
- self, param: Parameter, kwarg_name: str
409
- ) -> List[str]:
450
+ def _serialize_parameter(self, param: Parameter, kwarg_name: str) -> List[str]:
410
451
  function_name = "header" if kwarg_name == "headers" else "query"
411
452
  set_parameter = "_{}['{}'] = {}".format(
412
453
  kwarg_name,
413
454
  param.rest_api_name,
414
- utils.build_serialize_data_call(param, function_name, self.serializer_name)
455
+ utils.build_serialize_data_call(param, function_name, self.serializer_name),
415
456
  )
416
457
  if param.required:
417
458
  retval = [set_parameter]
418
459
  else:
419
460
  retval = [
420
461
  f"if {param.full_serialized_name} is not None:",
421
- f" {set_parameter}"
462
+ f" {set_parameter}",
422
463
  ]
423
464
  return retval
424
465
 
425
466
  def _get_json_response_template(self, builder) -> List[str]:
426
467
  template = []
427
- for response_body, status_codes in self._get_json_response_template_to_status_codes(builder).items():
428
- template.append("# response body for status code(s): {}".format(", ".join(status_codes)))
468
+ for (
469
+ response_body,
470
+ status_codes,
471
+ ) in self._get_json_response_template_to_status_codes(builder).items():
472
+ template.append(
473
+ "# response body for status code(s): {}".format(", ".join(status_codes))
474
+ )
429
475
  template.extend(f"response.json() == {response_body}".splitlines())
430
476
  return template
431
477
 
@@ -440,7 +486,9 @@ class _BuilderBaseSerializer(_BuilderSerializerProtocol): # pylint: disable=abs
440
486
  ############################## REQUEST BUILDERS ##############################
441
487
 
442
488
 
443
- class _RequestBuilderBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstract-method
489
+ class _RequestBuilderBaseSerializer(
490
+ _BuilderBaseSerializer
491
+ ): # pylint: disable=abstract-method
444
492
  def description_and_summary(self, builder) -> List[str]:
445
493
  retval = super().description_and_summary(builder)
446
494
  retval += [
@@ -458,18 +506,25 @@ class _RequestBuilderBaseSerializer(_BuilderBaseSerializer): # pylint: disable=
458
506
  def declare_non_inputtable_constants(builder) -> List[str]:
459
507
  def _get_value(param: Parameter):
460
508
  if param.location in [ParameterLocation.Header, ParameterLocation.Query]:
461
- kwarg_dict = "headers" if param.location == ParameterLocation.Header else "params"
509
+ kwarg_dict = (
510
+ "headers"
511
+ if param.location == ParameterLocation.Header
512
+ else "params"
513
+ )
462
514
  return f"_{kwarg_dict}.pop('{param.rest_api_name}', {param.constant_declaration})"
463
515
  return f"{param.constant_declaration}"
516
+
464
517
  return [
465
518
  f"{p.serialized_name} = {_get_value(p)}"
466
519
  for p in builder.parameters.constant
467
- if p.original_parameter is None and
468
- p.in_method_code and
469
- not p.in_method_signature
520
+ if p.original_parameter is None
521
+ and p.in_method_code
522
+ and not p.in_method_signature
470
523
  ]
471
524
 
472
525
  def want_example_template(self, builder) -> bool:
526
+ if builder.abstract:
527
+ return False
473
528
  if self.code_model.options["builders_visibility"] != "public":
474
529
  return False # if we're not exposing rest layer, don't need to generate
475
530
  if builder.parameters.has_body:
@@ -485,7 +540,9 @@ class _RequestBuilderBaseSerializer(_BuilderBaseSerializer): # pylint: disable=
485
540
  def _is_in_class(self) -> bool:
486
541
  return False
487
542
 
488
- def _response_type_annotation(self, builder, modify_if_head_as_boolean: bool = True) -> str:
543
+ def _response_type_annotation(
544
+ self, builder, modify_if_head_as_boolean: bool = True
545
+ ) -> str:
489
546
  return "HttpRequest"
490
547
 
491
548
  def response_docstring(self, builder) -> List[str]:
@@ -503,12 +560,6 @@ class _RequestBuilderBaseSerializer(_BuilderBaseSerializer): # pylint: disable=
503
560
  def _has_json_example_template(self, builder) -> bool:
504
561
  return "json" in builder.parameters.body_kwarg_names
505
562
 
506
- def _has_files_example_template(self, builder) -> bool:
507
- return "files" in builder.parameters.body_kwarg_names
508
-
509
- def _has_data_example_template(self, builder) -> bool:
510
- return "data" in builder.parameters.body_kwarg_names
511
-
512
563
  @abstractmethod
513
564
  def _body_params_to_pass_to_request_creation(self, builder) -> List[str]:
514
565
  ...
@@ -517,10 +568,12 @@ class _RequestBuilderBaseSerializer(_BuilderBaseSerializer): # pylint: disable=
517
568
  return utils.pop_kwargs_from_signature(
518
569
  self._get_kwargs_to_pop(builder),
519
570
  check_kwarg_dict=True,
520
- pop_headers_kwarg=utils.PopKwargType.CASE_INSENSITIVE if bool(builder.parameters.headers)
521
- else utils.PopKwargType.NO,
522
- pop_params_kwarg=utils.PopKwargType.CASE_INSENSITIVE if bool(builder.parameters.query)
523
- else utils.PopKwargType.NO,
571
+ pop_headers_kwarg=utils.PopKwargType.CASE_INSENSITIVE
572
+ if bool(builder.parameters.headers)
573
+ else utils.PopKwargType.NO,
574
+ pop_params_kwarg=utils.PopKwargType.CASE_INSENSITIVE
575
+ if bool(builder.parameters.query)
576
+ else utils.PopKwargType.NO,
524
577
  )
525
578
 
526
579
  def create_http_request(self, builder) -> List[str]:
@@ -532,10 +585,14 @@ class _RequestBuilderBaseSerializer(_BuilderBaseSerializer): # pylint: disable=
532
585
  if builder.parameters.headers:
533
586
  retval.append(" headers=_headers,")
534
587
  if builder.parameters.has_body:
535
- retval.extend([
536
- f" {body_kwarg}={body_kwarg},"
537
- for body_kwarg in self._body_params_to_pass_to_request_creation(builder)
538
- ])
588
+ retval.extend(
589
+ [
590
+ f" {body_kwarg}={body_kwarg},"
591
+ for body_kwarg in self._body_params_to_pass_to_request_creation(
592
+ builder
593
+ )
594
+ ]
595
+ )
539
596
  retval.append(" **kwargs")
540
597
  retval.append(")")
541
598
  return retval
@@ -543,44 +600,61 @@ class _RequestBuilderBaseSerializer(_BuilderBaseSerializer): # pylint: disable=
543
600
  def serialize_headers(self, builder) -> List[str]:
544
601
  retval = ["# Construct headers"]
545
602
  for parameter in builder.parameters.headers:
546
- retval.extend(self._serialize_parameter(
547
- parameter,
548
- kwarg_name="headers",
549
- ))
603
+ retval.extend(
604
+ self._serialize_parameter(
605
+ parameter,
606
+ kwarg_name="headers",
607
+ )
608
+ )
550
609
  return retval
551
610
 
552
611
  def serialize_query(self, builder) -> List[str]:
553
612
  retval = ["# Construct parameters"]
554
613
  for parameter in builder.parameters.query:
555
- retval.extend(self._serialize_parameter(
556
- parameter,
557
- kwarg_name="params",
558
- ))
614
+ retval.extend(
615
+ self._serialize_parameter(
616
+ parameter,
617
+ kwarg_name="params",
618
+ )
619
+ )
559
620
  return retval
560
621
 
561
622
  def construct_url(self, builder) -> str:
562
- if any(o for o in ["low_level_client", "version_tolerant"] if self.code_model.options.get(o)):
623
+ if any(
624
+ o
625
+ for o in ["low_level_client", "version_tolerant"]
626
+ if self.code_model.options.get(o)
627
+ ):
563
628
  url_value = _escape_str(builder.url)
564
629
  else:
565
630
  url_value = f'kwargs.pop("template_url", {_escape_str(builder.url)})'
566
631
  return f"_url = {url_value}{' # pylint: disable=line-too-long' if len(url_value) > 114 else ''}"
567
632
 
633
+
568
634
  class RequestBuilderGenericSerializer(_RequestBuilderBaseSerializer):
569
635
  @property
570
636
  def _want_inline_type_hints(self) -> bool:
571
637
  return False
572
638
 
573
639
  @staticmethod
574
- def _method_signature_and_response_type_annotation_template(method_signature: str, response_type_annotation: str):
640
+ def _method_signature_and_response_type_annotation_template(
641
+ method_signature: str, response_type_annotation: str
642
+ ):
575
643
  return utils.method_signature_and_response_type_annotation_template(
576
- is_python3_file=False, method_signature=method_signature, response_type_annotation=response_type_annotation
644
+ is_python3_file=False,
645
+ method_signature=method_signature,
646
+ response_type_annotation=response_type_annotation,
577
647
  )
578
648
 
579
649
  def _get_kwargs_to_pop(self, builder):
580
650
  return builder.parameters.kwargs_to_pop(is_python3_file=False)
581
651
 
582
652
  def _body_params_to_pass_to_request_creation(self, builder) -> List[str]:
583
- if builder.parameters.has_body and not builder.parameters.body_kwarg_names:
653
+ if any(
654
+ b
655
+ for b in builder.parameters.body
656
+ if b.constant and not (b.is_data_input or b.is_multipart)
657
+ ):
584
658
  # this means we have a constant body
585
659
  # only doing json body in this case
586
660
  return ["json"]
@@ -593,9 +667,13 @@ class RequestBuilderPython3Serializer(_RequestBuilderBaseSerializer):
593
667
  return True
594
668
 
595
669
  @staticmethod
596
- def _method_signature_and_response_type_annotation_template(method_signature: str, response_type_annotation: str):
670
+ def _method_signature_and_response_type_annotation_template(
671
+ method_signature: str, response_type_annotation: str
672
+ ):
597
673
  return utils.method_signature_and_response_type_annotation_template(
598
- is_python3_file=True, method_signature=method_signature, response_type_annotation=response_type_annotation
674
+ is_python3_file=True,
675
+ method_signature=method_signature,
676
+ response_type_annotation=response_type_annotation,
599
677
  )
600
678
 
601
679
  def _get_kwargs_to_pop(self, builder):
@@ -605,9 +683,11 @@ class RequestBuilderPython3Serializer(_RequestBuilderBaseSerializer):
605
683
  body_kwargs = list(builder.parameters.body_kwarg_names.keys())
606
684
  if body_kwargs:
607
685
  return body_kwargs
608
- if builder.parameters.has_body:
609
- # this means we have a constant body
610
- # only doing json body in this case
686
+ if any(
687
+ b
688
+ for b in builder.parameters.body
689
+ if b.constant and not (b.is_data_input or b.is_multipart)
690
+ ):
611
691
  return ["json"]
612
692
  return body_kwargs
613
693
 
@@ -615,7 +695,9 @@ class RequestBuilderPython3Serializer(_RequestBuilderBaseSerializer):
615
695
  ############################## NORMAL OPERATIONS ##############################
616
696
 
617
697
 
618
- class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstract-method
698
+ class _OperationBaseSerializer(
699
+ _BuilderBaseSerializer
700
+ ): # pylint: disable=abstract-method
619
701
  def description_and_summary(self, builder) -> List[str]:
620
702
  retval = super().description_and_summary(builder)
621
703
  if builder.deprecated:
@@ -632,7 +714,16 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
632
714
  def serializer_name(self) -> str:
633
715
  return "self._serialize"
634
716
 
635
- def _response_docstring_type_wrapper(self, builder) -> List[str]: # pylint: disable=unused-argument, no-self-use
717
+ def decorators(self, builder, async_mode: bool) -> List[str]:
718
+ """Decorators for the method"""
719
+ super_decorators = super().decorators(builder, async_mode)
720
+ if builder.abstract:
721
+ super_decorators.append("@abc.abstractmethod")
722
+ return super_decorators
723
+
724
+ def _response_docstring_type_wrapper( # pylint: disable=unused-argument, no-self-use
725
+ self, builder
726
+ ) -> List[str]:
636
727
  return []
637
728
 
638
729
  def param_description(self, builder) -> List[str]: # pylint: disable=no-self-use
@@ -649,7 +740,9 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
649
740
  retval = f"{wrapper}[{retval}]"
650
741
  return retval
651
742
 
652
- def _response_type_annotation(self, builder, modify_if_head_as_boolean: bool = True) -> str:
743
+ def _response_type_annotation(
744
+ self, builder, modify_if_head_as_boolean: bool = True
745
+ ) -> str:
653
746
  if (
654
747
  modify_if_head_as_boolean
655
748
  and builder.request_builder.method.lower() == "head"
@@ -658,7 +751,9 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
658
751
  return "bool"
659
752
  response_body_annotations: OrderedSet[str] = {}
660
753
  for response in [r for r in builder.responses if r.has_body]:
661
- response_body_annotations[response.type_annotation(is_operation_file=True)] = None
754
+ response_body_annotations[
755
+ response.type_annotation(is_operation_file=True)
756
+ ] = None
662
757
  response_str = ", ".join(response_body_annotations.keys()) or "None"
663
758
  if len(response_body_annotations) > 1:
664
759
  response_str = f"Union[{response_str}]"
@@ -671,24 +766,37 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
671
766
  kwargs = utils.pop_kwargs_from_signature(
672
767
  kwargs_to_pop,
673
768
  check_kwarg_dict=True,
674
- pop_headers_kwarg=utils.PopKwargType.CASE_INSENSITIVE if builder.has_kwargs_to_pop_with_default(
675
- kwargs_to_pop, ParameterLocation.Header) else utils.PopKwargType.SIMPLE,
676
- pop_params_kwarg=utils.PopKwargType.CASE_INSENSITIVE if builder.has_kwargs_to_pop_with_default(
677
- kwargs_to_pop, ParameterLocation.Query) else utils.PopKwargType.SIMPLE,
769
+ pop_headers_kwarg=utils.PopKwargType.CASE_INSENSITIVE
770
+ if builder.has_kwargs_to_pop_with_default(
771
+ kwargs_to_pop, ParameterLocation.Header
772
+ )
773
+ else utils.PopKwargType.SIMPLE,
774
+ pop_params_kwarg=utils.PopKwargType.CASE_INSENSITIVE
775
+ if builder.has_kwargs_to_pop_with_default(
776
+ kwargs_to_pop, ParameterLocation.Query
777
+ )
778
+ else utils.PopKwargType.SIMPLE,
779
+ )
780
+ kwargs.append(
781
+ f"cls = kwargs.pop('cls', None) {self.cls_type_annotation(builder)}"
678
782
  )
679
- kwargs.append(f"cls = kwargs.pop('cls', None) {self.cls_type_annotation(builder)}")
680
783
  return kwargs
681
784
 
682
785
  def cls_type_annotation(self, builder) -> str:
683
786
  return f"# type: ClsType[{self._response_type_annotation(builder, modify_if_head_as_boolean=False)}]"
684
787
 
685
- def _response_docstring_text_template(self, builder) -> str: # pylint: disable=no-self-use, unused-argument
788
+ def _response_docstring_text_template( # pylint: disable=no-self-use, unused-argument
789
+ self, builder
790
+ ) -> str:
686
791
  cls_str = f",{self._cls_docstring_rtype}" if self._cls_docstring_rtype else ""
687
792
  return "{}" + cls_str
688
793
 
689
794
  def response_docstring(self, builder) -> List[str]:
690
795
  responses_with_body = [r for r in builder.responses if r.has_body]
691
- if builder.request_builder.method.lower() == "head" and self.code_model.options["head_as_boolean"]:
796
+ if (
797
+ builder.request_builder.method.lower() == "head"
798
+ and self.code_model.options["head_as_boolean"]
799
+ ):
692
800
  response_docstring_text = "bool"
693
801
  rtype = "bool"
694
802
  elif responses_with_body:
@@ -706,36 +814,46 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
706
814
  response_docstring_text = "None"
707
815
  rtype = "None"
708
816
  response_str = f":return: {self._response_docstring_text_template(builder).format(response_docstring_text)}"
709
- rtype_str = f":rtype: {self._response_docstring_type_template(builder).format(rtype)}"
710
- return [response_str, rtype_str, ":raises: ~azure.core.exceptions.HttpResponseError"]
817
+ rtype_str = (
818
+ f":rtype: {self._response_docstring_type_template(builder).format(rtype)}"
819
+ )
820
+ return [
821
+ response_str,
822
+ rtype_str,
823
+ ":raises: ~azure.core.exceptions.HttpResponseError",
824
+ ]
711
825
 
712
826
  def want_example_template(self, builder) -> bool:
713
- if self.code_model.options['models_mode']:
827
+ if builder.abstract:
828
+ return False
829
+ if self.code_model.options["models_mode"]:
714
830
  return False
715
831
  if builder.parameters.has_body:
716
- if builder.parameters.multipart or builder.parameters.data_inputs:
717
- return True
718
832
  body_params = builder.parameters.body
719
- return any([b for b in body_params if isinstance(b.schema, (DictionarySchema, ListSchema, ObjectSchema))])
833
+ return any(
834
+ [
835
+ b
836
+ for b in body_params
837
+ if isinstance(
838
+ b.schema, (DictionarySchema, ListSchema, ObjectSchema)
839
+ )
840
+ ]
841
+ )
720
842
  return bool(self._get_json_response_template_to_status_codes(builder))
721
843
 
722
844
  def _json_example_param_name(self, builder) -> str:
723
845
  return builder.parameters.body[0].serialized_name
724
846
 
725
847
  def _has_json_example_template(self, builder) -> bool:
726
- return (
727
- builder.parameters.has_body and
728
- not (builder.parameters.multipart or builder.parameters.data_inputs)
729
- )
730
-
731
- def _has_files_example_template(self, builder) -> bool:
732
- return bool(builder.parameters.multipart)
733
-
734
- def _has_data_example_template(self, builder) -> bool:
735
- return bool(builder.parameters.data_inputs)
848
+ return builder.parameters.has_body
736
849
 
737
850
  def _serialize_body_call(
738
- self, builder, body_param: Parameter, send_xml: bool, ser_ctxt: Optional[str], ser_ctxt_name: str
851
+ self,
852
+ builder,
853
+ body_param: Parameter,
854
+ send_xml: bool,
855
+ ser_ctxt: Optional[str],
856
+ ser_ctxt_name: str,
739
857
  ) -> str:
740
858
  body_is_xml = ", is_xml=True" if send_xml else ""
741
859
  pass_ser_ctxt = f", {ser_ctxt_name}={ser_ctxt_name}" if ser_ctxt else ""
@@ -747,15 +865,19 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
747
865
  )
748
866
  return f"_{body_kwarg_to_pass} = {body_param.serialized_name}"
749
867
 
750
- def _serialize_body(self, builder, body_param: Parameter, body_kwarg: str) -> List[str]:
868
+ def _serialize_body(
869
+ self, builder, body_param: Parameter, body_kwarg: str
870
+ ) -> List[str]:
751
871
  retval = []
752
872
  send_xml = bool(
753
- builder.parameters.has_body and
754
- any(["xml" in ct for ct in builder.parameters.content_types]) and
755
- not isinstance(body_param.schema, IOSchema)
873
+ builder.parameters.has_body
874
+ and any(["xml" in ct for ct in builder.parameters.content_types])
875
+ and not isinstance(body_param.schema, IOSchema)
756
876
  )
757
877
  ser_ctxt_name = "serialization_ctxt"
758
- ser_ctxt = builder.parameters.body[0].xml_serialization_ctxt if send_xml else None
878
+ ser_ctxt = (
879
+ builder.parameters.body[0].xml_serialization_ctxt if send_xml else None
880
+ )
759
881
  if ser_ctxt and self.code_model.options["models_mode"]:
760
882
  retval.append(f'{ser_ctxt_name} = {{"xml": {{{ser_ctxt}}}}}')
761
883
  serialize_body_call = self._serialize_body_call(
@@ -779,25 +901,31 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
779
901
  self, builder, body_param: Parameter, body_kwarg: Parameter
780
902
  ) -> List[str]:
781
903
  retval: List[str] = []
782
- if body_kwarg.serialized_name == "data" or body_kwarg.serialized_name == "files":
904
+ if (
905
+ body_kwarg.serialized_name == "data"
906
+ or body_kwarg.serialized_name == "files"
907
+ ):
783
908
  return retval
784
909
  try:
785
910
  if not body_param.style == ParameterStyle.binary:
786
- retval.extend(self._serialize_body(builder, body_param, body_kwarg.serialized_name))
911
+ retval.extend(
912
+ self._serialize_body(
913
+ builder, body_param, body_kwarg.serialized_name
914
+ )
915
+ )
787
916
  return retval
788
917
  except AttributeError:
789
918
  pass
790
919
  retval.append(f"_{body_kwarg.serialized_name} = {body_param.serialized_name}")
791
920
  return retval
792
921
 
793
-
794
922
  def _serialize_body_parameters(
795
- self, builder,
923
+ self,
924
+ builder,
796
925
  ) -> List[str]:
797
926
  retval = []
798
927
  body_kwargs = [
799
- p for p in builder.request_builder.parameters.body
800
- if p.content_types
928
+ p for p in builder.request_builder.parameters.body if p.content_types
801
929
  ]
802
930
  builder_params = []
803
931
  if builder.parameters.has_body:
@@ -805,24 +933,34 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
805
933
  if builder.multiple_content_type_parameters.has_body:
806
934
  builder_params += builder.multiple_content_type_parameters.body
807
935
  if len(body_kwargs) == 1:
808
- retval.extend(self._set_body_content_kwarg(builder, builder.parameters.body[0], body_kwargs[0]))
936
+ retval.extend(
937
+ self._set_body_content_kwarg(
938
+ builder, builder.parameters.body[0], body_kwargs[0]
939
+ )
940
+ )
809
941
  else:
810
942
  retval.append('content_type = content_type or ""')
811
943
  for idx, body_kwarg in enumerate(body_kwargs):
812
944
  body_param = next(
813
- b for b in builder_params
814
- if body_kwarg in b.body_kwargs
945
+ b for b in builder_params if body_kwarg in b.body_kwargs
815
946
  )
816
947
  if_statement = "if" if idx == 0 else "elif"
817
948
  retval.append(
818
949
  f'{if_statement} content_type.split(";")[0] in {body_kwarg.pre_semicolon_content_types}:'
819
950
  )
820
- retval.extend([" " + line for line in self._set_body_content_kwarg(builder, body_param, body_kwarg)])
951
+ retval.extend(
952
+ [
953
+ " " + line
954
+ for line in self._set_body_content_kwarg(
955
+ builder, body_param, body_kwarg
956
+ )
957
+ ]
958
+ )
821
959
  retval.extend(_content_type_error_check(builder))
822
960
 
823
961
  return retval
824
962
 
825
- def _call_request_builder_helper(
963
+ def _call_request_builder_helper( # pylint: disable=too-many-statements
826
964
  self,
827
965
  builder,
828
966
  request_builder: RequestBuilder,
@@ -834,7 +972,9 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
834
972
  # special case for files, bc we hardcode body param to be called 'files' for multipart
835
973
  body_params_to_initialize = builder.body_kwargs_to_pass_to_request_builder
836
974
  if self.code_model.options["version_tolerant"]:
837
- body_params_to_initialize = [p for p in body_params_to_initialize if p != "files"]
975
+ body_params_to_initialize = [
976
+ p for p in body_params_to_initialize if p != "files"
977
+ ]
838
978
  for k in body_params_to_initialize:
839
979
  retval.append(f"_{k} = None")
840
980
  if builder.parameters.grouped:
@@ -856,38 +996,46 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
856
996
  else:
857
997
  builder_group_name = request_builder.builder_group_name
858
998
  request_path_name = "rest{}.{}".format(
859
- ("_" + builder_group_name) if builder_group_name else "", request_builder.name
999
+ ("_" + builder_group_name) if builder_group_name else "",
1000
+ request_builder.name,
860
1001
  )
861
1002
  retval.append("")
862
1003
  retval.append(f"request = {request_path_name}(")
863
1004
  for parameter in request_builder.parameters.method:
864
1005
  if (
865
- parameter.is_body and
866
- not parameter.constant and
867
- parameter.serialized_name not in builder.body_kwargs_to_pass_to_request_builder
1006
+ parameter.is_body
1007
+ and not parameter.constant
1008
+ and parameter.serialized_name
1009
+ not in builder.body_kwargs_to_pass_to_request_builder
868
1010
  ):
869
1011
  continue
870
1012
  if (
871
- is_next_request and
872
- not bool(builder.next_request_builder) and
873
- not self.code_model.options["reformat_next_link"] and
874
- parameter.location == ParameterLocation.Query
1013
+ is_next_request
1014
+ and not bool(builder.next_request_builder)
1015
+ and not self.code_model.options["reformat_next_link"]
1016
+ and parameter.location == ParameterLocation.Query
875
1017
  ):
876
1018
  # if we don't want to reformat query parameters for next link calls
877
1019
  # in paging operations with a single swagger operation defintion,
878
1020
  # we skip passing query params when building the next request
879
1021
  continue
880
- high_level_name = cast(RequestBuilderParameter, parameter).name_in_high_level_operation
1022
+ high_level_name = cast(
1023
+ RequestBuilderParameter, parameter
1024
+ ).name_in_high_level_operation
881
1025
  retval.append(f" {parameter.serialized_name}={high_level_name},")
882
1026
  if not self.code_model.options["version_tolerant"]:
1027
+ if builder.parameters.multipart:
1028
+ retval.append(f" files=_files,")
1029
+ if builder.parameters.data_inputs:
1030
+ retval.append(f" data=_data,")
883
1031
  template_url = template_url or f"self.{builder.name}.metadata['url']"
884
1032
  retval.append(f" template_url={template_url},")
885
- retval.append(' headers=_headers,')
886
- retval.append(' params=_params,')
1033
+ retval.append(" headers=_headers,")
1034
+ retval.append(" params=_params,")
887
1035
  retval.append(f")")
888
1036
  if not self.code_model.options["version_tolerant"]:
889
1037
  pass_files = ""
890
- if "files" in builder.body_kwargs_to_pass_to_request_builder:
1038
+ if builder.parameters.multipart:
891
1039
  pass_files = ", _files"
892
1040
  retval.append(f"request = _convert_request(request{pass_files})")
893
1041
  if builder.parameters.path:
@@ -898,7 +1046,7 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
898
1046
  retval.append(
899
1047
  "request.url = self._client.format_url({}{}) # type: ignore".format(
900
1048
  url_to_format,
901
- ", **path_format_arguments" if builder.parameters.path else ""
1049
+ ", **path_format_arguments" if builder.parameters.path else "",
902
1050
  )
903
1051
  )
904
1052
  return retval
@@ -922,16 +1070,21 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
922
1070
  if response.is_stream_response:
923
1071
  retval.append(
924
1072
  "deserialized = {}".format(
925
- "response" if self.code_model.options["version_tolerant"]
1073
+ "response"
1074
+ if self.code_model.options["version_tolerant"]
926
1075
  else "response.stream_download(self._client._pipeline)"
927
1076
  )
928
1077
  )
929
1078
  elif response.has_body:
930
1079
  if self.code_model.options["models_mode"]:
931
- retval.append(f"deserialized = self._deserialize('{response.serialization_type}', pipeline_response)")
1080
+ retval.append(
1081
+ f"deserialized = self._deserialize('{response.serialization_type}', pipeline_response)"
1082
+ )
932
1083
  else:
933
1084
  is_xml = any(["xml" in ct for ct in response.content_types])
934
- deserialized_value = "ET.fromstring(response.text())" if is_xml else "response.json()"
1085
+ deserialized_value = (
1086
+ "ET.fromstring(response.text())" if is_xml else "response.json()"
1087
+ )
935
1088
  retval.append(f"if response.content:")
936
1089
  retval.append(f" deserialized = {deserialized_value}")
937
1090
  retval.append("else:")
@@ -945,17 +1098,23 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
945
1098
 
946
1099
  def handle_error_response(self, builder) -> List[str]:
947
1100
  retval = [f"if response.status_code not in {str(builder.success_status_code)}:"]
948
- retval.append(" map_error(status_code=response.status_code, response=response, error_map=error_map)")
1101
+ retval.append(
1102
+ " map_error(status_code=response.status_code, response=response, error_map=error_map)"
1103
+ )
949
1104
  error_model = ""
950
1105
  if builder.default_exception and self.code_model.options["models_mode"]:
951
1106
  retval.append(
952
1107
  f" error = self._deserialize.failsafe_deserialize({builder.default_exception}, pipeline_response)"
953
1108
  )
954
1109
  error_model = ", model=error"
955
- retval.append(" raise HttpResponseError(response=response{}{})".format(
956
- error_model,
957
- ", error_format=ARMErrorFormat" if self.code_model.options['azure_arm'] else ""
958
- ))
1110
+ retval.append(
1111
+ " raise HttpResponseError(response=response{}{})".format(
1112
+ error_model,
1113
+ ", error_format=ARMErrorFormat"
1114
+ if self.code_model.options["azure_arm"]
1115
+ else "",
1116
+ )
1117
+ )
959
1118
  return retval
960
1119
 
961
1120
  def handle_response(self, builder) -> List[str]:
@@ -973,29 +1132,40 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
973
1132
  response = builder.get_response_from_status(status_code)
974
1133
  if response.headers or response.has_body:
975
1134
  retval.append(f"if response.status_code == {status_code}:")
976
- retval.extend([
977
- f" {line}"
978
- for line in self.response_headers_and_deserialization(response)
979
- ])
1135
+ retval.extend(
1136
+ [
1137
+ f" {line}"
1138
+ for line in self.response_headers_and_deserialization(
1139
+ response
1140
+ )
1141
+ ]
1142
+ )
980
1143
  retval.append("")
981
1144
  else:
982
- retval.extend(self.response_headers_and_deserialization(
983
- builder.responses[0]
984
- ))
1145
+ retval.extend(
1146
+ self.response_headers_and_deserialization(builder.responses[0])
1147
+ )
985
1148
  retval.append("")
986
1149
  if builder.has_optional_return_type or self.code_model.options["models_mode"]:
987
1150
  deserialized = "deserialized"
988
1151
  else:
989
- deserialized = f"cast({self._response_type_annotation(builder)}, deserialized)"
1152
+ deserialized = (
1153
+ f"cast({self._response_type_annotation(builder)}, deserialized)"
1154
+ )
990
1155
  retval.append("if cls:")
991
- retval.append(" return cls(pipeline_response, {}, {})".format(
992
- deserialized if builder.has_response_body else "None",
993
- "response_headers" if builder.any_response_has_headers else '{}'
994
- ))
1156
+ retval.append(
1157
+ " return cls(pipeline_response, {}, {})".format(
1158
+ deserialized if builder.has_response_body else "None",
1159
+ "response_headers" if builder.any_response_has_headers else "{}",
1160
+ )
1161
+ )
995
1162
  if builder.has_response_body:
996
1163
  retval.append("")
997
1164
  retval.append(f"return {deserialized}")
998
- if builder.request_builder.method == 'HEAD' and self.code_model.options['head_as_boolean']:
1165
+ if (
1166
+ builder.request_builder.method == "HEAD"
1167
+ and self.code_model.options["head_as_boolean"]
1168
+ ):
999
1169
  retval.append("return 200 <= response.status_code <= 299")
1000
1170
  return retval
1001
1171
 
@@ -1016,7 +1186,11 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
1016
1186
  and self.code_model.options["models_mode"]
1017
1187
  ):
1018
1188
  error_model_str = f", model=self._deserialize(_models.{excep.serialization_type}, response)"
1019
- error_format_str = ", error_format=ARMErrorFormat" if self.code_model.options['azure_arm'] else ""
1189
+ error_format_str = (
1190
+ ", error_format=ARMErrorFormat"
1191
+ if self.code_model.options["azure_arm"]
1192
+ else ""
1193
+ )
1020
1194
  for status_code in excep.status_codes:
1021
1195
  if status_code == 401:
1022
1196
  retval.append(
@@ -1041,7 +1215,9 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
1041
1215
  f"{error_model_str}{error_format_str}),"
1042
1216
  )
1043
1217
  else:
1044
- retval.append(" 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError")
1218
+ retval.append(
1219
+ " 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError"
1220
+ )
1045
1221
  retval.append("}")
1046
1222
  retval.append("error_map.update(kwargs.pop('error_map', {}) or {})")
1047
1223
  return retval
@@ -1051,7 +1227,10 @@ class _OperationBaseSerializer(_BuilderBaseSerializer): # pylint: disable=abstr
1051
1227
  url = _escape_str(builder.request_builder.url)
1052
1228
  return f"{builder.python_name}.metadata = {{'url': { url }}} # type: ignore"
1053
1229
 
1054
- class _SyncOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable=abstract-method
1230
+
1231
+ class _SyncOperationBaseSerializer(
1232
+ _OperationBaseSerializer
1233
+ ): # pylint: disable=abstract-method
1055
1234
  @property
1056
1235
  def _want_inline_type_hints(self) -> bool:
1057
1236
  return False
@@ -1064,15 +1243,20 @@ class _SyncOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable
1064
1243
  def _call_method(self) -> str:
1065
1244
  return ""
1066
1245
 
1246
+
1067
1247
  class SyncOperationGenericSerializer(_SyncOperationBaseSerializer):
1068
1248
  @property
1069
1249
  def _want_inline_type_hints(self) -> bool:
1070
1250
  return False
1071
1251
 
1072
1252
  @staticmethod
1073
- def _method_signature_and_response_type_annotation_template(method_signature: str, response_type_annotation: str):
1253
+ def _method_signature_and_response_type_annotation_template(
1254
+ method_signature: str, response_type_annotation: str
1255
+ ):
1074
1256
  return utils.method_signature_and_response_type_annotation_template(
1075
- is_python3_file=False, method_signature=method_signature, response_type_annotation=response_type_annotation
1257
+ is_python3_file=False,
1258
+ method_signature=method_signature,
1259
+ response_type_annotation=response_type_annotation,
1076
1260
  )
1077
1261
 
1078
1262
  def _get_kwargs_to_pop(self, builder):
@@ -1085,16 +1269,20 @@ class SyncOperationPython3Serializer(_SyncOperationBaseSerializer):
1085
1269
  return True
1086
1270
 
1087
1271
  @staticmethod
1088
- def _method_signature_and_response_type_annotation_template(method_signature: str, response_type_annotation: str):
1272
+ def _method_signature_and_response_type_annotation_template(
1273
+ method_signature: str, response_type_annotation: str
1274
+ ):
1089
1275
  return utils.method_signature_and_response_type_annotation_template(
1090
- is_python3_file=True, method_signature=method_signature, response_type_annotation=response_type_annotation
1276
+ is_python3_file=True,
1277
+ method_signature=method_signature,
1278
+ response_type_annotation=response_type_annotation,
1091
1279
  )
1092
1280
 
1093
1281
  def _get_kwargs_to_pop(self, builder):
1094
1282
  return builder.parameters.kwargs_to_pop(is_python3_file=True)
1095
1283
 
1096
- class AsyncOperationSerializer(SyncOperationPython3Serializer):
1097
1284
 
1285
+ class AsyncOperationSerializer(SyncOperationPython3Serializer):
1098
1286
  @property
1099
1287
  def _def(self) -> str:
1100
1288
  return "async def"
@@ -1111,55 +1299,66 @@ class AsyncOperationSerializer(SyncOperationPython3Serializer):
1111
1299
  ############################## PAGING OPERATIONS ##############################
1112
1300
 
1113
1301
 
1114
- class _PagingOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable=abstract-method
1115
- def _response_docstring_text_template(self, builder) -> str: # pylint: disable=no-self-use, unused-argument
1302
+ class _PagingOperationBaseSerializer(
1303
+ _OperationBaseSerializer
1304
+ ): # pylint: disable=abstract-method
1305
+ def _response_docstring_text_template(
1306
+ self, builder
1307
+ ) -> str: # pylint: disable=no-self-use, unused-argument
1116
1308
  if self._cls_docstring_rtype:
1117
1309
  return "An iterator like instance of either {}" + self._cls_docstring_rtype
1118
1310
  return "An iterator like instance of {}"
1119
1311
 
1120
1312
  def cls_type_annotation(self, builder) -> str:
1121
- interior = super()._response_type_annotation(builder, modify_if_head_as_boolean=False)
1313
+ interior = super()._response_type_annotation(
1314
+ builder, modify_if_head_as_boolean=False
1315
+ )
1122
1316
  return f"# type: ClsType[{interior}]"
1123
1317
 
1318
+ def decorators(self, builder, async_mode: bool) -> List[str]:
1319
+ """Decorators for the method"""
1320
+ retval: List[str] = []
1321
+ if self.code_model.options["tracing"] and builder.want_tracing:
1322
+ retval.append("@distributed_trace")
1323
+ if builder.abstract:
1324
+ retval.append("@abc.abstractmethod")
1325
+ return retval
1326
+
1124
1327
  def call_next_link_request_builder(self, builder) -> List[str]:
1125
1328
  if builder.next_request_builder:
1126
1329
  request_builder = builder.next_request_builder
1127
- template_url = None if self.code_model.options["version_tolerant"] else f"'{request_builder.url}'"
1330
+ template_url = (
1331
+ None
1332
+ if self.code_model.options["version_tolerant"]
1333
+ else f"'{request_builder.url}'"
1334
+ )
1128
1335
  else:
1129
1336
  request_builder = builder.request_builder
1130
1337
  template_url = "next_link"
1131
1338
 
1132
1339
  request_builder = builder.next_request_builder or builder.request_builder
1133
1340
  return self._call_request_builder_helper(
1134
- builder,
1135
- request_builder,
1136
- template_url=template_url,
1137
- is_next_request=True
1341
+ builder, request_builder, template_url=template_url, is_next_request=True
1138
1342
  )
1139
1343
 
1140
1344
  def _prepare_request_callback(self, builder) -> List[str]:
1141
1345
  retval = ["def prepare_request(next_link=None):"]
1142
1346
  retval.append(" if not next_link:")
1143
- retval.extend([
1144
- f" {line}"
1145
- for line in self.call_request_builder(builder)
1146
- ])
1347
+ retval.extend(
1348
+ [f" {line}" for line in self.call_request_builder(builder)]
1349
+ )
1147
1350
  retval.append("")
1148
1351
  retval.append(" else:")
1149
- retval.extend([
1150
- f" {line}"
1151
- for line in self.call_next_link_request_builder(builder)
1152
- ])
1352
+ retval.extend(
1353
+ [f" {line}" for line in self.call_next_link_request_builder(builder)]
1354
+ )
1153
1355
  if not builder.next_request_builder and builder.parameters.path:
1154
1356
  retval.append("")
1155
- retval.extend([
1156
- f" {line}"
1157
- for line in self.serialize_path(builder)
1158
- ])
1357
+ retval.extend([f" {line}" for line in self.serialize_path(builder)])
1159
1358
  if not builder.next_request_builder:
1160
1359
  retval.append(' request.method = "GET"')
1161
1360
  else:
1162
- retval.append('')
1361
+ retval.append("")
1163
1362
  retval.append(" return request")
1164
1363
  return retval
1165
1364
 
@@ -1178,12 +1377,16 @@ class _PagingOperationBaseSerializer(_OperationBaseSerializer): # pylint: disab
1178
1377
  response = builder.responses[0]
1179
1378
  deserialized = (
1180
1379
  f'self._deserialize("{response.serialization_type}", pipeline_response)'
1181
- if self.code_model.options["models_mode"] else
1182
- "pipeline_response.http_response.json()"
1380
+ if self.code_model.options["models_mode"]
1381
+ else "pipeline_response.http_response.json()"
1183
1382
  )
1184
1383
  retval.append(f" deserialized = {deserialized}")
1185
1384
  item_name = builder.item_name(self.code_model)
1186
- list_of_elem = f".{item_name}" if self.code_model.options["models_mode"] else f'["{item_name}"]'
1385
+ list_of_elem = (
1386
+ f".{item_name}"
1387
+ if self.code_model.options["models_mode"]
1388
+ else f'["{item_name}"]'
1389
+ )
1187
1390
  retval.append(f" list_of_elem = deserialized{list_of_elem}")
1188
1391
  retval.append(" if cls:")
1189
1392
  retval.append(" list_of_elem = cls(list_of_elem)")
@@ -1195,24 +1398,25 @@ class _PagingOperationBaseSerializer(_OperationBaseSerializer): # pylint: disab
1195
1398
  next_link_property = f"deserialized.{next_link_name} or None"
1196
1399
  else:
1197
1400
  next_link_property = f'deserialized.get("{next_link_name}", None)'
1198
- retval.append(f" return {next_link_property}, {self._list_type_returned_to_users}(list_of_elem)")
1401
+ retval.append(
1402
+ f" return {next_link_property}, {self._list_type_returned_to_users}(list_of_elem)"
1403
+ )
1199
1404
  return retval
1200
1405
 
1201
1406
  def _get_next_callback(self, builder) -> List[str]:
1202
1407
  retval = [f"{self._def} get_next(next_link=None):"]
1203
1408
  retval.append(" request = prepare_request(next_link)")
1204
1409
  retval.append("")
1205
- retval.append(f" pipeline_response = {self._call_method}self._client._pipeline.run( # pylint: disable=protected-access")
1410
+ retval.append(
1411
+ f" pipeline_response = {self._call_method}self._client._pipeline.run( # pylint: disable=protected-access"
1412
+ )
1206
1413
  retval.append(" request,")
1207
1414
  retval.append(f" stream={builder.is_stream_response},")
1208
1415
  retval.append(" **kwargs")
1209
1416
  retval.append(" )")
1210
1417
  retval.append(" response = pipeline_response.http_response")
1211
1418
  retval.append("")
1212
- retval.extend([
1213
- f" {line}"
1214
- for line in self.handle_error_response(builder)
1215
- ])
1419
+ retval.extend([f" {line}" for line in self.handle_error_response(builder)])
1216
1420
  retval.append("")
1217
1421
  retval.append(" return pipeline_response")
1218
1422
  return retval
@@ -1227,8 +1431,13 @@ class _PagingOperationBaseSerializer(_OperationBaseSerializer): # pylint: disab
1227
1431
  retval.extend(self._get_next_callback(builder))
1228
1432
  return retval
1229
1433
 
1230
- class _SyncPagingOperationBaseSerializer(_PagingOperationBaseSerializer, _SyncOperationBaseSerializer): # pylint: disable=abstract-method
1231
- def _response_docstring_type_wrapper(self, builder) -> List[str]: # pylint: no-self-use
1434
+
1435
+ class _SyncPagingOperationBaseSerializer(
1436
+ _PagingOperationBaseSerializer, _SyncOperationBaseSerializer
1437
+ ): # pylint: disable=abstract-method
1438
+ def _response_docstring_type_wrapper(
1439
+ self, builder
1440
+ ) -> List[str]: # pylint: no-self-use
1232
1441
  return [f"~{builder.get_pager_path(async_mode=False)}"]
1233
1442
 
1234
1443
  def _response_type_annotation_wrapper(self, builder) -> List[str]:
@@ -1242,14 +1451,25 @@ class _SyncPagingOperationBaseSerializer(_PagingOperationBaseSerializer, _SyncOp
1242
1451
  def _pager(builder) -> str:
1243
1452
  return builder.get_pager(async_mode=False)
1244
1453
 
1245
- class SyncPagingOperationGenericSerializer(_SyncPagingOperationBaseSerializer, SyncOperationGenericSerializer):
1454
+
1455
+ class SyncPagingOperationGenericSerializer(
1456
+ _SyncPagingOperationBaseSerializer, SyncOperationGenericSerializer
1457
+ ):
1246
1458
  pass
1247
1459
 
1248
- class SyncPagingOperationPython3Serializer(_SyncPagingOperationBaseSerializer, SyncOperationPython3Serializer):
1460
+
1461
+ class SyncPagingOperationPython3Serializer(
1462
+ _SyncPagingOperationBaseSerializer, SyncOperationPython3Serializer
1463
+ ):
1249
1464
  pass
1250
1465
 
1251
- class AsyncPagingOperationSerializer(_PagingOperationBaseSerializer, AsyncOperationSerializer):
1252
- def _response_docstring_type_wrapper(self, builder) -> List[str]: # pylint: no-self-use
1466
+
1467
+ class AsyncPagingOperationSerializer(
1468
+ _PagingOperationBaseSerializer, AsyncOperationSerializer
1469
+ ):
1470
+ def _response_docstring_type_wrapper(
1471
+ self, builder
1472
+ ) -> List[str]: # pylint: no-self-use
1253
1473
  return [f"~{builder.get_pager_path(async_mode=True)}"]
1254
1474
 
1255
1475
  @property
@@ -1271,7 +1491,9 @@ class AsyncPagingOperationSerializer(_PagingOperationBaseSerializer, AsyncOperat
1271
1491
  ############################## LRO OPERATIONS ##############################
1272
1492
 
1273
1493
 
1274
- class _LROOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable=abstract-method
1494
+ class _LROOperationBaseSerializer(
1495
+ _OperationBaseSerializer
1496
+ ): # pylint: disable=abstract-method
1275
1497
  def cls_type_annotation(self, builder) -> str:
1276
1498
  return f"# type: ClsType[{super()._response_type_annotation(builder, modify_if_head_as_boolean=False)}]"
1277
1499
 
@@ -1294,13 +1516,17 @@ class _LROOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable=
1294
1516
 
1295
1517
  def param_description(self, builder) -> List[str]:
1296
1518
  retval = super().param_description(builder)
1297
- retval.append(":keyword str continuation_token: A continuation token to restart a poller from a saved state.")
1519
+ retval.append(
1520
+ ":keyword str continuation_token: A continuation token to restart a poller from a saved state."
1521
+ )
1298
1522
  retval.append(
1299
1523
  f":keyword polling: By default, your polling method will be {self._default_polling_method(builder)}. "
1300
1524
  "Pass in False for this operation to not poll, or pass in your own initialized polling object for a"
1301
1525
  " personal polling strategy."
1302
1526
  )
1303
- retval.append(f":paramtype polling: bool or ~azure.core.polling.{self._polling_method_type}")
1527
+ retval.append(
1528
+ f":paramtype polling: bool or ~azure.core.polling.{self._polling_method_type}"
1529
+ )
1304
1530
  retval.append(
1305
1531
  ":keyword int polling_interval: Default waiting time between two polls for LRO operations "
1306
1532
  "if no Retry-After header is present."
@@ -1308,18 +1534,26 @@ class _LROOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable=
1308
1534
  return retval
1309
1535
 
1310
1536
  def initial_call(self, builder) -> List[str]:
1311
- retval = [f"polling = kwargs.pop('polling', True) # type: Union[bool, {self._polling_method_type}]"]
1537
+ retval = [
1538
+ f"polling = kwargs.pop('polling', True) # type: Union[bool, {self._polling_method_type}]"
1539
+ ]
1312
1540
  retval.append("lro_delay = kwargs.pop(")
1313
1541
  retval.append(" 'polling_interval',")
1314
1542
  retval.append(" self._config.polling_interval")
1315
1543
  retval.append(")")
1316
- retval.append("cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]")
1544
+ retval.append(
1545
+ "cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]"
1546
+ )
1317
1547
  retval.append("if cont_token is None:")
1318
- retval.append(f" raw_result = {self._call_method}self.{builder.initial_operation.name}( # type: ignore")
1319
- retval.extend([
1320
- f" {parameter.serialized_name}={parameter.serialized_name},"
1321
- for parameter in builder.parameters.method
1322
- ])
1548
+ retval.append(
1549
+ f" raw_result = {self._call_method}self.{builder.initial_operation.name}( # type: ignore"
1550
+ )
1551
+ retval.extend(
1552
+ [
1553
+ f" {parameter.serialized_name}={parameter.serialized_name},"
1554
+ for parameter in builder.parameters.method
1555
+ ]
1556
+ )
1323
1557
  retval.append(" cls=lambda x,y,z: x,")
1324
1558
  retval.append(" headers=_headers,")
1325
1559
  retval.append(" params=_params,")
@@ -1331,23 +1565,27 @@ class _LROOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable=
1331
1565
  def return_lro_poller(self, builder) -> List[str]:
1332
1566
  retval = []
1333
1567
  lro_options_str = (
1334
- "lro_options={'final-state-via': '" + builder.lro_options['final-state-via'] + "'},"
1335
- if builder.lro_options else ""
1568
+ "lro_options={'final-state-via': '"
1569
+ + builder.lro_options["final-state-via"]
1570
+ + "'},"
1571
+ if builder.lro_options
1572
+ else ""
1336
1573
  )
1337
1574
  path_format_arguments_str = ""
1338
1575
  if builder.parameters.path:
1339
1576
  path_format_arguments_str = "path_format_arguments=path_format_arguments,"
1340
1577
  retval.extend(self.serialize_path(builder))
1341
1578
  retval.append("")
1342
- retval.extend([
1343
- "if polling is True:",
1344
- f" polling_method = cast({self._polling_method_type}, {self._default_polling_method(builder)}(",
1345
- " lro_delay,",
1346
- f" {lro_options_str}",
1347
- f" {path_format_arguments_str}",
1348
- " **kwargs",
1349
- f")) # type: {self._polling_method_type}",
1350
- ]
1579
+ retval.extend(
1580
+ [
1581
+ "if polling is True:",
1582
+ f" polling_method = cast({self._polling_method_type}, {self._default_polling_method(builder)}(",
1583
+ " lro_delay,",
1584
+ f" {lro_options_str}",
1585
+ f" {path_format_arguments_str}",
1586
+ " **kwargs",
1587
+ f")) # type: {self._polling_method_type}",
1588
+ ]
1351
1589
  )
1352
1590
  retval.append(
1353
1591
  f"elif polling is False: polling_method = cast({self._polling_method_type}, "
@@ -1372,37 +1610,58 @@ class _LROOperationBaseSerializer(_OperationBaseSerializer): # pylint: disable=
1372
1610
  if builder.lro_response:
1373
1611
  if builder.lro_response.has_headers:
1374
1612
  retval.append(" response_headers = {}")
1375
- if not self.code_model.options["models_mode"] or builder.lro_response.has_headers:
1613
+ if (
1614
+ not self.code_model.options["models_mode"]
1615
+ or builder.lro_response.has_headers
1616
+ ):
1376
1617
  retval.append(" response = pipeline_response.http_response")
1377
- retval.extend([
1378
- f" {line}"
1379
- for line in self.response_headers_and_deserialization(builder.lro_response)
1380
- ])
1618
+ retval.extend(
1619
+ [
1620
+ f" {line}"
1621
+ for line in self.response_headers_and_deserialization(
1622
+ builder.lro_response
1623
+ )
1624
+ ]
1625
+ )
1381
1626
  retval.append(" if cls:")
1382
- retval.append(" return cls(pipeline_response, {}, {})".format(
1383
- 'deserialized' if builder.lro_response and builder.lro_response.has_body else 'None',
1384
- 'response_headers' if builder.lro_response and builder.lro_response.has_headers else '{}'
1385
- ))
1627
+ retval.append(
1628
+ " return cls(pipeline_response, {}, {})".format(
1629
+ "deserialized"
1630
+ if builder.lro_response and builder.lro_response.has_body
1631
+ else "None",
1632
+ "response_headers"
1633
+ if builder.lro_response and builder.lro_response.has_headers
1634
+ else "{}",
1635
+ )
1636
+ )
1386
1637
  if builder.lro_response and builder.lro_response.has_body:
1387
1638
  retval.append(" return deserialized")
1388
1639
  return retval
1389
1640
 
1390
1641
 
1391
- class _SyncLROOperationBaseSerializer(_LROOperationBaseSerializer, _SyncOperationBaseSerializer): # pylint: disable=abstract-method
1392
- def _response_docstring_text_template(self, builder) -> str: # pylint: disable=no-self-use
1642
+ class _SyncLROOperationBaseSerializer(
1643
+ _LROOperationBaseSerializer, _SyncOperationBaseSerializer
1644
+ ): # pylint: disable=abstract-method
1645
+ def _response_docstring_text_template(
1646
+ self, builder
1647
+ ) -> str: # pylint: disable=no-self-use
1393
1648
  lro_section = f"An instance of {builder.get_poller(async_mode=False)} "
1394
1649
  if self._cls_docstring_rtype:
1395
1650
  return lro_section + "that returns either {}" + self._cls_docstring_rtype
1396
1651
  return lro_section + "that returns {}"
1397
1652
 
1398
- def _response_docstring_type_wrapper(self, builder) -> List[str]: # pylint: no-self-use
1653
+ def _response_docstring_type_wrapper(
1654
+ self, builder
1655
+ ) -> List[str]: # pylint: no-self-use
1399
1656
  return [f"~{builder.get_poller_path(async_mode=False)}"]
1400
1657
 
1401
1658
  def _response_type_annotation_wrapper(self, builder) -> List[str]:
1402
1659
  return [builder.get_poller(async_mode=False)]
1403
1660
 
1404
1661
  def _default_polling_method(self, builder) -> str:
1405
- return builder.get_default_polling_method(async_mode=False, azure_arm=self.code_model.options["azure_arm"])
1662
+ return builder.get_default_polling_method(
1663
+ async_mode=False, azure_arm=self.code_model.options["azure_arm"]
1664
+ )
1406
1665
 
1407
1666
  def _default_no_polling_method(self, builder) -> str:
1408
1667
  return builder.get_default_no_polling_method(async_mode=False)
@@ -1414,28 +1673,42 @@ class _SyncLROOperationBaseSerializer(_LROOperationBaseSerializer, _SyncOperatio
1414
1673
  def _poller(self, builder) -> str:
1415
1674
  return builder.get_poller(async_mode=False)
1416
1675
 
1417
- class SyncLROOperationGenericSerializer(_SyncLROOperationBaseSerializer, SyncOperationGenericSerializer):
1676
+
1677
+ class SyncLROOperationGenericSerializer(
1678
+ _SyncLROOperationBaseSerializer, SyncOperationGenericSerializer
1679
+ ):
1418
1680
  pass
1419
1681
 
1420
- class SyncLROOperationPython3Serializer(_SyncLROOperationBaseSerializer, SyncOperationPython3Serializer):
1682
+
1683
+ class SyncLROOperationPython3Serializer(
1684
+ _SyncLROOperationBaseSerializer, SyncOperationPython3Serializer
1685
+ ):
1421
1686
  pass
1422
1687
 
1423
- class AsyncLROOperationSerializer(_LROOperationBaseSerializer, AsyncOperationSerializer):
1424
1688
 
1425
- def _response_docstring_text_template(self, builder) -> str: # pylint: disable=no-self-use
1689
+ class AsyncLROOperationSerializer(
1690
+ _LROOperationBaseSerializer, AsyncOperationSerializer
1691
+ ):
1692
+ def _response_docstring_text_template(
1693
+ self, builder
1694
+ ) -> str: # pylint: disable=no-self-use
1426
1695
  lro_section = f"An instance of {builder.get_poller(async_mode=True)} "
1427
1696
  if self._cls_docstring_rtype:
1428
1697
  return lro_section + "that returns either {}" + self._cls_docstring_rtype
1429
1698
  return lro_section + "that returns {}"
1430
1699
 
1431
- def _response_docstring_type_wrapper(self, builder) -> List[str]: # pylint: no-self-use
1700
+ def _response_docstring_type_wrapper(
1701
+ self, builder
1702
+ ) -> List[str]: # pylint: no-self-use
1432
1703
  return [f"~{builder.get_poller_path(async_mode=True)}"]
1433
1704
 
1434
1705
  def _response_type_annotation_wrapper(self, builder) -> List[str]:
1435
1706
  return [builder.get_poller(async_mode=True)]
1436
1707
 
1437
1708
  def _default_polling_method(self, builder) -> str:
1438
- return builder.get_default_polling_method(async_mode=True, azure_arm=self.code_model.options["azure_arm"])
1709
+ return builder.get_default_polling_method(
1710
+ async_mode=True, azure_arm=self.code_model.options["azure_arm"]
1711
+ )
1439
1712
 
1440
1713
  def _default_no_polling_method(self, builder) -> str:
1441
1714
  return builder.get_default_no_polling_method(async_mode=True)
@@ -1450,8 +1723,10 @@ class AsyncLROOperationSerializer(_LROOperationBaseSerializer, AsyncOperationSer
1450
1723
 
1451
1724
  ############################## LRO PAGING OPERATIONS ##############################
1452
1725
 
1453
- class _LROPagingOperationBaseSerializer(_LROOperationBaseSerializer, _PagingOperationBaseSerializer): # pylint: disable=abstract-method
1454
1726
 
1727
+ class _LROPagingOperationBaseSerializer(
1728
+ _LROOperationBaseSerializer, _PagingOperationBaseSerializer
1729
+ ): # pylint: disable=abstract-method
1455
1730
  def get_long_running_output(self, builder) -> List[str]:
1456
1731
  retval = ["def get_long_running_output(pipeline_response):"]
1457
1732
  retval.append(f" {self._def} internal_get_next(next_link=None):")
@@ -1464,38 +1739,64 @@ class _LROPagingOperationBaseSerializer(_LROOperationBaseSerializer, _PagingOper
1464
1739
  retval.append(" )")
1465
1740
  return retval
1466
1741
 
1742
+ def decorators(self, builder, async_mode: bool) -> List[str]:
1743
+ """Decorators for the method"""
1744
+ return _LROOperationBaseSerializer.decorators(self, builder, async_mode)
1745
+
1467
1746
 
1468
1747
  class _SyncLROPagingOperationBaseSerializer( # pylint: disable=abstract-method
1469
- _SyncLROOperationBaseSerializer, _SyncPagingOperationBaseSerializer, _LROPagingOperationBaseSerializer
1748
+ _SyncLROOperationBaseSerializer,
1749
+ _SyncPagingOperationBaseSerializer,
1750
+ _LROPagingOperationBaseSerializer,
1470
1751
  ):
1471
-
1472
1752
  def _response_docstring_type_wrapper(self, builder) -> List[str]:
1473
1753
  return _SyncLROOperationBaseSerializer._response_docstring_type_wrapper(
1474
1754
  self, builder
1475
- ) + _SyncPagingOperationBaseSerializer._response_docstring_type_wrapper(self, builder)
1755
+ ) + _SyncPagingOperationBaseSerializer._response_docstring_type_wrapper(
1756
+ self, builder
1757
+ )
1476
1758
 
1477
1759
  def _response_type_annotation_wrapper(self, builder) -> List[str]:
1478
- return _SyncLROOperationBaseSerializer._response_type_annotation_wrapper(self, builder) + [
1479
- builder.get_pager(async_mode=False)
1480
- ]
1760
+ return _SyncLROOperationBaseSerializer._response_type_annotation_wrapper(
1761
+ self, builder
1762
+ ) + [builder.get_pager(async_mode=False)]
1481
1763
 
1482
1764
  def _response_docstring_text_template(self, builder) -> str:
1483
- lro_doc = _SyncLROOperationBaseSerializer._response_docstring_text_template(self, builder)
1484
- paging_doc = _SyncPagingOperationBaseSerializer._response_docstring_text_template(self, builder)
1765
+ lro_doc = _SyncLROOperationBaseSerializer._response_docstring_text_template(
1766
+ self, builder
1767
+ )
1768
+ paging_doc = (
1769
+ _SyncPagingOperationBaseSerializer._response_docstring_text_template(
1770
+ self, builder
1771
+ )
1772
+ )
1485
1773
  paging_doc = paging_doc.replace(paging_doc[0], paging_doc[0].lower(), 1)
1486
- return lro_doc.format(paging_doc).replace(self._cls_docstring_rtype, "", 1).replace("either ", "", 1)
1774
+ return (
1775
+ lro_doc.format(paging_doc)
1776
+ .replace(self._cls_docstring_rtype, "", 1)
1777
+ .replace("either ", "", 1)
1778
+ )
1487
1779
 
1488
1780
  def cls_type_annotation(self, builder) -> str:
1489
1781
  return f"# type: ClsType[{self._response_type_annotation(builder, modify_if_head_as_boolean=False)}]"
1490
1782
 
1491
- class SyncLROPagingOperationGenericSerializer(_SyncLROPagingOperationBaseSerializer, SyncOperationGenericSerializer):
1783
+
1784
+ class SyncLROPagingOperationGenericSerializer(
1785
+ _SyncLROPagingOperationBaseSerializer, SyncOperationGenericSerializer
1786
+ ):
1492
1787
  pass
1493
1788
 
1494
- class SyncLROPagingOperationPython3Serializer(_SyncLROPagingOperationBaseSerializer, SyncOperationPython3Serializer):
1789
+
1790
+ class SyncLROPagingOperationPython3Serializer(
1791
+ _SyncLROPagingOperationBaseSerializer, SyncOperationPython3Serializer
1792
+ ):
1495
1793
  pass
1496
1794
 
1795
+
1497
1796
  class AsyncLROPagingOperationSerializer(
1498
- _LROPagingOperationBaseSerializer, AsyncLROOperationSerializer, AsyncPagingOperationSerializer
1797
+ _LROPagingOperationBaseSerializer,
1798
+ AsyncLROOperationSerializer,
1799
+ AsyncPagingOperationSerializer,
1499
1800
  ):
1500
1801
  @property
1501
1802
  def _function_definition(self) -> str:
@@ -1504,18 +1805,30 @@ class AsyncLROPagingOperationSerializer(
1504
1805
  def _response_docstring_type_wrapper(self, builder) -> List[str]:
1505
1806
  return AsyncLROOperationSerializer._response_docstring_type_wrapper(
1506
1807
  self, builder
1507
- ) + AsyncPagingOperationSerializer._response_docstring_type_wrapper(self, builder)
1808
+ ) + AsyncPagingOperationSerializer._response_docstring_type_wrapper(
1809
+ self, builder
1810
+ )
1508
1811
 
1509
- def _response_type_annotation_wrapper(self, builder: LROPagingOperation) -> List[str]:
1510
- return AsyncLROOperationSerializer._response_type_annotation_wrapper(self, builder) + [
1511
- builder.get_pager(async_mode=True)
1512
- ]
1812
+ def _response_type_annotation_wrapper(
1813
+ self, builder: LROPagingOperation
1814
+ ) -> List[str]:
1815
+ return AsyncLROOperationSerializer._response_type_annotation_wrapper(
1816
+ self, builder
1817
+ ) + [builder.get_pager(async_mode=True)]
1513
1818
 
1514
1819
  def _response_docstring_text_template(self, builder) -> str:
1515
- lro_doc = AsyncLROOperationSerializer._response_docstring_text_template(self, builder)
1516
- paging_doc = AsyncPagingOperationSerializer._response_docstring_text_template(self, builder)
1820
+ lro_doc = AsyncLROOperationSerializer._response_docstring_text_template(
1821
+ self, builder
1822
+ )
1823
+ paging_doc = AsyncPagingOperationSerializer._response_docstring_text_template(
1824
+ self, builder
1825
+ )
1517
1826
  paging_doc = paging_doc.replace(paging_doc[0], paging_doc[0].lower(), 1)
1518
- return lro_doc.format(paging_doc).replace(self._cls_docstring_rtype, "", 1).replace("either ", "", 1)
1827
+ return (
1828
+ lro_doc.format(paging_doc)
1829
+ .replace(self._cls_docstring_rtype, "", 1)
1830
+ .replace("either ", "", 1)
1831
+ )
1519
1832
 
1520
1833
 
1521
1834
  def get_operation_serializer(
@@ -1527,32 +1840,55 @@ def get_operation_serializer(
1527
1840
  retcls = _OperationBaseSerializer
1528
1841
  if isinstance(builder, LROPagingOperation):
1529
1842
  retcls = (
1530
- AsyncLROPagingOperationSerializer if async_mode
1843
+ AsyncLROPagingOperationSerializer
1844
+ if async_mode
1531
1845
  else (
1532
- SyncLROPagingOperationPython3Serializer if is_python3_file
1846
+ SyncLROPagingOperationPython3Serializer
1847
+ if is_python3_file
1533
1848
  else SyncLROPagingOperationGenericSerializer
1534
1849
  )
1535
1850
  )
1536
1851
  return retcls(code_model)
1537
1852
  if isinstance(builder, LROOperation):
1538
1853
  retcls = (
1539
- AsyncLROOperationSerializer if async_mode
1540
- else (SyncLROOperationPython3Serializer if is_python3_file else SyncLROOperationGenericSerializer)
1854
+ AsyncLROOperationSerializer
1855
+ if async_mode
1856
+ else (
1857
+ SyncLROOperationPython3Serializer
1858
+ if is_python3_file
1859
+ else SyncLROOperationGenericSerializer
1860
+ )
1541
1861
  )
1542
1862
  return retcls(code_model)
1543
1863
  if isinstance(builder, PagingOperation):
1544
1864
  retcls = (
1545
- AsyncPagingOperationSerializer if async_mode
1546
- else (SyncPagingOperationPython3Serializer if is_python3_file else SyncPagingOperationGenericSerializer)
1865
+ AsyncPagingOperationSerializer
1866
+ if async_mode
1867
+ else (
1868
+ SyncPagingOperationPython3Serializer
1869
+ if is_python3_file
1870
+ else SyncPagingOperationGenericSerializer
1871
+ )
1547
1872
  )
1548
1873
  return retcls(code_model)
1549
1874
  retcls = (
1550
- AsyncOperationSerializer if async_mode
1551
- else (SyncOperationPython3Serializer if is_python3_file else SyncOperationGenericSerializer)
1875
+ AsyncOperationSerializer
1876
+ if async_mode
1877
+ else (
1878
+ SyncOperationPython3Serializer
1879
+ if is_python3_file
1880
+ else SyncOperationGenericSerializer
1881
+ )
1552
1882
  )
1553
1883
  return retcls(code_model)
1554
1884
 
1555
1885
 
1556
- def get_request_builder_serializer(code_model, is_python3_file: bool) -> _RequestBuilderBaseSerializer:
1557
- retcls = RequestBuilderPython3Serializer if is_python3_file else RequestBuilderGenericSerializer
1886
+ def get_request_builder_serializer(
1887
+ code_model, is_python3_file: bool
1888
+ ) -> _RequestBuilderBaseSerializer:
1889
+ retcls = (
1890
+ RequestBuilderPython3Serializer
1891
+ if is_python3_file
1892
+ else RequestBuilderGenericSerializer
1893
+ )
1558
1894
  return retcls(code_model)