Skip to content

Commit 2a0dd0e

Browse files
authored
[storage-queue] Modernized strings (Azure#25901)
1 parent d5f14cd commit 2a0dd0e

28 files changed

+811
-620
lines changed

sdk/storage/azure-storage-queue/azure/storage/queue/_deserialize.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,11 @@ def deserialize_queue_creation(response, obj, headers):
3030
if response.status_code == 204:
3131
error_code = StorageErrorCode.queue_already_exists
3232
error = ResourceExistsError(
33-
message="Queue already exists\nRequestId:{}\nTime:{}\nErrorCode:{}".format(
34-
headers['x-ms-request-id'],
35-
headers['Date'],
36-
error_code
37-
),
33+
message=(
34+
"Queue already exists\n"
35+
f"RequestId:{headers['x-ms-request-id']}\n"
36+
f"Time:{headers['Date']}\n"
37+
f"ErrorCode:{error_code}"),
3838
response=response)
3939
error.error_code = error_code
4040
error.additional_info = {}

sdk/storage/azure-storage-queue/azure/storage/queue/_encryption.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242
def _validate_not_none(param_name, param):
4343
if param is None:
44-
raise ValueError('{0} should not be None.'.format(param_name))
44+
raise ValueError(f'{param_name} should not be None.')
4545

4646

4747
def _validate_key_encryption_key_wrap(kek):

sdk/storage/azure-storage-queue/azure/storage/queue/_models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class QueueAnalyticsLogging(GeneratedLogging):
3232
"""
3333

3434
def __init__(self, **kwargs):
35-
self.version = kwargs.get('version', u'1.0')
35+
self.version = kwargs.get('version', '1.0')
3636
self.delete = kwargs.get('delete', False)
3737
self.read = kwargs.get('read', False)
3838
self.write = kwargs.get('write', False)
@@ -65,7 +65,7 @@ class Metrics(GeneratedMetrics):
6565
"""
6666

6767
def __init__(self, **kwargs):
68-
self.version = kwargs.get('version', u'1.0')
68+
self.version = kwargs.get('version', '1.0')
6969
self.enabled = kwargs.get('enabled', False)
7070
self.include_apis = kwargs.get('include_apis')
7171
self.retention_policy = kwargs.get('retention_policy') or RetentionPolicy()

sdk/storage/azure-storage-queue/azure/storage/queue/_queue_client.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def __init__(
9292
if not queue_name:
9393
raise ValueError("Please specify a queue name.")
9494
if not parsed_url.netloc:
95-
raise ValueError("Invalid URL: {}".format(parsed_url))
95+
raise ValueError(f"Invalid URL: {parsed_url}")
9696

9797
_, sas_token = parse_query(parsed_url.query)
9898
if not sas_token and not credential:
@@ -115,11 +115,9 @@ def _format_url(self, hostname):
115115
queue_name = self.queue_name
116116
if isinstance(queue_name, six.text_type):
117117
queue_name = queue_name.encode('UTF-8')
118-
return "{}://{}/{}{}".format(
119-
self.scheme,
120-
hostname,
121-
quote(queue_name),
122-
self._query_str)
118+
return (
119+
f"{self.scheme}://{hostname}"
120+
f"/{quote(queue_name)}{self._query_str}")
123121

124122
@classmethod
125123
def from_queue_url(cls,
@@ -151,17 +149,15 @@ def from_queue_url(cls,
151149
parsed_url = urlparse(queue_url.rstrip('/'))
152150

153151
if not parsed_url.netloc:
154-
raise ValueError("Invalid URL: {}".format(queue_url))
152+
raise ValueError(f"Invalid URL: {queue_url}")
155153

156154
queue_path = parsed_url.path.lstrip('/').split('/')
157155
account_path = ""
158156
if len(queue_path) > 1:
159157
account_path = "/" + "/".join(queue_path[:-1])
160-
account_url = "{}://{}{}?{}".format(
161-
parsed_url.scheme,
162-
parsed_url.netloc.rstrip('/'),
163-
account_path,
164-
parsed_url.query)
158+
account_url = (
159+
f"{parsed_url.scheme}://{parsed_url.netloc.rstrip('/')}"
160+
f"{account_path}?{parsed_url.query}")
165161
queue_name = unquote(queue_path[-1])
166162
if not queue_name:
167163
raise ValueError("Invalid URL. Please provide a URL with a valid queue name")

sdk/storage/azure-storage-queue/azure/storage/queue/_queue_service_client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def __init__(
9999
raise ValueError("Account URL must be a string.")
100100
parsed_url = urlparse(account_url.rstrip('/'))
101101
if not parsed_url.netloc:
102-
raise ValueError("Invalid URL: {}".format(account_url))
102+
raise ValueError(f"Invalid URL: {account_url}")
103103

104104
_, sas_token = parse_query(parsed_url.query)
105105
if not sas_token and not credential:
@@ -114,7 +114,7 @@ def _format_url(self, hostname):
114114
"""Format the endpoint URL according to the current location
115115
mode hostname.
116116
"""
117-
return "{}://{}/{}".format(self.scheme, hostname, self._query_str)
117+
return f"{self.scheme}://{hostname}/{self._query_str}"
118118

119119
@classmethod
120120
def from_connection_string(

sdk/storage/azure-storage-queue/azure/storage/queue/_serialize.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,5 @@ def get_api_version(kwargs):
2424
api_version = kwargs.get('api_version', None)
2525
if api_version and api_version not in _SUPPORTED_API_VERSIONS:
2626
versions = '\n'.join(_SUPPORTED_API_VERSIONS)
27-
raise ValueError("Unsupported API version '{}'. Please select from:\n{}".format(api_version, versions))
27+
raise ValueError(f"Unsupported API version '{api_version}'. Please select from:\n{versions}")
2828
return api_version or _SUPPORTED_API_VERSIONS[-1]

sdk/storage/azure-storage-queue/azure/storage/queue/_shared/authentication.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
# --------------------------------------------------------------------------
66

77
import logging
8-
import sys
98

109
try:
1110
from urllib.parse import urlparse, unquote
@@ -38,15 +37,7 @@ def _wrap_exception(ex, desired_type):
3837
msg = ""
3938
if ex.args:
4039
msg = ex.args[0]
41-
if sys.version_info >= (3,):
42-
# Automatic chaining in Python 3 means we keep the trace
43-
return desired_type(msg)
44-
# There isn't a good solution in 2 for keeping the stack trace
45-
# in general, or that will not result in an error in 3
46-
# However, we can keep the previous error type and message
47-
# TODO: In the future we will log the trace
48-
return desired_type('{}: {}'.format(ex.__class__.__name__, msg))
49-
40+
return desired_type(msg)
5041

5142
class AzureSigningError(ClientAuthenticationError):
5243
"""

sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client.py

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,9 @@ def __init__(
8080
self.scheme = parsed_url.scheme
8181

8282
if service not in ["blob", "queue", "file-share", "dfs"]:
83-
raise ValueError("Invalid service: {}".format(service))
83+
raise ValueError(f"Invalid service: {service}")
8484
service_name = service.split('-')[0]
85-
account = parsed_url.netloc.split(".{}.core.".format(service_name))
85+
account = parsed_url.netloc.split(f".{service_name}.core.")
8686

8787
self.account_name = account[0] if len(account) > 1 else None
8888
if not self.account_name and parsed_url.netloc.startswith("localhost") \
@@ -96,8 +96,7 @@ def __init__(
9696
secondary_hostname = None
9797
if hasattr(self.credential, "account_name"):
9898
self.account_name = self.credential.account_name
99-
secondary_hostname = "{}-secondary.{}.{}".format(
100-
self.credential.account_name, service_name, SERVICE_HOST_BASE)
99+
secondary_hostname = f"{self.credential.account_name}-secondary.{service_name}.{SERVICE_HOST_BASE}"
101100

102101
if not self._hosts:
103102
if len(account) > 1:
@@ -189,7 +188,7 @@ def location_mode(self, value):
189188
self._location_mode = value
190189
self._client._config.url = self.url # pylint: disable=protected-access
191190
else:
192-
raise ValueError("No host URL for location mode: {}".format(value))
191+
raise ValueError(f"No host URL for location mode: {value}")
193192

194193
@property
195194
def api_version(self):
@@ -202,9 +201,9 @@ def api_version(self):
202201
def _format_query_string(self, sas_token, credential, snapshot=None, share_snapshot=None):
203202
query_str = "?"
204203
if snapshot:
205-
query_str += "snapshot={}&".format(self.snapshot)
204+
query_str += f"snapshot={self.snapshot}&"
206205
if share_snapshot:
207-
query_str += "sharesnapshot={}&".format(self.snapshot)
206+
query_str += f"sharesnapshot={self.snapshot}&"
208207
if sas_token and isinstance(credential, AzureSasCredential):
209208
raise ValueError(
210209
"You cannot use AzureSasCredential when the resource URI also contains a Shared Access Signature.")
@@ -225,7 +224,7 @@ def _create_pipeline(self, credential, **kwargs):
225224
elif isinstance(credential, AzureSasCredential):
226225
self._credential_policy = AzureSasCredentialPolicy(credential)
227226
elif credential is not None:
228-
raise TypeError("Unsupported credential: {}".format(credential))
227+
raise TypeError(f"Unsupported credential: {credential}")
229228

230229
config = kwargs.get("_configuration") or create_configuration(**kwargs)
231230
if kwargs.get("_pipeline"):
@@ -268,13 +267,10 @@ def _batch_send(
268267
batch_id = str(uuid.uuid1())
269268

270269
request = self._client._client.post( # pylint: disable=protected-access
271-
url='{}://{}/{}?{}comp=batch{}{}'.format(
272-
self.scheme,
273-
self.primary_hostname,
274-
kwargs.pop('path', ""),
275-
kwargs.pop('restype', ""),
276-
kwargs.pop('sas', ""),
277-
kwargs.pop('timeout', "")
270+
url=(
271+
f'{self.scheme}://{self.primary_hostname}/'
272+
f"{kwargs.pop('path', '')}?{kwargs.pop('restype', '')}"
273+
f"comp=batch{kwargs.pop('sas', '')}{kwargs.pop('timeout', '')}"
278274
),
279275
headers={
280276
'x-ms-version': self.api_version,
@@ -383,22 +379,22 @@ def parse_connection_str(conn_str, credential, service):
383379
if endpoints["secondary"] in conn_settings:
384380
raise ValueError("Connection string specifies only secondary endpoint.")
385381
try:
386-
primary = "{}://{}.{}.{}".format(
387-
conn_settings["DEFAULTENDPOINTSPROTOCOL"],
388-
conn_settings["ACCOUNTNAME"],
389-
service,
390-
conn_settings["ENDPOINTSUFFIX"],
382+
primary =(
383+
f"{conn_settings['DEFAULTENDPOINTSPROTOCOL']}://"
384+
f"{conn_settings['ACCOUNTNAME']}.{service}.{conn_settings['ENDPOINTSUFFIX']}"
391385
)
392-
secondary = "{}-secondary.{}.{}".format(
393-
conn_settings["ACCOUNTNAME"], service, conn_settings["ENDPOINTSUFFIX"]
386+
secondary = (
387+
f"{conn_settings['ACCOUNTNAME']}-secondary."
388+
f"{service}.{conn_settings['ENDPOINTSUFFIX']}"
394389
)
395390
except KeyError:
396391
pass
397392

398393
if not primary:
399394
try:
400-
primary = "https://{}.{}.{}".format(
401-
conn_settings["ACCOUNTNAME"], service, conn_settings.get("ENDPOINTSUFFIX", SERVICE_HOST_BASE)
395+
primary = (
396+
f"https://{conn_settings['ACCOUNTNAME']}."
397+
f"{service}.{conn_settings.get('ENDPOINTSUFFIX', SERVICE_HOST_BASE)}"
402398
)
403399
except KeyError:
404400
raise ValueError("Connection string missing required connection details.")
@@ -414,7 +410,7 @@ def create_configuration(**kwargs):
414410
config = Configuration(**kwargs)
415411
config.headers_policy = StorageHeadersPolicy(**kwargs)
416412
config.user_agent_policy = UserAgentPolicy(
417-
sdk_moniker="storage-{}/{}".format(kwargs.pop('storage_sdk'), VERSION), **kwargs)
413+
sdk_moniker=f"storage-{kwargs.pop('storage_sdk')}/{VERSION}", **kwargs)
418414
config.retry_policy = kwargs.get("retry_policy") or ExponentialRetry(**kwargs)
419415
config.logging_policy = StorageLoggingPolicy(**kwargs)
420416
config.proxy_policy = ProxyPolicy(**kwargs)
@@ -446,7 +442,7 @@ def create_configuration(**kwargs):
446442
def parse_query(query_str):
447443
sas_values = QueryStringConstants.to_list()
448444
parsed_query = {k: v[0] for k, v in parse_qs(query_str).items()}
449-
sas_params = ["{}={}".format(k, quote(v, safe='')) for k, v in parsed_query.items() if k in sas_values]
445+
sas_params = [f"{k}={quote(v, safe='')}" for k, v in parsed_query.items() if k in sas_values]
450446
sas_token = None
451447
if sas_params:
452448
sas_token = "&".join(sas_params)

sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client_async.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def _create_pipeline(self, credential, **kwargs):
7575
elif isinstance(credential, AzureSasCredential):
7676
self._credential_policy = AzureSasCredentialPolicy(credential)
7777
elif credential is not None:
78-
raise TypeError("Unsupported credential: {}".format(credential))
78+
raise TypeError(f"Unsupported credential: {credential}")
7979
config = kwargs.get('_configuration') or create_configuration(**kwargs)
8080
if kwargs.get('_pipeline'):
8181
return config, kwargs['_pipeline']
@@ -118,7 +118,7 @@ async def _batch_send(
118118
# Pop it here, so requests doesn't feel bad about additional kwarg
119119
raise_on_any_failure = kwargs.pop("raise_on_any_failure", True)
120120
request = self._client._client.post( # pylint: disable=protected-access
121-
url='https://{}/?comp=batch'.format(self.primary_hostname),
121+
url=f'https://{self.primary_hostname}/?comp=batch',
122122
headers={
123123
'x-ms-version': self.api_version
124124
}

sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def on_request(self, request):
179179
# Lock retries to the specific location
180180
request.context.options['retry_to_secondary'] = False
181181
if use_location not in self.hosts:
182-
raise ValueError("Attempting to use undefined host location {}".format(use_location))
182+
raise ValueError(f"Attempting to use undefined host location {use_location}")
183183
if use_location != location_mode:
184184
# Update request URL to use the specified location
185185
updated = parsed_url._replace(netloc=self.hosts[use_location])
@@ -379,9 +379,9 @@ def on_response(self, request, response):
379379
computed_md5 = request.context.get('validate_content_md5') or \
380380
encode_base64(StorageContentValidation.get_content_md5(response.http_response.body()))
381381
if response.http_response.headers['content-md5'] != computed_md5:
382-
raise AzureError(
383-
'MD5 mismatch. Expected value is \'{0}\', computed value is \'{1}\'.'.format(
384-
response.http_response.headers['content-md5'], computed_md5),
382+
raise AzureError((
383+
f"MD5 mismatch. Expected value is '{response.http_response.headers['content-md5']}', "
384+
f"computed value is '{computed_md5}'."),
385385
response=response.http_response
386386
)
387387

0 commit comments

Comments
 (0)