@autorest/python 6.8.1 → 6.9.1

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.
@@ -3,7 +3,7 @@
3
3
  # Licensed under the MIT License. See License.txt in the project root for
4
4
  # license information.
5
5
  # --------------------------------------------------------------------------
6
- from typing import Any, Dict, Tuple
6
+ from typing import Any, Dict, Tuple, List
7
7
  import re
8
8
  import argparse
9
9
 
@@ -105,3 +105,26 @@ KNOWN_TYPES: Dict[str, Dict[str, Any]] = {
105
105
  }
106
106
 
107
107
  JSON_REGEXP = re.compile(r"^(application|text)/(.+\+)?json$")
108
+
109
+
110
+ def build_policies(is_arm: bool, async_mode: bool) -> List[str]:
111
+ async_prefix = "Async" if async_mode else ""
112
+ policies = [
113
+ "policies.RequestIdPolicy(**kwargs)",
114
+ "self._config.headers_policy",
115
+ "self._config.user_agent_policy",
116
+ "self._config.proxy_policy",
117
+ "policies.ContentDecodePolicy(**kwargs)",
118
+ f"{async_prefix}ARMAutoResourceProviderRegistrationPolicy()"
119
+ if is_arm
120
+ else None,
121
+ "self._config.redirect_policy",
122
+ "self._config.retry_policy",
123
+ "self._config.authentication_policy",
124
+ "self._config.custom_hook_policy",
125
+ "self._config.logging_policy",
126
+ "policies.DistributedTracingPolicy(**kwargs)",
127
+ "policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None",
128
+ "self._config.http_logging_policy",
129
+ ]
130
+ return [p for p in policies if p]
@@ -230,7 +230,16 @@ class Client(_ClientConfigBase[ClientGlobalParameterList]):
230
230
  MsrestImportType.SerializerDeserializer,
231
231
  TypingSection.REGULAR,
232
232
  )
233
-
233
+ file_import.add_submodule_import(
234
+ "azure.core.pipeline", "policies", ImportType.AZURECORE
235
+ )
236
+ if self.code_model.options["azure_arm"]:
237
+ async_prefix = "Async" if async_mode else ""
238
+ file_import.add_submodule_import(
239
+ "azure.mgmt.core.policies",
240
+ f"{async_prefix}ARMAutoResourceProviderRegistrationPolicy",
241
+ ImportType.AZURECORE,
242
+ )
234
243
  return file_import
235
244
 
236
245
  @property
@@ -239,10 +248,10 @@ class Client(_ClientConfigBase[ClientGlobalParameterList]):
239
248
  return any(o for o in self.operation_groups if o.is_mixin)
240
249
 
241
250
  @property
242
- def has_lro_operations(self) -> bool:
251
+ def has_public_lro_operations(self) -> bool:
243
252
  """Are there any LRO operations in this SDK?"""
244
253
  return any(
245
- operation.operation_type in ("lro", "lropaging")
254
+ operation.operation_type in ("lro", "lropaging") and not operation.internal
246
255
  for operation_group in self.operation_groups
247
256
  for operation in operation_group.operations
248
257
  )
@@ -398,9 +407,6 @@ class Config(_ClientConfigBase[ConfigGlobalParameterList]):
398
407
 
399
408
  def _imports_shared(self, async_mode: bool) -> FileImport:
400
409
  file_import = FileImport()
401
- file_import.add_submodule_import(
402
- "azure.core.configuration", "Configuration", ImportType.AZURECORE
403
- )
404
410
  file_import.add_submodule_import(
405
411
  "azure.core.pipeline", "policies", ImportType.AZURECORE
406
412
  )
@@ -68,6 +68,7 @@ class EnumType(BaseType):
68
68
  self.name: str = yaml_data["name"][0].upper() + yaml_data["name"][1:]
69
69
  self.values = values
70
70
  self.value_type = value_type
71
+ self.internal: bool = self.yaml_data.get("internal", False)
71
72
 
72
73
  def __lt__(self, other):
73
74
  return self.name.lower() < other.name.lower()
@@ -46,7 +46,8 @@ class LROOperationBase(OperationBase[LROResponseType]):
46
46
  exceptions=exceptions,
47
47
  overloads=overloads,
48
48
  )
49
- self.name = "begin_" + self.name
49
+ if not self.name.lstrip("_").startswith("begin"):
50
+ self.name = ("_begin" if self.internal else "begin_") + self.name
50
51
  self.lro_options: Dict[str, Any] = self.yaml_data.get("lroOptions", {})
