Skip to content

Commit ecbb639

Browse files
authored
[Key Vault] Python 3-style typing and formatting (Azure#28113)
1 parent 38a022f commit ecbb639

File tree

128 files changed

+1988
-2030
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

128 files changed

+1988
-2030
lines changed

sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_access_control_client.py

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,9 @@ class KeyVaultAccessControlClient(KeyVaultClientBase):
3838
# pylint:disable=protected-access
3939

4040
@distributed_trace
41-
def create_role_assignment(self, scope, definition_id, principal_id, **kwargs):
42-
# type: (Union[str, KeyVaultRoleScope], str, str, **Any) -> KeyVaultRoleAssignment
41+
def create_role_assignment(
42+
self, scope: "Union[str, KeyVaultRoleScope]", definition_id: str, principal_id: str, **kwargs
43+
) -> KeyVaultRoleAssignment:
4344
"""Create a role assignment.
4445
4546
:param scope: scope the role assignment will apply over. :class:`KeyVaultRoleScope` defines common
@@ -48,8 +49,10 @@ def create_role_assignment(self, scope, definition_id, principal_id, **kwargs):
4849
:param str definition_id: ID of the role's definition
4950
:param str principal_id: Azure Active Directory object ID of the principal which will be assigned the role. The
5051
principal can be a user, service principal, or security group.
52+
5153
:keyword name: a name for the role assignment. Must be a UUID.
5254
:paramtype name: str or uuid.UUID
55+
5356
:rtype: ~azure.keyvault.administration.KeyVaultRoleAssignment
5457
"""
5558
name = kwargs.pop("name", None) or uuid4()
@@ -69,15 +72,17 @@ def create_role_assignment(self, scope, definition_id, principal_id, **kwargs):
6972
return KeyVaultRoleAssignment._from_generated(assignment)
7073

7174
@distributed_trace
72-
def delete_role_assignment(self, scope, name, **kwargs):
73-
# type: (Union[str, KeyVaultRoleScope], Union[str, UUID], **Any) -> None
75+
def delete_role_assignment(
76+
self, scope: "Union[str, KeyVaultRoleScope]", name: "Union[str, UUID]", **kwargs
77+
) -> None:
7478
"""Delete a role assignment.
7579
7680
:param scope: the assignment's scope, for example "/", "/keys", or "/keys/<specific key identifier>"
7781
:class:`KeyVaultRoleScope` defines common broad scopes. Specify a narrower scope as a string.
7882
:type scope: str or KeyVaultRoleScope
7983
:param name: the role assignment's name.
8084
:type name: str or uuid.UUID
85+
8186
:returns: None
8287
"""
8388
try:
@@ -88,15 +93,17 @@ def delete_role_assignment(self, scope, name, **kwargs):
8893
pass
8994

9095
@distributed_trace
91-
def get_role_assignment(self, scope, name, **kwargs):
92-
# type: (Union[str, KeyVaultRoleScope], Union[str, UUID], **Any) -> KeyVaultRoleAssignment
96+
def get_role_assignment(
97+
self, scope: "Union[str, KeyVaultRoleScope]", name: "Union[str, UUID]", **kwargs
98+
) -> KeyVaultRoleAssignment:
9399
"""Get a role assignment.
94100
95101
:param scope: the assignment's scope, for example "/", "/keys", or "/keys/<specific key identifier>"
96102
:class:`KeyVaultRoleScope` defines common broad scopes. Specify a narrower scope as a string.
97103
:type scope: str or KeyVaultRoleScope
98104
:param name: the role assignment's name.
99105
:type name: str or uuid.UUID
106+
100107
:rtype: ~azure.keyvault.administration.KeyVaultRoleAssignment
101108
"""
102109
assignment = self._client.role_assignments.get(
@@ -105,13 +112,15 @@ def get_role_assignment(self, scope, name, **kwargs):
105112
return KeyVaultRoleAssignment._from_generated(assignment)
106113

107114
@distributed_trace
108-
def list_role_assignments(self, scope, **kwargs):
109-
# type: (Union[str, KeyVaultRoleScope], **Any) -> ItemPaged[KeyVaultRoleAssignment]
115+
def list_role_assignments(
116+
self, scope: "Union[str, KeyVaultRoleScope]", **kwargs
117+
) -> "ItemPaged[KeyVaultRoleAssignment]":
110118
"""List all role assignments for a scope.
111119
112120
:param scope: scope of the role assignments. :class:`KeyVaultRoleScope` defines common broad scopes.
113121
Specify a narrower scope as a string.
114122
:type scope: str or KeyVaultRoleScope
123+
115124
:rtype: ~azure.core.paging.ItemPaged[~azure.keyvault.administration.KeyVaultRoleAssignment]
116125
"""
117126
return self._client.role_assignments.list_for_scope(
@@ -122,15 +131,17 @@ def list_role_assignments(self, scope, **kwargs):
122131
)
123132

124133
@distributed_trace
125-
def set_role_definition(self, scope, **kwargs):
126-
# type: (Union[str, KeyVaultRoleScope], **Any) -> KeyVaultRoleDefinition
134+
def set_role_definition(
135+
self, scope: "Union[str, KeyVaultRoleScope]", **kwargs
136+
) -> "KeyVaultRoleDefinition":
127137
"""Creates or updates a custom role definition.
128138
129139
To update a role definition, specify the definition's ``name``.
130140
131141
:param scope: scope of the role definition. :class:`KeyVaultRoleScope` defines common broad scopes.
132142
Specify a narrower scope as a string. Managed HSM only supports '/', or KeyVaultRoleScope.GLOBAL.
133143
:type scope: str or KeyVaultRoleScope
144+
134145
:keyword name: the role definition's name, a UUID. When this argument has a value, the client will create a new
135146
role definition with this name or update an existing role definition, if one exists with the given name.
136147
When this argument has no value, a new role definition will be created with a generated name.
@@ -144,6 +155,7 @@ def set_role_definition(self, scope, **kwargs):
144155
:paramtype permissions: Iterable[KeyVaultPermission]
145156
:keyword assignable_scopes: the scopes for which the role definition can be assigned.
146157
:paramtype assignable_scopes: Iterable[str] or Iterable[KeyVaultRoleScope]
158+
147159
:returns: The created or updated role definition
148160
:rtype: ~azure.keyvault.administration.KeyVaultRoleDefinition
149161
"""
@@ -175,15 +187,17 @@ def set_role_definition(self, scope, **kwargs):
175187
return KeyVaultRoleDefinition._from_generated(definition)
176188

177189
@distributed_trace
178-
def get_role_definition(self, scope, name, **kwargs):
179-
# type: (Union[str, KeyVaultRoleScope], Union[str, UUID], **Any) -> KeyVaultRoleDefinition
190+
def get_role_definition(
191+
self, scope: "Union[str, KeyVaultRoleScope]", name: "Union[str, UUID]", **kwargs
192+
) -> "KeyVaultRoleDefinition":
180193
"""Get the specified role definition.
181194
182195
:param scope: scope of the role definition. :class:`KeyVaultRoleScope` defines common broad scopes.
183196
Specify a narrower scope as a string. Managed HSM only supports '/', or KeyVaultRoleScope.GLOBAL.
184197
:type scope: str or KeyVaultRoleScope
185198
:param name: the role definition's name.
186199
:type name: str or uuid.UUID
200+
187201
:rtype: ~azure.keyvault.administration.KeyVaultRoleDefinition
188202
"""
189203
definition = self._client.role_definitions.get(
@@ -192,15 +206,17 @@ def get_role_definition(self, scope, name, **kwargs):
192206
return KeyVaultRoleDefinition._from_generated(definition)
193207

194208
@distributed_trace
195-
def delete_role_definition(self, scope, name, **kwargs):
196-
# type: (Union[str, KeyVaultRoleScope], Union[str, UUID], **Any) -> None
209+
def delete_role_definition(
210+
self, scope: "Union[str, KeyVaultRoleScope]", name: "Union[str, UUID]", **kwargs
211+
) -> None:
197212
"""Deletes a custom role definition.
198213
199214
:param scope: scope of the role definition. :class:`KeyVaultRoleScope` defines common broad scopes.
200215
Specify a narrower scope as a string. Managed HSM only supports '/', or KeyVaultRoleScope.GLOBAL.
201216
:type scope: str or KeyVaultRoleScope
202217
:param name: the role definition's name.
203218
:type name: str or uuid.UUID
219+
204220
:returns: None
205221
"""
206222
try:
@@ -211,13 +227,15 @@ def delete_role_definition(self, scope, name, **kwargs):
211227
pass
212228

213229
@distributed_trace
214-
def list_role_definitions(self, scope, **kwargs):
215-
# type: (Union[str, KeyVaultRoleScope], **Any) -> ItemPaged[KeyVaultRoleDefinition]
230+
def list_role_definitions(
231+
self, scope: "Union[str, KeyVaultRoleScope]", **kwargs
232+
) -> "ItemPaged[KeyVaultRoleDefinition]":
216233
"""List all role definitions applicable at and above a scope.
217234
218235
:param scope: scope of the role definitions. :class:`KeyVaultRoleScope` defines common broad scopes.
219236
Specify a narrower scope as a string.
220237
:type scope: str or KeyVaultRoleScope
238+
221239
:rtype: ~azure.core.paging.ItemPaged[~azure.keyvault.administration.KeyVaultRoleDefinition]
222240
"""
223241
return self._client.role_definitions.list(

sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_backup_client.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,17 @@ class KeyVaultBackupClient(KeyVaultClientBase):
4242
"""
4343

4444
# pylint:disable=protected-access
45-
def begin_backup(self, blob_storage_url, sas_token, **kwargs):
46-
# type: (str, str, **Any) -> LROPoller[KeyVaultBackupResult]
45+
def begin_backup(
46+
self, blob_storage_url: str, sas_token: str, **kwargs
47+
) -> "LROPoller[KeyVaultBackupResult]":
4748
"""Begin a full backup of the Key Vault.
4849
4950
:param str blob_storage_url: URL of the blob storage container in which the backup will be stored, for example
5051
https://<account>.blob.core.windows.net/backup
5152
:param str sas_token: a Shared Access Signature (SAS) token authorizing access to the blob storage resource
53+
5254
:keyword str continuation_token: a continuation token to restart polling from a saved state
55+
5356
:returns: An :class:`~azure.core.polling.LROPoller` instance. Call `result()` on this object to wait for the
5457
operation to complete and get a :class:`KeyVaultBackupResult`.
5558
:rtype: ~azure.core.polling.LROPoller[~azure.keyvault.administration.KeyVaultBackupResult]
@@ -95,8 +98,7 @@ def begin_backup(self, blob_storage_url, sas_token, **kwargs):
9598
**kwargs
9699
)
97100

98-
def begin_restore(self, folder_url, sas_token, **kwargs):
99-
# type: (str, str, **Any) -> LROPoller
101+
def begin_restore(self, folder_url: str, sas_token: str, **kwargs) -> "LROPoller":
100102
"""Restore a Key Vault backup.
101103
102104
This method restores either a complete Key Vault backup or when ``key_name`` has a value, a single key.
@@ -105,8 +107,10 @@ def begin_restore(self, folder_url, sas_token, **kwargs):
105107
:class:`KeyVaultBackupResult` returned by :func:`begin_backup`, for example
106108
https://<account>.blob.core.windows.net/backup/mhsm-account-2020090117323313
107109
:param str sas_token: a Shared Access Signature (SAS) token authorizing access to the blob storage resource
110+
108111
:keyword str continuation_token: a continuation token to restart polling from a saved state
109112
:keyword str key_name: name of a single key in the backup. When set, only this key will be restored.
113+
110114
:rtype: ~azure.core.polling.LROPoller
111115
112116
Examples:

sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,21 @@
2323
_VaultId = namedtuple("_VaultId", ["vault_url", "collection", "name", "version"])
2424

2525

26-
def parse_vault_id(url):
26+
def parse_vault_id(url: str) -> "_VaultId":
2727
try:
2828
parsed_uri = urlparse(url)
2929
except Exception: # pylint: disable=broad-except
30-
raise ValueError("'{}' is not a valid url".format(url))
30+
raise ValueError(f"'{url}' is not a valid url")
3131
if not (parsed_uri.scheme and parsed_uri.hostname):
32-
raise ValueError("'{}' is not a valid url".format(url))
32+
raise ValueError(f"'{url}' is not a valid url")
3333

3434
path = list(filter(None, parsed_uri.path.split("/")))
3535

3636
if len(path) < 2 or len(path) > 3:
37-
raise ValueError("'{}' is not a valid vault url".format(url))
37+
raise ValueError(f"'{url}' is not a valid vault url")
3838

3939
return _VaultId(
40-
vault_url="{}://{}".format(parsed_uri.scheme, parsed_uri.hostname),
40+
vault_url=f"{parsed_uri.scheme}://{parsed_uri.hostname}",
4141
collection=path[0],
4242
name=path[1],
4343
version=path[2] if len(path) == 3 else None,
@@ -47,8 +47,7 @@ def parse_vault_id(url):
4747
BackupLocation = namedtuple("BackupLocation", ["container_url", "folder_name"])
4848

4949

50-
def parse_folder_url(folder_url):
51-
# type: (str) -> BackupLocation
50+
def parse_folder_url(folder_url: str) -> "BackupLocation":
5251
"""Parse the blob container URL and folder name from a backup's blob storage URL.
5352
5453
For example, https://<account>.blob.core.windows.net/backup/mhsm-account-2020090117323313 parses to
@@ -66,7 +65,7 @@ def parse_folder_url(folder_url):
6665
folder_name = stripped_path[len(container) + 1 :]
6766

6867
# this intentionally discards any SAS token in the URL--methods require the SAS token as a separate parameter
69-
container_url = "{}://{}/{}".format(parsed.scheme, parsed.netloc, container)
68+
container_url = f"{parsed.scheme}://{parsed.netloc}/{container}"
7069

7170
return BackupLocation(container_url, folder_name)
7271
except: # pylint:disable=broad-except

sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_challenge_auth_policy.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
class AsyncChallengeAuthPolicy(AsyncBearerTokenCredentialPolicy):
3434
"""policy for handling HTTP authentication challenges"""
3535

36-
def __init__(self, credential: "AsyncTokenCredential", *scopes: str, **kwargs: "Any") -> None:
36+
def __init__(self, credential: "AsyncTokenCredential", *scopes: str, **kwargs) -> None:
3737
super().__init__(credential, *scopes, **kwargs)
3838
self._credential = credential
3939
self._token = None # type: Optional[AccessToken]
@@ -50,7 +50,7 @@ async def on_request(self, request: "PipelineRequest") -> None:
5050
self._token = await self._credential.get_token(scope, tenant_id=challenge.tenant_id)
5151

5252
# ignore mypy's warning -- although self._token is Optional, get_token raises when it fails to get a token
53-
request.http_request.headers["Authorization"] = "Bearer {}".format(self._token.token) # type: ignore
53+
request.http_request.headers["Authorization"] = f"Bearer {self._token.token}" # type: ignore
5454
return
5555

5656
# else: discover authentication information by eliciting a challenge from Key Vault. Remove any request data,

sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121

2222
class AsyncKeyVaultClientBase(object):
23-
def __init__(self, vault_url: str, credential: "AsyncTokenCredential", **kwargs: "Any") -> None:
23+
def __init__(self, vault_url: str, credential: "AsyncTokenCredential", **kwargs) -> None:
2424
if not credential:
2525
raise ValueError(
2626
"credential should be an object supporting the AsyncTokenCredential protocol, "
@@ -63,8 +63,8 @@ def __init__(self, vault_url: str, credential: "AsyncTokenCredential", **kwargs:
6363
self._models = _KeyVaultClient.models(api_version=api_version)
6464
except ValueError:
6565
raise NotImplementedError(
66-
"This package doesn't support API version '{}'. ".format(api_version)
67-
+ "Supported versions: {}".format(", ".join(v.value for v in ApiVersion))
66+
f"This package doesn't support API version '{api_version}'. "
67+
+ f"Supported versions: {', '.join(v.value for v in ApiVersion)}"
6868
)
6969

7070
@property

sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/challenge_auth_policy.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,15 @@
3535
from azure.core.pipeline import PipelineResponse
3636

3737

38-
def _enforce_tls(request):
39-
# type: (PipelineRequest) -> None
38+
def _enforce_tls(request: PipelineRequest) -> None:
4039
if not request.http_request.url.lower().startswith("https"):
4140
raise ServiceRequestError(
4241
"Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."
4342
)
4443

4544

46-
def _update_challenge(request, challenger):
47-
# type: (PipelineRequest, PipelineResponse) -> HttpChallenge
48-
"""parse challenge from challenger, cache it, return it"""
45+
def _update_challenge(request: PipelineRequest, challenger: "PipelineResponse") -> HttpChallenge:
46+
"""Parse challenge from challenger, cache it, return it"""
4947

5048
challenge = HttpChallenge(
5149
request.http_request.url,
@@ -57,17 +55,15 @@ def _update_challenge(request, challenger):
5755

5856

5957
class ChallengeAuthPolicy(BearerTokenCredentialPolicy):
60-
"""policy for handling HTTP authentication challenges"""
58+
"""Policy for handling HTTP authentication challenges"""
6159

62-
def __init__(self, credential, *scopes, **kwargs):
63-
# type: (TokenCredential, *str, **Any) -> None
60+
def __init__(self, credential: "TokenCredential", *scopes: str, **kwargs) -> None:
6461
super(ChallengeAuthPolicy, self).__init__(credential, *scopes, **kwargs)
6562
self._credential = credential
6663
self._token = None # type: Optional[AccessToken]
6764
self._verify_challenge_resource = kwargs.pop("verify_challenge_resource", True)
6865

69-
def on_request(self, request):
70-
# type: (PipelineRequest) -> None
66+
def on_request(self, request: PipelineRequest) -> None:
7167
_enforce_tls(request)
7268
challenge = ChallengeCache.get_challenge_for_url(request.http_request.url)
7369
if challenge:
@@ -78,7 +74,7 @@ def on_request(self, request):
7874
self._token = self._credential.get_token(scope, tenant_id=challenge.tenant_id)
7975

8076
# ignore mypy's warning -- although self._token is Optional, get_token raises when it fails to get a token
81-
request.http_request.headers["Authorization"] = "Bearer {}".format(self._token.token) # type: ignore
77+
request.http_request.headers["Authorization"] = f"Bearer {self._token.token}" # type: ignore
8278
return
8379

8480
# else: discover authentication information by eliciting a challenge from Key Vault. Remove any request data,
@@ -90,8 +86,7 @@ def on_request(self, request):
9086
request.http_request.set_json_body(None)
9187
request.http_request.headers["Content-Length"] = "0"
9288

93-
def on_challenge(self, request, response):
94-
# type: (PipelineRequest, PipelineResponse) -> bool
89+
def on_challenge(self, request: PipelineRequest, response: "PipelineResponse") -> bool:
9590
try:
9691
challenge = _update_challenge(request, response)
9792
# azure-identity credentials require an AADv2 scope but the challenge may specify an AADv1 resource
@@ -119,6 +114,5 @@ def on_challenge(self, request, response):
119114
return True
120115

121116
@property
122-
def _need_new_token(self):
123-
# type: () -> bool
117+
def _need_new_token(self) -> bool:
124118
return not self._token or self._token.expires_on - time.time() < 300

0 commit comments

Comments
 (0)