51
52
  self._initial_operation: Optional["OperationType"] = None
52
53
 
@@ -486,7 +486,9 @@ class OperationBase( # pylint: disable=too-many-public-methods
486
486
  @property
487
487
  def success_status_codes(self) -> List[Union[str, int]]:
488
488
  """The list of all successfull status code."""
489
- return [code for response in self.responses for code in response.status_codes]
489
+ return sorted(
490
+ [code for response in self.responses for code in response.status_codes]
491
+ )
490
492
 
491
493
  @property
492
494
  def filename(self) -> str:
@@ -8,6 +8,7 @@ from typing import List
8
8
  from . import utils
9
9
  from ..models import Client, ParameterMethodLocation
10
10
  from .parameter_serializer import ParameterSerializer, PopKwargType
11
+ from ..._utils import build_policies
11
12
 
12
13
 
13
14
  class ClientSerializer:
@@ -72,7 +73,7 @@ class ClientSerializer:
72
73
  retval.append(
73
74
  f":{param.docstring_type_keyword} {param.client_name}: {param.docstring_type(async_mode=async_mode)}"
74
75
  )
75
- if self.client.has_lro_operations:
76
+ if self.client.has_public_lro_operations:
76
77
  retval.append(
77
78
  ":keyword int polling_interval: Default waiting time between two polls for LRO operations "
78
79
  "if no Retry-After header is present."
@@ -107,18 +108,27 @@ class ClientSerializer:
107
108
  if og.is_mixin and og.has_abstract_operations
108
109
  )
109
110
 
110
- def initialize_pipeline_client(self, async_mode: bool) -> str:
111
+ def initialize_pipeline_client(self, async_mode: bool) -> List[str]:
112
+ result = []
111
113
  pipeline_client_name = self.client.pipeline_class(async_mode)
112
114
  params = {
113
115
  "base_url": self.host_variable_name,
114
- "config": "self._config",
116
+ "policies": "_policies",
115
117
  }
116
118
  if not self.client.code_model.is_legacy and self.client.request_id_header_name:
117
- params["request_id_header_name"] = f'"{self.client.request_id_header_name}"'
118
- return (
119
- f"self._client: {pipeline_client_name} = {pipeline_client_name}("
120
- f"{', '.join(f'{k}={v}' for k, v in params.items())}, **kwargs)"
119
+ result.append(
120
+ f'kwargs["request_id_header_name"] = "{self.client.request_id_header_name}"'
121
+ )
122
+ result.extend(
123
+ [
124
+ "_policies = kwargs.pop('policies', None)",
125
+ "if _policies is None:",
126
+ f' _policies = [{",".join(build_policies(self.client.code_model.options["azure_arm"], async_mode))}]', # pylint: disable=line-too-long
127
+ f"self._client: {pipeline_client_name} = {pipeline_client_name}("
128
+ f"{', '.join(f'{k}={v}' for k, v in params.items())}, **kwargs)",
129
+ ]
121
130
  )
131
+ return result
122
132
 
123
133
  def serializers_and_operation_groups_properties(self) -> List[str]:
124
134
  retval = []
@@ -16,7 +16,9 @@ class ModelInitSerializer:
16
16
  schemas = [s.name for s in self.code_model.public_model_types]
17
17
  schemas.sort()
18
18
  enums = (
19
- [e.name for e in self.code_model.enums] if self.code_model.enums else None
19
+ [e.name for e in self.code_model.enums if not e.internal]
20
+ if self.code_model.enums
21
+ else None
20
22
  )
21
23
 
22
24
  if enums:
@@ -10,7 +10,7 @@
10
10
  {{ serializer.host_variable_name }} = {{ keywords.escape_str(client.url) }}{{ client.url_pylint_disable }}
11
11
  {% endif %}
12
12
  {{ serializer.initialize_config() }}
13
- {{ serializer.initialize_pipeline_client(async_mode) }}
13
+ {{ op_tools.serialize(serializer.initialize_pipeline_client(async_mode)) | indent(8) }}
14
14
 
15
15
  {{ op_tools.serialize(serializer.serializers_and_operation_groups_properties()) | indent(8) }}
16
16
 
@@ -1,6 +1,4 @@
1
- class {{ client.name }}Configuration( {{ client.config.pylint_disable }}
2
- Configuration
3
- ):
1
+ class {{ client.name }}Configuration: {{ client.config.pylint_disable }}
4
2
  """Configuration for {{ client.name }}.
5
3
 
6
4
  Note that all parameters used to create this instance are saved as instance
@@ -10,7 +8,6 @@ class {{ client.name }}Configuration( {{ client.config.pylint_disable }}
10
8
  {% endif %}
11
9
  {{ op_tools.serialize_with_wrap(serializer.property_descriptions(async_mode), "\n ") | indent }}
12
10
  {{ serializer.init_signature_and_response_type_annotation(async_mode) | indent }}
13
- super({{ client.name }}Configuration, self).__init__(**kwargs)
14
11
  {% if client.config.parameters.kwargs_to_pop %}
15
12
  {{ op_tools.serialize(serializer.pop_kwargs_from_signature()) | indent(8) }}
16
13
  {% endif %}
@@ -34,6 +31,7 @@ class {{ client.name }}Configuration( {{ client.config.pylint_disable }}
34
31
  {% endif %}
35
32
  {% endif %}
36
33
  kwargs.setdefault('sdk_moniker', '{{ client.config.sdk_moniker }}/{}'.format(VERSION))
34
+ self.polling_interval = kwargs.get("polling_interval", 30)
37
35
  self._configure(**kwargs)
38
36
 
39
37
  {% if client.credential and client.credential.type.types is defined %}
@@ -10,7 +10,7 @@
10
10
  "host_value": {{ (client.parameters.host.client_default_value_declaration if not client.has_parameterized_host else None) | tojson }},
11
11
  "parameterized_host_template": {{ (keywords.escape_str(client.url) if client.has_parameterized_host else None) | tojson }},
12
12
  "azure_arm": {{ client.code_model.options["azure_arm"] | tojson }},
13
- "has_lro_operations": {{ client.has_lro_operations | tojson }},
13
+ "has_public_lro_operations": {{ client.has_public_lro_operations | tojson }},
14
14
  "client_side_validation": {{ client.code_model.options["client_side_validation"] | tojson }},
15
15
  "sync_imports": {{ sync_client_imports | tojson }},
16
16
  "async_imports": {{ async_client_imports | tojson }}
@@ -1126,10 +1126,7 @@ class M4Reformatter(
1126
1126
  "skipUrlEncoding": True,
1127
1127
  "inOverload": False,
1128
1128
  }
1129
- if self.version_tolerant:
1130
- parameters.append(credential)
1131
- else:
1132
- parameters.insert(0, credential)
1129
+ parameters.append(credential)
1133
1130
 
1134
1131
  def update_client(self, yaml_data: Dict[str, Any]) -> Dict[str, Any]:
1135
1132
  parameters = self.update_global_parameters(
@@ -71,12 +71,12 @@ class Client:
71
71
  return parameterized_host_template_to_api_version
72
72
 
73
73
  @property
74
- def has_lro_operations(self) -> bool:
75
- has_lro_operations = False
74
+ def has_public_lro_operations(self) -> bool:
75
+ has_public_lro_operations = False
76
76
  for _, metadata_json in self.version_path_to_metadata.items():
77
- current_client_has_lro_operations = metadata_json["client"][
78
- "has_lro_operations"
77
+ current_client_has_public_lro_operations = metadata_json["client"][
78
+ "has_public_lro_operations"
79
79
  ]
80
- if current_client_has_lro_operations:
81
- has_lro_operations = True
82
- return has_lro_operations
80
+ if current_client_has_public_lro_operations:
81
+ has_public_lro_operations = True
82
+ return has_public_lro_operations
@@ -12,6 +12,7 @@ from .import_serializer import FileImportSerializer
12
12
  from ...jsonrpc import AutorestAPI
13
13
  from ..models import CodeModel, GlobalParameter
14
14
  from ... import ReaderAndWriter, ReaderAndWriterAutorest
15
+ from ..._utils import build_policies
15
16
 
16
17
  __all__ = [
17
18
  "MultiAPISerializer",
@@ -86,9 +87,12 @@ class MultiAPISerializer(ReaderAndWriter): # pylint: disable=abstract-method
86
87
 
87
88
  # serialize service client file
88
89
  imports = FileImportSerializer(code_model.client.imports(async_mode))
90
+ config_policies = build_policies(code_model.azure_arm, async_mode)
89
91
  self.write_file(
90
92
  _get_file_path(code_model.client.filename, async_mode),
91
- _render_template("client", imports=imports),
93
+ _render_template(
94
+ "client", imports=imports, config_policies=config_policies
95
+ ),
92
96
  )
93
97
 
94
98
  # serialize config file
@@ -28,7 +28,7 @@ def __init__(
28
28
  # --------------------------------------------------------------------------
29
29
  {{ imports }}
30
30
 
31
- class {{ code_model.client.name }}Configuration(Configuration):
31
+ class {{ code_model.client.name }}Configuration:
32
32
  """Configuration for {{ code_model.client.name }}.
33
33
 
34
34
  Note that all parameters used to create this instance are saved as instance
@@ -49,7 +49,6 @@ class {{ code_model.client.name }}Configuration(Configuration):
49
49
  raise ValueError("Parameter '{{ parameter.name }}' must not be None.")
50
50
  {% endif %}
51
51
  {% endfor %}
52
- super({{ code_model.client.name }}Configuration, self).__init__(**kwargs)
53
52
 
54
53
  {% for parameter in code_model.global_parameters.parameters %}
55
54
  self.{{ parameter.name }} = {{ parameter.name }}
@@ -63,6 +62,7 @@ class {{ code_model.client.name }}Configuration(Configuration):
63
62
  self.credential_scopes = kwargs.pop('credential_scopes', {{ code_model.config.credential_scopes }})
64
63
  {% endif %}
65
64
  kwargs.setdefault('sdk_moniker', '{{ code_model.package_name|lower }}/{}'.format(VERSION))
65
+ self.polling_interval = kwargs.get("polling_interval", 30)
66
66
  self._configure(**kwargs)
67
67
 
68
68
  def _configure(
@@ -60,7 +60,7 @@ class {{ code_model.client.name }}({% if code_model.operation_mixin_group.mixin_
60
60
  :param {{ parameter.name }}: {{ parameter.description(async_mode) }}
61
61
  :type {{ parameter.name }}: {{ parameter.docstring_type(async_mode) }}
62
62
  {% endfor %}
63
- {% if code_model.client.has_lro_operations %}
63
+ {% if code_model.client.has_public_lro_operations %}
64
64
  :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
65
65
  {% endif %}
66
66
  """
@@ -90,7 +90,14 @@ class {{ code_model.client.name }}({% if code_model.operation_mixin_group.mixin_
90
90
  if api_version:
91
91
  kwargs.setdefault('api_version', api_version)
92
92
  self._config = {{ code_model.client.name }}Configuration({{ code_model.global_parameters.call }}{{ ", " if code_model.global_parameters.call }}**kwargs)
93
- self._client = {{ async_prefix }}{{ code_model.client.pipeline_client }}(base_url={{ code_model.host_variable_name }}, config=self._config, **kwargs)
93
+ _policies = kwargs.pop("policies", None)
94
+ if _policies is None:
95
+ _policies = [
96
+ {% for p in config_policies %}
97
+ {{ p }},
98
+ {% endfor %}
99
+ ]
100
+ self._client = {{ async_prefix }}{{ code_model.client.pipeline_client }}(base_url={{ code_model.host_variable_name }}, policies=_policies, **kwargs)
94
101
  super({{ code_model.client.name }}, self).__init__(
95
102
  api_version=api_version,
96
103
  profile=profile
@@ -281,7 +281,8 @@ class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method
281
281
  yaml_data["description"], default_description=yaml_data["name"]
282
282
  )
283
283
  yaml_data["legacyFilename"] = to_snake_case(yaml_data["name"].replace(" ", "_"))
284
- for parameter in yaml_data["parameters"]:
284
+ parameters = yaml_data["parameters"]
285
+ for parameter in parameters:
285
286
  self.update_parameter(parameter)
286
287
  if parameter["clientName"] == "credential":
287
288
  policy = parameter["type"].get("policy")
@@ -294,7 +295,13 @@ class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method
294
295
  policy["credentialScopes"] = [
295
296
  "https://management.azure.com/.default"
296
297
  ]
297
-
298
+ if (
299
+ (not self.version_tolerant or self.azure_arm)
300
+ and parameters
301
+ and parameters[-1]["clientName"] == "credential"
302
+ ):
303
+ # we need to move credential to the front in mgmt mode for backcompat reasons
304
+ yaml_data["parameters"] = [parameters[-1]] + parameters[:-1]
298
305
  prop_name = yaml_data["name"]
299
306
  if prop_name.endswith("Client"):
300
307
  prop_name = prop_name[: len(prop_name) - len("Client")]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autorest/python",
3
- "version": "6.8.1",
3
+ "version": "6.9.1",
4
4
  "description": "The Python extension for generators in AutoRest.",
5
5
  "main": "index.js",
6
6
  "repository": {