diff --git a/sdk/storage/azure-storage-extensions/CHANGELOG.md b/sdk/storage/azure-storage-extensions/CHANGELOG.md index 39fe92420296..5fcc28e80e09 100644 --- a/sdk/storage/azure-storage-extensions/CHANGELOG.md +++ b/sdk/storage/azure-storage-extensions/CHANGELOG.md @@ -3,3 +3,7 @@ ## 0.1.0 (Unreleased) Initial release. + +### Other Changes + +- Minimum supported Python version is now 3.10. diff --git a/sdk/storage/azure-storage-extensions/pyproject.toml b/sdk/storage/azure-storage-extensions/pyproject.toml index 3da29b9f50da..f4591da73f1c 100644 --- a/sdk/storage/azure-storage-extensions/pyproject.toml +++ b/sdk/storage/azure-storage-extensions/pyproject.toml @@ -17,7 +17,7 @@ suppressed_skip_warnings = ["*"] requires = ["setuptools", "wheel"] [tool.cibuildwheel] -build = ["cp39*", "pp310*", "pp311*"] +build = ["cp310*", "pp310*", "pp311*"] test-requires = "pytest" test-command = "pytest {project}/tests" test-skip = "*-macosx_arm64" diff --git a/sdk/storage/azure-storage-extensions/setup.py b/sdk/storage/azure-storage-extensions/setup.py index 1c0cfebe2b38..b0457001240d 100644 --- a/sdk/storage/azure-storage-extensions/setup.py +++ b/sdk/storage/azure-storage-extensions/setup.py @@ -41,7 +41,6 @@ def get_tag(self): 'Programming Language :: Python', "Programming Language :: Python :: 3 :: Only", 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', @@ -50,7 +49,7 @@ def get_tag(self): 'License :: OSI Approved :: MIT License', ], zip_safe=False, - python_requires=">=3.9", + python_requires=">=3.10", ext_package='azure.storage.extensions', ext_modules=[ Extension( diff --git a/sdk/storage/azure-storage-queue/MANIFEST.in b/sdk/storage/azure-storage-queue/MANIFEST.in index f2919ebac602..8e7ae2ff16fb 100644 --- a/sdk/storage/azure-storage-queue/MANIFEST.in +++ b/sdk/storage/azure-storage-queue/MANIFEST.in @@ -1,7 +1,7 @@ include *.md -include azure/__init__.py -include azure/storage/__init__.py include LICENSE +include azure/storage/queue/py.typed recursive-include tests *.py recursive-include samples *.py *.md -include azure/storage/queue/py.typed +include azure/__init__.py +include azure/storage/__init__.py diff --git a/sdk/storage/azure-storage-queue/_metadata.json b/sdk/storage/azure-storage-queue/_metadata.json new file mode 100644 index 000000000000..722c39b95657 --- /dev/null +++ b/sdk/storage/azure-storage-queue/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersion": "2026-04-06", + "apiVersions": { + "Storage.Queues": "2026-04-06" + } +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/apiview-properties.json b/sdk/storage/azure-storage-queue/apiview-properties.json new file mode 100644 index 000000000000..056dcf5fc299 --- /dev/null +++ b/sdk/storage/azure-storage-queue/apiview-properties.json @@ -0,0 +1,64 @@ +{ + "CrossLanguagePackageId": "Storage.Queues", + "CrossLanguageDefinitionId": { + "azure.storage.queue.models.AccessPolicy": "Storage.Queues.AccessPolicy", + "azure.storage.queue.models.CorsRule": "Storage.Queues.CorsRule", + "azure.storage.queue.models.Error": "Storage.Queues.Error", + "azure.storage.queue.models.GeoReplication": "Storage.Queues.GeoReplication", + "azure.storage.queue.models.KeyInfo": "Storage.Queues.KeyInfo", + "azure.storage.queue.models.ListOfSentMessage": "Storage.Queues.ListOfSentMessage", + "azure.storage.queue.models.ListQueuesResponse": "Storage.Queues.ListQueuesResponse", + "azure.storage.queue.models.Logging": "Storage.Queues.Logging", + "azure.storage.queue.models.Metrics": "Storage.Queues.Metrics", + "azure.storage.queue.models.PeekedMessage": "Storage.Queues.PeekedMessage", + "azure.storage.queue.models.PeekedMessages": "Storage.Queues.PeekedMessages", + "azure.storage.queue.models.QueueItem": "Storage.Queues.QueueItem", + "azure.storage.queue.models.QueueMessage": "Storage.Queues.QueueMessage", + "azure.storage.queue.models.QueueServiceProperties": "Storage.Queues.QueueServiceProperties", + "azure.storage.queue.models.QueueServiceStats": "Storage.Queues.QueueServiceStats", + "azure.storage.queue.models.ReceivedMessage": "Storage.Queues.ReceivedMessage", + "azure.storage.queue.models.ReceivedMessages": "Storage.Queues.ReceivedMessages", + "azure.storage.queue.models.RetentionPolicy": "Storage.Queues.RetentionPolicy", + "azure.storage.queue.models.SentMessage": "Storage.Queues.SentMessage", + "azure.storage.queue.models.SignedIdentifier": "Storage.Queues.SignedIdentifier", + "azure.storage.queue.models.SignedIdentifiers": "Storage.Queues.SignedIdentifiers", + "azure.storage.queue.models.UserDelegationKey": "Storage.Queues.UserDelegationKey", + "azure.storage.queue.models.StorageErrorCode": "Storage.Queues.StorageErrorCode", + "azure.storage.queue.models.GeoReplicationStatus": "Storage.Queues.GeoReplicationStatus", + "azure.storage.queue.models.ListQueuesIncludeType": "Storage.Queues.ListQueuesIncludeType", + "azure.storage.queue.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", + "azure.storage.queue.aio.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", + "azure.storage.queue.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", + "azure.storage.queue.aio.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", + "azure.storage.queue.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", + "azure.storage.queue.aio.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", + "azure.storage.queue.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", + "azure.storage.queue.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", + "azure.storage.queue.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", + "azure.storage.queue.aio.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", + "azure.storage.queue.operations.QueueOperations.create": "Storage.Queues.Queue.create", + "azure.storage.queue.aio.operations.QueueOperations.create": "Storage.Queues.Queue.create", + "azure.storage.queue.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", + "azure.storage.queue.aio.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", + "azure.storage.queue.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", + "azure.storage.queue.aio.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", + "azure.storage.queue.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", + "azure.storage.queue.aio.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", + "azure.storage.queue.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", + "azure.storage.queue.aio.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", + "azure.storage.queue.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", + "azure.storage.queue.aio.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", + "azure.storage.queue.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", + "azure.storage.queue.aio.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", + "azure.storage.queue.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", + "azure.storage.queue.aio.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", + "azure.storage.queue.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", + "azure.storage.queue.aio.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", + "azure.storage.queue.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", + "azure.storage.queue.aio.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", + "azure.storage.queue.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", + "azure.storage.queue.aio.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", + "azure.storage.queue.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage", + "azure.storage.queue.aio.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage" + } +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py index a743737977f3..0fe6e78452f5 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,10 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._azure_queue_storage import AzureQueueStorage # type: ignore +from ._client import QueuesClient # type: ignore +from ._version import VERSION + +__version__ = VERSION try: from ._patch import __all__ as _patch_all @@ -22,7 +25,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureQueueStorage", + "QueuesClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_azure_queue_storage.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py similarity index 60% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_azure_queue_storage.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py index 688769fac8c3..2335c04700ae 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_azure_queue_storage.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py @@ -2,53 +2,47 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import AzureQueueStorageConfiguration +from ._configuration import QueuesClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import ( - MessageIdOperations, - MessagesOperations, - QueueOperations, - ServiceOperations, -) +from .operations import QueueOperations, ServiceOperations +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class AzureQueueStorage: # pylint: disable=client-accepts-api-version-keyword - """AzureQueueStorage. + +class QueuesClient: # pylint: disable=client-accepts-api-version-keyword + """QueuesClient. :ivar service: ServiceOperations operations :vartype service: azure.storage.queue.operations.ServiceOperations :ivar queue: QueueOperations operations :vartype queue: azure.storage.queue.operations.QueueOperations - :ivar messages: MessagesOperations operations - :vartype messages: azure.storage.queue.operations.MessagesOperations - :ivar message_id: MessageIdOperations operations - :vartype message_id: azure.storage.queue.operations.MessageIdOperations - :param url: The URL of the service account, queue or message that is the target of the desired - operation. Required. + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. :type url: str - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str - :param base_url: Service URL. Required. Default value is "". - :type base_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, url: str, version: str, base_url: str = "", **kwargs: Any - ) -> None: - self._config = AzureQueueStorageConfiguration(url=url, version=version, **kwargs) + def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{url}" + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -64,27 +58,24 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._config.custom_hook_policy, self._config.logging_policy, policies.DistributedTracingPolicy(**kwargs), - (policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: PipelineClient = PipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) - self.messages = MessagesOperations(self._client, self._config, self._serialize, self._deserialize) - self.message_id = MessageIdOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -97,7 +88,11 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py index 04adef0da253..e53f7601f7a3 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py @@ -2,39 +2,50 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import Any, TYPE_CHECKING from azure.core.pipeline import policies -VERSION = "unknown" +from ._version import VERSION +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class AzureQueueStorageConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for AzureQueueStorage. + +class QueuesClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for QueuesClient. Note that all parameters used to create this instance are saved as instance attributes. - :param url: The URL of the service account, queue or message that is the target of the desired - operation. Required. + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. :type url: str - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__(self, url: str, version: str, **kwargs: Any) -> None: + def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: + version: str = kwargs.pop("version", "2026-04-06") + if url is None: raise ValueError("Parameter 'url' must not be None.") - if version is None: - raise ValueError("Parameter 'version' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") self.url = url + self.credential = credential self.version = version - kwargs.setdefault("sdk_moniker", "azurequeuestorage/{}".format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "storage-queue/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -48,3 +59,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py index 4688ca7f8ac2..c079cad7a525 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py @@ -1,33 +1,82 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, Optional, TYPE_CHECKING + +from azure.core import PipelineClient + +from ._configuration import QueuesClientConfiguration as QueuesClientConfigurationInternal +from ._utils.serialization import Deserializer, Serializer +from .operations import QueueOperations, ServiceOperations +from ._client import QueuesClient as QueuesClientInternal +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class QueuesClientConfiguration(QueuesClientConfigurationInternal): + """Configuration for QueuesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. + :type url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str + """ + + def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **kwargs: Any) -> None: + version: str = kwargs.pop("version", "2026-04-06") + + if url is None: + raise ValueError("Parameter 'url' must not be None.") + + self.url = url + self.credential = credential + self.version = version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "storage-queue/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + +class QueuesClient(QueuesClientInternal): + """QueuesClient that supports being instantiated with a pre-built pipeline.""" + + def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **kwargs: Any) -> None: + _pipeline = kwargs.pop("pipeline", None) + if _pipeline is not None: + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) + self._client: PipelineClient = PipelineClient(base_url="{url}", pipeline=_pipeline) + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) + else: + super().__init__(url, credential, **kwargs) + + +__all__: list[str] = ["QueuesClient"] def patch_sdk(): - pass + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py index 0af9b28f6607..8026245c2abc 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py @@ -1,6 +1,6 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py new file mode 100644 index 000000000000..eef4e52ed1a0 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py @@ -0,0 +1,1459 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + model_meta = getattr(self, "_xml", {}) + existed_attr_keys: list[str] = [] + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + original_tsp_name=original_tsp_name, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py index adacf7b3e18a..81ec1de5922b 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py @@ -3,7 +3,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -235,17 +235,9 @@ def __init__(self, **kwargs: Any) -> None: self.additional_properties: Optional[dict[str, Any]] = {} for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: - _LOGGER.warning( - "%s is not a known attribute of class %s and will be ignored", - k, - self.__class__, - ) + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning( - "Readonly attribute %s will be ignored in class %s", - k, - self.__class__, - ) + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) else: setattr(self, k, kwargs[k]) @@ -296,11 +288,7 @@ def _create_xml_node(cls): except AttributeError: xml_map = {} - return _create_xml_node( - xml_map.get("name", cls.__name__), - xml_map.get("prefix", None), - xml_map.get("ns", None), - ) + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: """Return the JSON that would be sent to server from this model. @@ -461,11 +449,7 @@ def _classify(cls, response, objects): ) break else: - _LOGGER.warning( - "Discriminator %s is absent or null, use base class %s.", - subtype_key, - cls.__name__, - ) + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) break return cls @@ -932,11 +916,7 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): if isinstance(el, ET.Element): el_node = el else: - el_node = _create_xml_node( - node_name, - xml_desc.get("prefix", None), - xml_desc.get("ns", None), - ) + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) if el is not None: # Otherwise it writes "None" :-p el_node.text = str(el) final_result.append(el_node) @@ -1173,12 +1153,7 @@ def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument if microseconds: microseconds = "." + microseconds date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, - utc.tm_mon, - utc.tm_mday, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec ) return date + microseconds + "Z" except (ValueError, OverflowError) as err: @@ -1454,10 +1429,7 @@ def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for ( - attr, - mapconfig, - ) in data._attribute_map.items(): # pylint: disable=protected-access + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1575,8 +1547,7 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): return self(target_obj, data, content_type=content_type) except: # pylint: disable=bare-except _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", - exc_info=True, + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) return None @@ -1878,11 +1849,7 @@ def deserialize_enum(data, enum_obj): if enum_value.value.lower() == str(data).lower(): return enum_value # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning( - "Deserializer is not able to find %s as valid enum in %s", - data, - enum_obj, - ) + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) return Deserializer.deserialize_unicode(data) @staticmethod diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py new file mode 100644 index 000000000000..be71c81bd282 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py index a743737977f3..e6fceae27b60 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._azure_queue_storage import AzureQueueStorage # type: ignore +from ._client import QueuesClient # type: ignore try: from ._patch import __all__ as _patch_all @@ -22,7 +22,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureQueueStorage", + "QueuesClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_azure_queue_storage.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py similarity index 63% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_azure_queue_storage.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py index 5a2ba62e4064..5ed74d3735ac 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_azure_queue_storage.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py @@ -2,53 +2,47 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models from .._utils.serialization import Deserializer, Serializer -from ._configuration import AzureQueueStorageConfiguration -from .operations import ( - MessageIdOperations, - MessagesOperations, - QueueOperations, - ServiceOperations, -) +from ._configuration import QueuesClientConfiguration +from .operations import QueueOperations, ServiceOperations +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class AzureQueueStorage: # pylint: disable=client-accepts-api-version-keyword - """AzureQueueStorage. + +class QueuesClient: # pylint: disable=client-accepts-api-version-keyword + """QueuesClient. :ivar service: ServiceOperations operations :vartype service: azure.storage.queue.aio.operations.ServiceOperations :ivar queue: QueueOperations operations :vartype queue: azure.storage.queue.aio.operations.QueueOperations - :ivar messages: MessagesOperations operations - :vartype messages: azure.storage.queue.aio.operations.MessagesOperations - :ivar message_id: MessageIdOperations operations - :vartype message_id: azure.storage.queue.aio.operations.MessageIdOperations - :param url: The URL of the service account, queue or message that is the target of the desired - operation. Required. + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. :type url: str - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str - :param base_url: Service URL. Required. Default value is "". - :type base_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, url: str, version: str, base_url: str = "", **kwargs: Any - ) -> None: - self._config = AzureQueueStorageConfiguration(url=url, version=version, **kwargs) + def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{url}" + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -64,21 +58,18 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._config.custom_hook_policy, self._config.logging_policy, policies.DistributedTracingPolicy(**kwargs), - (policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) - self.messages = MessagesOperations(self._client, self._config, self._serialize, self._deserialize) - self.message_id = MessageIdOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -86,7 +77,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -99,7 +90,11 @@ def _send_request( """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py index 1c90497920fe..bb5eb3fe726d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py @@ -2,39 +2,50 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import Any, TYPE_CHECKING from azure.core.pipeline import policies -VERSION = "unknown" +from .._version import VERSION +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class AzureQueueStorageConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for AzureQueueStorage. + +class QueuesClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for QueuesClient. Note that all parameters used to create this instance are saved as instance attributes. - :param url: The URL of the service account, queue or message that is the target of the desired - operation. Required. + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. :type url: str - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__(self, url: str, version: str, **kwargs: Any) -> None: + def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + version: str = kwargs.pop("version", "2026-04-06") + if url is None: raise ValueError("Parameter 'url' must not be None.") - if version is None: - raise ValueError("Parameter 'version' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") self.url = url + self.credential = credential self.version = version - kwargs.setdefault("sdk_moniker", "azurequeuestorage/{}".format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "storage-queue/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -48,3 +59,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py index 4688ca7f8ac2..039588791200 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py @@ -1,33 +1,82 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import Any, Optional, TYPE_CHECKING + +from azure.core import AsyncPipelineClient + +from .._version import VERSION +from ._configuration import QueuesClientConfiguration as QueuesClientConfigurationInternal +from .._utils.serialization import Deserializer, Serializer +from .operations import QueueOperations, ServiceOperations +from ._client import QueuesClient as _QueuesClient + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class QueuesClientConfiguration(QueuesClientConfigurationInternal): + """Configuration for QueuesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. + :type url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str + """ + + def __init__(self, url: str, credential: Optional["AsyncTokenCredential"] = None, **kwargs: Any) -> None: + version: str = kwargs.pop("version", "2026-04-06") + + if url is None: + raise ValueError("Parameter 'url' must not be None.") + + self.url = url + self.credential = credential + self.version = version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "storage-queue/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + +class QueuesClient(_QueuesClient): + """QueuesClient that supports being instantiated with a pre-built pipeline.""" + + def __init__(self, url: str, credential: Optional["AsyncTokenCredential"] = None, **kwargs: Any) -> None: + _pipeline = kwargs.pop("pipeline", None) + if _pipeline is not None: + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url="{url}", pipeline=_pipeline) + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) + else: + super().__init__(url, credential, **kwargs) + + +__all__: list[str] = ["QueuesClient"] def patch_sdk(): - pass + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py index e53a2d5483fd..3fb890991836 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,10 +12,8 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._service_operations import ServiceOperations # type: ignore -from ._queue_operations import QueueOperations # type: ignore -from ._messages_operations import MessagesOperations # type: ignore -from ._message_id_operations import MessageIdOperations # type: ignore +from ._operations import ServiceOperations # type: ignore +from ._operations import QueueOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -24,8 +22,6 @@ __all__ = [ "ServiceOperations", "QueueOperations", - "MessagesOperations", - "MessageIdOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py deleted file mode 100644 index bc26d91d2d9d..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py +++ /dev/null @@ -1,223 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._message_id_operations import ( - build_delete_request, - build_update_request, -) -from .._configuration import AzureQueueStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class MessageIdOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.aio.AzureQueueStorage`'s - :attr:`message_id` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def update( - self, - pop_receipt: str, - visibilitytimeout: int, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - queue_message: Optional[_models.QueueMessage] = None, - **kwargs: Any - ) -> None: - """The Update operation was introduced with version 2011-08-18 of the Queue service API. The - Update Message operation updates the visibility timeout of a message. You can also use this - operation to update the contents of a message. A message must be in a format that can be - included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in - size. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Required. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Delete operation deletes the specified message. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def dequeue( - self, - number_of_messages: Optional[int] = None, - visibilitytimeout: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> list[_models.DequeuedMessageItem]: - """The Dequeue operation retrieves one or more messages from the front of the queue. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Default value is None. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Clear operation deletes all messages from the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.EnqueuedMessage]: - """The Enqueue operation adds a new message to the back of the message queue. A visibility timeout - can also be specified to make the message invisible until the visibility timeout expires. A - message must be in a format that can be included in an XML request with UTF-8 encoding. The - encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size - for previous versions. - - :param queue_message: A Message object which can be stored in a Queue. Required. - :type queue_message: ~azure.storage.queue.models.QueueMessage - :param visibilitytimeout: Optional. If specified, the request must be made using an - x-ms-version of 2011-08-18 or later. If not specified, the default value is 0. Specifies the - new visibility timeout value, in seconds, relative to server time. The new value must be larger - than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message - cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value - smaller than the time-to-live value. Default value is None. - :type visibilitytimeout: int - :param message_time_to_live: Optional. Specifies the time-to-live interval for the message, in - seconds. Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For version - 2017-07-29 or later, the maximum time-to-live can be any positive number, as well as -1 - indicating that the message does not expire. If this parameter is omitted, the default - time-to-live is 7 days. Default value is None. - :type message_time_to_live: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.PeekedMessageItem]: - """The Peek operation retrieves one or more messages from the front of the queue, but does not - alter the visibility of the message. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def set_properties( + self, queue_service_properties: _models.QueueServiceProperties, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Sets properties for a storage account's Queue service endpoint, including properties for + Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :param queue_service_properties: The storage service properties to set. Required. + :type queue_service_properties: ~azure.storage.queue._generated.models.QueueServiceProperties + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(queue_service_properties) + + _request = build_service_set_properties_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceProperties: + """Retrieves properties of a storage account's Queue service, including properties for Storage + Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceProperties. The QueueServiceProperties is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceProperties] = kwargs.pop("cls", None) + + _request = build_service_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceProperties, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceStats: + """Retrieves statistics related to replication for the Queue service. It is only available on the + secondary location endpoint when read-access geo-redundant replication is enabled for the + storage account. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceStats. The QueueServiceStats is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceStats + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceStats] = kwargs.pop("cls", None) + + _request = build_service_get_statistics_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceStats, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_user_delegation_key( + self, key_info: _models.KeyInfo, *, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.UserDelegationKey: + """Retrieves a user delegation key for the Queue service. This is only a valid operation when + using bearer token authentication. + + :param key_info: Key information. Required. + :type key_info: ~azure.storage.queue._generated.models.KeyInfo + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.UserDelegationKey + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) + + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.UserDelegationKey, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_queues( + self, + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, + **kwargs: Any + ) -> _models.ListQueuesResponse: + """returns a list of the queues under the specified account. + + :keyword prefix: Filters the results to return only queues whose name begins with the specified + prefix. Default value is None. + :paramtype prefix: str + :keyword marker: A string value that identifies the portion of the list of queues to be + returned with the next listing operation. The operation returns the NextMarker value within the + response body if the listing operation did not return all queues remaining to be listed with + the current page. The NextMarker value can be used as the value for the marker parameter in a + subsequent call to request the next page of list items. The marker value is opaque to the + client. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of queues to return. If the request does not + specify maxresults, or specifies a value greater than 5000, the server will return up to 5000 + items. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :keyword include: Include this parameter to specify that the queue's metadata be returned as + part of the response body. Default value is None. + :paramtype include: list[str or ~azure.storage.queue.models.ListQueuesIncludeType] + :return: ListQueuesResponse. The ListQueuesResponse is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ListQueuesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListQueuesResponse] = kwargs.pop("cls", None) + + _request = build_service_get_queues_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, + timeout=timeout, + include=include, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListQueuesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class QueueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.queue.aio.QueuesClient`'s + :attr:`queue` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def create(self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any) -> None: + """Creates a new queue under the specified account. If a queue with the same name already exists, + the operation succeeds when the metadata is identical and returns 204; if the metadata differs, + the operation returns 409. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_create_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: + """returns all user-defined metadata and system properties for the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("str", response.headers.get("x-ms-meta")) + response_headers["x-ms-approximate-messages-count"] = self._deserialize( + "int", response.headers.get("x-ms-approximate-messages-count") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def delete(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: + """operation permanently deletes the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def set_metadata( + self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any + ) -> None: + """operation sets one or more user-defined name-value pairs for the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_set_metadata_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.SignedIdentifiers: + """gets the permissions for the specified queue. The permissions indicate whether queue data may + be accessed publicly. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.SignedIdentifiers + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + + _request = build_queue_get_access_policy_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.SignedIdentifiers, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def set_access_policy( + self, queue_acl: Optional[_models.SignedIdentifiers] = None, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """sets the permissions for the specified queue. + + :param queue_acl: The access control list for the queue. Default value is None. + :type queue_acl: ~azure.storage.queue._generated.models.SignedIdentifiers + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_acl else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_acl is not None: + _content = _get_element(queue_acl) + else: + _content = None + + _request = build_queue_set_access_policy_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def receive_messages( + self, + *, + number_of_messages: Optional[int] = None, + visibility_timeout: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any + ) -> _models.ReceivedMessages: + """The Dequeue operation retrieves one or more messages from the front of the queue. + + :keyword number_of_messages: Optional. A nonzero integer value that specifies the number of + messages to + retrieve from the queue, up to a maximum of 32. If fewer are visible, the + visible messages are returned. By default, a single message is retrieved from + the queue with this operation. Default value is None. + :paramtype number_of_messages: int + :keyword visibility_timeout: Specifies the new visibility timeout value, in seconds, relative + to server time. The default value is 30 seconds. A specified value must be larger than or equal + to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions + prior to version 2011-08-18. The visibility timeout of a message can be set to a value later + than the expiry time. Default value is None. + :paramtype visibility_timeout: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: ReceivedMessages. The ReceivedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ReceivedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ReceivedMessages] = kwargs.pop("cls", None) + + _request = build_queue_receive_messages_request( + number_of_messages=number_of_messages, + visibility_timeout=visibility_timeout, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ReceivedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def clear(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: + """The Clear operation deletes all messages from the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_clear_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def send_message( + self, + queue_message: _models.QueueMessage, + *, + visibility_timeout: Optional[int] = None, + message_time_to_live: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any + ) -> _models.ListOfSentMessage: + """The Enqueue operation adds a new message to the back of the message queue. A visibility timeout + can also be specified to make the message invisible until the visibility timeout expires. A + message must be in a format that can be included in an XML request with UTF-8 encoding. The + encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size + for previous versions. + + :param queue_message: A Message object which can be stored in a Queue. Required. + :type queue_message: ~azure.storage.queue._generated.models.QueueMessage + :keyword visibility_timeout: Specifies the new visibility timeout value, in seconds, relative + to server time. The default value is 30 seconds. A specified value must be larger than or equal + to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions + prior to version 2011-08-18. The visibility timeout of a message can be set to a value later + than the expiry time. Default value is None. + :paramtype visibility_timeout: int + :keyword message_time_to_live: Optional. Specifies the time-to-live interval for the message, + in seconds. + Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For + version 2017-07-29 or later, the maximum time-to-live can be any positive + number, as well as -1 indicating that the message does not expire. If this + parameter is omitted, the default time-to-live is 7 days. Default value is None. + :paramtype message_time_to_live: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: ListOfSentMessage. The ListOfSentMessage is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ListOfSentMessage + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.ListOfSentMessage] = kwargs.pop("cls", None) + + _content = _get_element(queue_message) + + _request = build_queue_send_message_request( + visibility_timeout=visibility_timeout, + message_time_to_live=message_time_to_live, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListOfSentMessage, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def peek_messages( + self, *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.PeekedMessages: + """The Peek operation retrieves one or more messages from the front of the queue, but does not + alter the visibility of the message. + + :keyword number_of_messages: Optional. A nonzero integer value that specifies the number of + messages to + retrieve from the queue, up to a maximum of 32. If fewer are visible, the + visible messages are returned. By default, a single message is retrieved from + the queue with this operation. Default value is None. + :paramtype number_of_messages: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: PeekedMessages. The PeekedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.PeekedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PeekedMessages] = kwargs.pop("cls", None) + + _request = build_queue_peek_messages_request( + number_of_messages=number_of_messages, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.PeekedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def update_message( + self, + message_id: str, + queue_message: Optional[_models.QueueMessage] = None, + *, + pop_receipt: str, + visibility_timeout: int, + timeout: Optional[int] = None, + **kwargs: Any + ) -> None: + """The Update operation was introduced with version 2011-08-18 of the Queue service API. The + Update Message operation updates the visibility timeout of a message. You can also use this + operation to update the contents of a message. A message must be in a format that can be + included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in + size. + + :param message_id: The id of the queue message. Required. + :type message_id: str + :param queue_message: A Message object which can be stored in a Queue. Default value is None. + :type queue_message: ~azure.storage.queue._generated.models.QueueMessage + :keyword pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier + call to the Get Messages or Update Message operation. Required. + :paramtype pop_receipt: str + :keyword visibility_timeout: Specifies the new visibility timeout value, in seconds, relative + to server time. The default value is 30 seconds. A specified value must be larger than or equal + to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions + prior to version 2011-08-18. The visibility timeout of a message can be set to a value later + than the expiry time. Required. + :paramtype visibility_timeout: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_message else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_message is not None: + _content = _get_element(queue_message) + else: + _content = None + + _request = build_queue_update_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + visibility_timeout=visibility_timeout, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-popreceipt"] = self._deserialize("str", response.headers.get("x-ms-popreceipt")) + response_headers["x-ms-time-next-visible"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-time-next-visible") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def delete_message( + self, message_id: str, *, pop_receipt: str, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """The Delete operation deletes the specified message. + + :param message_id: The id of the queue message. Required. + :type message_id: str + :keyword pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier + call to the Get Messages or Update Message operation. Required. + :paramtype pop_receipt: str + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py index 2e25743cab74..87676c65a8f0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py @@ -1,17 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_queue_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_queue_operations.py deleted file mode 100644 index 252b7d54f4c5..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_queue_operations.py +++ /dev/null @@ -1,505 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._queue_operations import ( - build_create_request, - build_delete_request, - build_get_access_policy_request, - build_get_properties_request, - build_set_access_policy_request, - build_set_metadata_request, -) -from .._configuration import AzureQueueStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class QueueOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.aio.AzureQueueStorage`'s - :attr:`queue` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def create( - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """creates a new queue under the given account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """operation permanently deletes the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """Retrieves user-defined metadata and queue properties on the specified queue. Metadata is - associated with the queue as name-values pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets user-defined metadata on the specified queue. Metadata is associated with the queue as - name-value pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.SignedIdentifier]: - """returns details about any stored access policies specified on the queue that may be used with - Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets stored access policies for the queue that may be used with Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def set_properties( - self, - storage_service_properties: _models.StorageServiceProperties, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """Sets properties for a storage account's Queue service endpoint, including properties for - Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param storage_service_properties: The StorageService properties. Required. - :type storage_service_properties: ~azure.storage.queue.models.StorageServiceProperties - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceProperties: - """gets the properties of a storage account's Queue service, including properties for Storage - Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceStats: - """Retrieves statistics related to replication for the Queue service. It is only available on the - secondary location endpoint when read-access geo-redundant replication is enabled for the - storage account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.UserDelegationKey: - """Retrieves a user delegation key for the Queue service. This is only a valid operation when - using bearer token authentication. - - :param key_info: Key information. Required. - :type key_info: ~azure.storage.queue.models.KeyInfo - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.ListQueuesSegmentResponse: - """The List Queues Segment operation returns a list of the queues under the specified account. - - :param prefix: Filters the results to return only queues whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param marker: A string value that identifies the portion of the list of queues to be returned - with the next listing operation. The operation returns the NextMarker value within the response - body if the listing operation did not return all queues remaining to be listed with the current - page. The NextMarker value can be used as the value for the marker parameter in a subsequent - call to request the next page of list items. The marker value is opaque to the client. Default - value is None. - :type marker: str - :param maxresults: Specifies the maximum number of queues to return. If the request does not - specify maxresults, or specifies a value greater than 5000, the server will return up to 5000 - items. Note that if the listing operation crosses a partition boundary, then the service will - return a continuation token for retrieving the remainder of the results. For this reason, it is - possible that the service will return fewer results than specified by maxresults, or than the - default of 5000. Default value is None. - :type maxresults: int - :param include: Include this parameter to specify that the queues' metadata be returned as part - of the response body. Default value is None. - :type include: list[str] - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CorsRule(_Model): + """CORS is an HTTP feature that enables a web application running under one domain to access + resources in another domain. Web browsers implement a security restriction known as same-origin + policy that prevents a web page from calling APIs in a different domain; CORS provides a secure + way to allow one domain (the origin domain) to call APIs in another domain. + + :ivar allowed_origins: The allowed origins. Required. + :vartype allowed_origins: str + :ivar allowed_methods: The allowed methods. Required. + :vartype allowed_methods: str + :ivar allowed_headers: The allowed headers. Required. + :vartype allowed_headers: str + :ivar exposed_headers: The exposed headers. Required. + :vartype exposed_headers: str + :ivar max_age_in_seconds: The maximum age in seconds. Required. + :vartype max_age_in_seconds: int + """ + + allowed_origins: str = rest_field( + name="allowedOrigins", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AllowedOrigins", "text": False, "unwrapped": False}, + ) + """The allowed origins. Required.""" + allowed_methods: str = rest_field( + name="allowedMethods", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AllowedMethods", "text": False, "unwrapped": False}, + ) + """The allowed methods. Required.""" + allowed_headers: str = rest_field( + name="allowedHeaders", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AllowedHeaders", "text": False, "unwrapped": False}, + ) + """The allowed headers. Required.""" + exposed_headers: str = rest_field( + name="exposedHeaders", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ExposedHeaders", "text": False, "unwrapped": False}, + ) + """The exposed headers. Required.""" + max_age_in_seconds: int = rest_field( + name="maxAgeInSeconds", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MaxAgeInSeconds", "text": False, "unwrapped": False}, + ) + """The maximum age in seconds. Required.""" + + _xml = {"attribute": False, "name": "CorsRule", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + allowed_origins: str, + allowed_methods: str, + allowed_headers: str, + exposed_headers: str, + max_age_in_seconds: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Error(_Model): + """The error response. + + :ivar code: The error code. Known values are: "AccountAlreadyExists", "AccountBeingCreated", + "AccountIsDisabled", "AuthenticationFailed", "AuthorizationFailure", + "ConditionHeadersNotSupported", "ConditionNotMet", "EmptyMetadataKey", + "InsufficientAccountPermissions", "InternalError", "InvalidAuthenticationInfo", + "InvalidHeaderValue", "InvalidHttpVerb", "InvalidInput", "InvalidMd5", "InvalidMetadata", + "InvalidQueryParameterValue", "InvalidRange", "InvalidResourceName", "InvalidUri", + "InvalidXmlDocument", "InvalidXmlNodeValue", "Md5Mismatch", "MetadataTooLarge", + "MissingContentLengthHeader", "MissingRequiredQueryParameter", "MissingRequiredHeader", + "MissingRequiredXmlNode", "MultipleConditionHeadersNotSupported", "OperationTimedOut", + "OutOfRangeInput", "OutOfRangeQueryParameterValue", "RequestBodyTooLarge", + "ResourceTypeMismatch", "RequestUrlFailedToParse", "ResourceAlreadyExists", "ResourceNotFound", + "ServerBusy", "UnsupportedHeader", "UnsupportedXmlNode", "UnsupportedQueryParameter", + "UnsupportedHttpVerb", "InvalidMarker", "MessageNotFound", "MessageTooLarge", + "PopReceiptMismatch", "QueueAlreadyExists", "QueueBeingDeleted", "QueueDisabled", + "QueueNotEmpty", "QueueNotFound", "AuthorizationSourceIPMismatch", + "AuthorizationProtocolMismatch", "AuthorizationPermissionMismatch", + "AuthorizationServiceMismatch", "AuthorizationResourceTypeMismatch", and + "FeatureVersionMismatch". + :vartype code: str or ~azure.storage.queue.models.StorageErrorCode + :ivar message: The error message. + :vartype message: str + """ + + code: Optional[Union[str, "_models.StorageErrorCode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Code", "text": False, "unwrapped": False}, + ) + """The error code. Known values are: \"AccountAlreadyExists\", \"AccountBeingCreated\", + \"AccountIsDisabled\", \"AuthenticationFailed\", \"AuthorizationFailure\", + \"ConditionHeadersNotSupported\", \"ConditionNotMet\", \"EmptyMetadataKey\", + \"InsufficientAccountPermissions\", \"InternalError\", \"InvalidAuthenticationInfo\", + \"InvalidHeaderValue\", \"InvalidHttpVerb\", \"InvalidInput\", \"InvalidMd5\", + \"InvalidMetadata\", \"InvalidQueryParameterValue\", \"InvalidRange\", \"InvalidResourceName\", + \"InvalidUri\", \"InvalidXmlDocument\", \"InvalidXmlNodeValue\", \"Md5Mismatch\", + \"MetadataTooLarge\", \"MissingContentLengthHeader\", \"MissingRequiredQueryParameter\", + \"MissingRequiredHeader\", \"MissingRequiredXmlNode\", + \"MultipleConditionHeadersNotSupported\", \"OperationTimedOut\", \"OutOfRangeInput\", + \"OutOfRangeQueryParameterValue\", \"RequestBodyTooLarge\", \"ResourceTypeMismatch\", + \"RequestUrlFailedToParse\", \"ResourceAlreadyExists\", \"ResourceNotFound\", \"ServerBusy\", + \"UnsupportedHeader\", \"UnsupportedXmlNode\", \"UnsupportedQueryParameter\", + \"UnsupportedHttpVerb\", \"InvalidMarker\", \"MessageNotFound\", \"MessageTooLarge\", + \"PopReceiptMismatch\", \"QueueAlreadyExists\", \"QueueBeingDeleted\", \"QueueDisabled\", + \"QueueNotEmpty\", \"QueueNotFound\", \"AuthorizationSourceIPMismatch\", + \"AuthorizationProtocolMismatch\", \"AuthorizationPermissionMismatch\", + \"AuthorizationServiceMismatch\", \"AuthorizationResourceTypeMismatch\", and + \"FeatureVersionMismatch\".""" + message: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Message", "text": False, "unwrapped": False}, + ) + """The error message.""" + + _xml = {"attribute": False, "name": "Error", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + code: Optional[Union[str, "_models.StorageErrorCode"]] = None, + message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GeoReplication(_Model): + """Geo-Replication information for the Secondary Storage Service. + + :ivar status: The status of the secondary location. Required. Known values are: "live", + "bootstrap", and "unavailable". + :vartype status: str or ~azure.storage.queue.models.GeoReplicationStatus + :ivar last_sync_time: A GMT date/time value, to the second. All primary writes preceding this + value are guaranteed to be available for read operations at the secondary. Primary writes after + this point in time may or may not be available for reads. Required. + :vartype last_sync_time: ~datetime.datetime + """ + + status: Union[str, "_models.GeoReplicationStatus"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Status", "text": False, "unwrapped": False}, + ) + """The status of the secondary location. Required. Known values are: \"live\", \"bootstrap\", and + \"unavailable\".""" + last_sync_time: datetime.datetime = rest_field( + name="lastSyncTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "LastSyncTime", "text": False, "unwrapped": False}, + ) + """A GMT date/time value, to the second. All primary writes preceding this value are guaranteed to + be available for read operations at the secondary. Primary writes after this point in time may + or may not be available for reads. Required.""" + + _xml = {"attribute": False, "name": "GeoReplication", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + status: Union[str, "_models.GeoReplicationStatus"], + last_sync_time: datetime.datetime, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KeyInfo(_Model): + """Key information for user delegation key. + + :ivar start: The date-time the key is active in ISO 8601 UTC time. + :vartype start: str + :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. + :vartype expiry: str + :ivar delegated_user_tid: The delegated user tenant id in Azure AD. + :vartype delegated_user_tid: str + """ + + start: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + ) + """The date-time the key is active in ISO 8601 UTC time.""" + expiry: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, + ) + """The date-time the key expires in ISO 8601 UTC time. Required.""" + delegated_user_tid: Optional[str] = rest_field( + name="delegatedUserTid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "DelegatedUserTid", "text": False, "unwrapped": False}, + ) + """The delegated user tenant id in Azure AD.""" + + _xml = {"attribute": False, "name": "KeyInfo", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + expiry: str, + start: Optional[str] = None, + delegated_user_tid: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListOfSentMessage(_Model): + """List wrapper for EnqueuedMessage array. + + :ivar items_property: The list of enqueued messages. Required. + :vartype items_property: ~azure.storage.queue._generated.models.SentMessage + """ + + items_property: list["_models.SentMessage"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "QueueMessage", "name": "QueueMessage", "text": False, "unwrapped": True}, + original_tsp_name="items", + ) + """The list of enqueued messages. Required.""" + + _xml = {"attribute": False, "name": "QueueMessagesList", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.SentMessage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListQueuesResponse(_Model): + """The list queue segment response. + + :ivar service_endpoint: The service endpoint. Required. + :vartype service_endpoint: str + :ivar prefix: The prefix of the queues. Required. + :vartype prefix: str + :ivar marker: The marker of the queues. + :vartype marker: str + :ivar max_results: The max results of the queues. Required. + :vartype max_results: int + :ivar queue_items: The queue segment. + :vartype queue_items: ~azure.storage.queue._generated.models.QueueItem + :ivar next_marker: The next marker of the queues. Required. + :vartype next_marker: str + """ + + service_endpoint: str = rest_field( + name="serviceEndpoint", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "ServiceEndpoint", "text": False, "unwrapped": False}, + ) + """The service endpoint. Required.""" + prefix: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Prefix", "text": False, "unwrapped": False}, + ) + """The prefix of the queues. Required.""" + marker: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Marker", "text": False, "unwrapped": False}, + ) + """The marker of the queues.""" + max_results: int = rest_field( + name="maxResults", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MaxResults", "text": False, "unwrapped": False}, + ) + """The max results of the queues. Required.""" + queue_items: Optional[list["_models.QueueItem"]] = rest_field( + name="queueItems", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "Queue", "name": "Queues", "text": False, "unwrapped": False}, + ) + """The queue segment.""" + next_marker: str = rest_field( + name="nextMarker", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + ) + """The next marker of the queues. Required.""" + + _xml = {"attribute": False, "name": "EnumerationResults", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + service_endpoint: str, + prefix: str, + max_results: int, + next_marker: str, + marker: Optional[str] = None, + queue_items: Optional[list["_models.QueueItem"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Logging(_Model): + """Azure Analytics Logging settings. + + :ivar version: The version of the logging properties. Required. + :vartype version: str + :ivar delete: Whether delete operation is logged. Required. + :vartype delete: bool + :ivar read: Whether read operation is logged. Required. + :vartype read: bool + :ivar write: Whether write operation is logged. Required. + :vartype write: bool + :ivar retention_policy: The retention policy of the logs. Required. + :vartype retention_policy: ~azure.storage.queue._generated.models.RetentionPolicy + """ + + version: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + ) + """The version of the logging properties. Required.""" + delete: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Delete", "text": False, "unwrapped": False}, + ) + """Whether delete operation is logged. Required.""" + read: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Read", "text": False, "unwrapped": False}, + ) + """Whether read operation is logged. Required.""" + write: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Write", "text": False, "unwrapped": False}, + ) + """Whether write operation is logged. Required.""" + retention_policy: "_models.RetentionPolicy" = rest_field( + name="retentionPolicy", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "RetentionPolicy", "text": False, "unwrapped": False}, + ) + """The retention policy of the logs. Required.""" + + _xml = {"attribute": False, "name": "Logging", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + version: str, + delete: bool, + read: bool, + write: bool, + retention_policy: "_models.RetentionPolicy", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Metrics(_Model): + """The metrics properties. + + :ivar version: The version of the metrics properties. + :vartype version: str + :ivar enabled: Whether it is enabled. Required. + :vartype enabled: bool + :ivar include_apis: Whether to include API in the metrics. + :vartype include_apis: bool + :ivar retention_policy: The retention policy of the metrics. + :vartype retention_policy: ~azure.storage.queue._generated.models.RetentionPolicy + """ + + version: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + ) + """The version of the metrics properties.""" + enabled: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + ) + """Whether it is enabled. Required.""" + include_apis: Optional[bool] = rest_field( + name="includeApis", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "IncludeAPIs", "text": False, "unwrapped": False}, + ) + """Whether to include API in the metrics.""" + retention_policy: Optional["_models.RetentionPolicy"] = rest_field( + name="retentionPolicy", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "RetentionPolicy", "text": False, "unwrapped": False}, + ) + """The retention policy of the metrics.""" + + _xml = {"attribute": False, "name": "Metrics", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + enabled: bool, + version: Optional[str] = None, + include_apis: Optional[bool] = None, + retention_policy: Optional["_models.RetentionPolicy"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PeekedMessage(_Model): + """The object returned in the QueueMessageList array when calling Peek Messages on a Queue. + + :ivar message_id: The Id of the Message. Required. + :vartype message_id: str + :ivar insertion_time: The time the Message was inserted into the Queue. Required. + :vartype insertion_time: ~datetime.datetime + :ivar expiration_time: The time that the Message will expire and be automatically deleted. + Required. + :vartype expiration_time: ~datetime.datetime + :ivar dequeue_count: The number of times the message has been dequeued. Required. + :vartype dequeue_count: int + :ivar message_text: The content of the Message. Required. + :vartype message_text: str + """ + + message_id: str = rest_field( + name="messageId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, + ) + """The Id of the Message. Required.""" + insertion_time: datetime.datetime = rest_field( + name="insertionTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "InsertionTime", "text": False, "unwrapped": False}, + ) + """The time the Message was inserted into the Queue. Required.""" + expiration_time: datetime.datetime = rest_field( + name="expirationTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "ExpirationTime", "text": False, "unwrapped": False}, + ) + """The time that the Message will expire and be automatically deleted. Required.""" + dequeue_count: int = rest_field( + name="dequeueCount", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "DequeueCount", "text": False, "unwrapped": False}, + ) + """The number of times the message has been dequeued. Required.""" + message_text: str = rest_field( + name="messageText", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MessageText", "text": False, "unwrapped": False}, + ) + """The content of the Message. Required.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_id: str, + insertion_time: datetime.datetime, + expiration_time: datetime.datetime, + dequeue_count: int, + message_text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PeekedMessages(_Model): + """List wrapper for PeekedMessageItem array. + + :ivar items_property: The list of peeked messages. Required. + :vartype items_property: ~azure.storage.queue._generated.models.PeekedMessage + """ + + items_property: list["_models.PeekedMessage"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "QueueMessage", "name": "QueueMessage", "text": False, "unwrapped": True}, + original_tsp_name="items", + ) + """The list of peeked messages. Required.""" + + _xml = {"attribute": False, "name": "QueueMessagesList", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.PeekedMessage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueueItem(_Model): + """An Azure Storage Queue. + + :ivar name: The name of the queue. Required. + :vartype name: str + :ivar metadata: The metadata of the container. + :vartype metadata: dict[str, str] + """ + + name: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Name", "text": False, "unwrapped": False}, + ) + """The name of the queue. Required.""" + metadata: Optional[dict[str, str]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Metadata", "text": False, "unwrapped": False}, + ) + """The metadata of the container.""" + + _xml = {"attribute": False, "name": "Queue", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + name: str, + metadata: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueueMessage(_Model): + """A Message object which can be stored in a Queue. + + :ivar message_text: The content of the message. Required. + :vartype message_text: str + """ + + message_text: str = rest_field( + name="messageText", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MessageText", "text": False, "unwrapped": False}, + ) + """The content of the message. Required.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueueServiceProperties(_Model): + """The service properties. + + :ivar logging: The logging properties. + :vartype logging: ~azure.storage.queue._generated.models.Logging + :ivar hour_metrics: The hour metrics properties. + :vartype hour_metrics: ~azure.storage.queue._generated.models.Metrics + :ivar minute_metrics: The minute metrics properties. + :vartype minute_metrics: ~azure.storage.queue._generated.models.Metrics + :ivar cors: The CORS properties. + :vartype cors: ~azure.storage.queue._generated.models.CorsRule + """ + + logging: Optional["_models.Logging"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Logging", "text": False, "unwrapped": False}, + ) + """The logging properties.""" + hour_metrics: Optional["_models.Metrics"] = rest_field( + name="hourMetrics", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "HourMetrics", "text": False, "unwrapped": False}, + ) + """The hour metrics properties.""" + minute_metrics: Optional["_models.Metrics"] = rest_field( + name="minuteMetrics", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MinuteMetrics", "text": False, "unwrapped": False}, + ) + """The minute metrics properties.""" + cors: Optional[list["_models.CorsRule"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "CorsRule", "name": "Cors", "text": False, "unwrapped": False}, + ) + """The CORS properties.""" + + _xml = {"attribute": False, "name": "StorageServiceProperties", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + logging: Optional["_models.Logging"] = None, + hour_metrics: Optional["_models.Metrics"] = None, + minute_metrics: Optional["_models.Metrics"] = None, + cors: Optional[list["_models.CorsRule"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueueServiceStats(_Model): + """Stats for the storage service. + + :ivar geo_replication: The geo replication stats. + :vartype geo_replication: ~azure.storage.queue._generated.models.GeoReplication + """ + + geo_replication: Optional["_models.GeoReplication"] = rest_field( + name="geoReplication", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "GeoReplication", "text": False, "unwrapped": False}, + ) + """The geo replication stats.""" + + _xml = {"attribute": False, "name": "QueueServiceStats", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + geo_replication: Optional["_models.GeoReplication"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ReceivedMessage(_Model): + """The object returned in the QueueMessageList array when calling Get Messages on a Queue. + + :ivar message_id: The Id of the Message. Required. + :vartype message_id: str + :ivar insertion_time: The time the Message was inserted into the Queue. Required. + :vartype insertion_time: ~datetime.datetime + :ivar expiration_time: The time that the Message will expire and be automatically deleted. + Required. + :vartype expiration_time: ~datetime.datetime + :ivar pop_receipt: This value is required to delete the Message. If deletion fails using this + PopReceipt then the message has been dequeued by another client. Required. + :vartype pop_receipt: str + :ivar time_next_visible: The time that the message will again become visible in the Queue. + Required. + :vartype time_next_visible: ~datetime.datetime + :ivar dequeue_count: The number of times the message has been dequeued. Required. + :vartype dequeue_count: int + :ivar message_text: The content of the message. Required. + :vartype message_text: str + """ + + message_id: str = rest_field( + name="messageId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, + ) + """The Id of the Message. Required.""" + insertion_time: datetime.datetime = rest_field( + name="insertionTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "InsertionTime", "text": False, "unwrapped": False}, + ) + """The time the Message was inserted into the Queue. Required.""" + expiration_time: datetime.datetime = rest_field( + name="expirationTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "ExpirationTime", "text": False, "unwrapped": False}, + ) + """The time that the Message will expire and be automatically deleted. Required.""" + pop_receipt: str = rest_field( + name="popReceipt", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "PopReceipt", "text": False, "unwrapped": False}, + ) + """This value is required to delete the Message. If deletion fails using this PopReceipt then the + message has been dequeued by another client. Required.""" + time_next_visible: datetime.datetime = rest_field( + name="timeNextVisible", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "TimeNextVisible", "text": False, "unwrapped": False}, + ) + """The time that the message will again become visible in the Queue. Required.""" + dequeue_count: int = rest_field( + name="dequeueCount", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "DequeueCount", "text": False, "unwrapped": False}, + ) + """The number of times the message has been dequeued. Required.""" + message_text: str = rest_field( + name="messageText", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MessageText", "text": False, "unwrapped": False}, + ) + """The content of the message. Required.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_id: str, + insertion_time: datetime.datetime, + expiration_time: datetime.datetime, + pop_receipt: str, + time_next_visible: datetime.datetime, + dequeue_count: int, + message_text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ReceivedMessages(_Model): + """List wrapper for DequeuedMessageItem array. + + :ivar items_property: The list of dequeued messages. Required. + :vartype items_property: ~azure.storage.queue._generated.models.ReceivedMessage + """ + + items_property: list["_models.ReceivedMessage"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "QueueMessage", "name": "QueueMessage", "text": False, "unwrapped": True}, + original_tsp_name="items", + ) + """The list of dequeued messages. Required.""" + + _xml = {"attribute": False, "name": "QueueMessagesList", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.ReceivedMessage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RetentionPolicy(_Model): + """The retention policy. + + :ivar enabled: Whether to enable the retention policy. Required. + :vartype enabled: bool + :ivar days: The number of days to retain the logs. + :vartype days: int + """ + + enabled: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + ) + """Whether to enable the retention policy. Required.""" + days: Optional[int] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Days", "text": False, "unwrapped": False}, + ) + """The number of days to retain the logs.""" + + _xml = {"attribute": False, "name": "RetentionPolicy", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + enabled: bool, + days: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SentMessage(_Model): + """The object returned in the QueueMessageList array when calling Put Message on a Queue. + + :ivar message_id: The Id of the Message. Required. + :vartype message_id: str + :ivar insertion_time: The time the Message was inserted into the Queue. Required. + :vartype insertion_time: ~datetime.datetime + :ivar expiration_time: The time that the Message will expire and be automatically deleted. + Required. + :vartype expiration_time: ~datetime.datetime + :ivar pop_receipt: This value is required to delete the Message. If deletion fails using this + PopReceipt then the message has been dequeued by another client. Required. + :vartype pop_receipt: str + :ivar time_next_visible: The time that the message will again become visible in the Queue. + Required. + :vartype time_next_visible: ~datetime.datetime + """ + + message_id: str = rest_field( + name="messageId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, + ) + """The Id of the Message. Required.""" + insertion_time: datetime.datetime = rest_field( + name="insertionTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "InsertionTime", "text": False, "unwrapped": False}, + ) + """The time the Message was inserted into the Queue. Required.""" + expiration_time: datetime.datetime = rest_field( + name="expirationTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "ExpirationTime", "text": False, "unwrapped": False}, + ) + """The time that the Message will expire and be automatically deleted. Required.""" + pop_receipt: str = rest_field( + name="popReceipt", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "PopReceipt", "text": False, "unwrapped": False}, + ) + """This value is required to delete the Message. If deletion fails using this PopReceipt then the + message has been dequeued by another client. Required.""" + time_next_visible: datetime.datetime = rest_field( + name="timeNextVisible", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "TimeNextVisible", "text": False, "unwrapped": False}, + ) + """The time that the message will again become visible in the Queue. Required.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_id: str, + insertion_time: datetime.datetime, + expiration_time: datetime.datetime, + pop_receipt: str, + time_next_visible: datetime.datetime, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SignedIdentifier(_Model): + """The signed identifier. + + :ivar id: The unique ID for the signed identifier. Required. + :vartype id: str + :ivar access_policy: The access policy for the signed identifier. Required. + :vartype access_policy: ~azure.storage.queue._generated.models.AccessPolicy + """ + + id: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Id", "text": False, "unwrapped": False}, + ) + """The unique ID for the signed identifier. Required.""" + access_policy: "_models.AccessPolicy" = rest_field( + name="accessPolicy", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AccessPolicy", "text": False, "unwrapped": False}, + ) + """The access policy for the signed identifier. Required.""" + + _xml = {"attribute": False, "name": "SignedIdentifier", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + access_policy: "_models.AccessPolicy", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SignedIdentifiers(_Model): + """Represents an array of signed identifiers. + + :ivar items_property: The list of signed identifiers. Required. + :vartype items_property: ~azure.storage.queue._generated.models.SignedIdentifier + """ + + items_property: list["_models.SignedIdentifier"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={ + "attribute": False, + "itemsName": "SignedIdentifier", + "name": "SignedIdentifier", + "text": False, + "unwrapped": True, + }, + original_tsp_name="items", + ) + """The list of signed identifiers. Required.""" + + _xml = {"attribute": False, "name": "SignedIdentifiers", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.SignedIdentifier"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UserDelegationKey(_Model): + """A user delegation key. + + :ivar signed_oid: The Azure Active Directory object ID in GUID format. Required. + :vartype signed_oid: str + :ivar signed_tid: The Azure Active Directory tenant ID in GUID format. Required. + :vartype signed_tid: str + :ivar signed_start: The date-time the key is active. Required. + :vartype signed_start: str + :ivar signed_expiry: The date-time the key expires. Required. + :vartype signed_expiry: str + :ivar signed_service: The service that created the key. Required. + :vartype signed_service: str + :ivar signed_version: The version of the service that created the key. Required. + :vartype signed_version: str + :ivar signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if + DelegatedUserTid is specified. + :vartype signed_delegated_user_tid: str + :ivar value: The key as a base64 string. Required. + :vartype value: str + """ + + signed_oid: str = rest_field( + name="signedOid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedOid", "text": False, "unwrapped": False}, + ) + """The Azure Active Directory object ID in GUID format. Required.""" + signed_tid: str = rest_field( + name="signedTid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedTid", "text": False, "unwrapped": False}, + ) + """The Azure Active Directory tenant ID in GUID format. Required.""" + signed_start: str = rest_field( + name="signedStart", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedStart", "text": False, "unwrapped": False}, + ) + """The date-time the key is active. Required.""" + signed_expiry: str = rest_field( + name="signedExpiry", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedExpiry", "text": False, "unwrapped": False}, + ) + """The date-time the key expires. Required.""" + signed_service: str = rest_field( + name="signedService", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedService", "text": False, "unwrapped": False}, + ) + """The service that created the key. Required.""" + signed_version: str = rest_field( + name="signedVersion", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedVersion", "text": False, "unwrapped": False}, + ) + """The version of the service that created the key. Required.""" + signed_delegated_user_tid: Optional[str] = rest_field( + name="signedDelegatedUserTid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedDelegatedUserTid", "text": False, "unwrapped": False}, + ) + """The delegated user tenant id in Azure AD. Return if DelegatedUserTid is specified.""" + value: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Value", "text": False, "unwrapped": False}, + ) + """The key as a base64 string. Required.""" + + _xml = {"attribute": False, "name": "UserDelegationKey", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + signed_oid: str, + signed_tid: str, + signed_start: str, + signed_expiry: str, + signed_service: str, + signed_version: str, + value: str, + signed_delegated_user_tid: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py deleted file mode 100644 index e28743c64d07..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py +++ /dev/null @@ -1,951 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models - - -class AccessPolicy(_serialization.Model): - """An Access policy. - - :ivar start: the date-time the policy is active. - :vartype start: str - :ivar expiry: the date-time the policy expires. - :vartype expiry: str - :ivar permission: the permissions for the acl policy. - :vartype permission: str - """ - - _attribute_map = { - "start": {"key": "Start", "type": "str"}, - "expiry": {"key": "Expiry", "type": "str"}, - "permission": {"key": "Permission", "type": "str"}, - } - - def __init__( - self, - *, - start: Optional[str] = None, - expiry: Optional[str] = None, - permission: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword start: the date-time the policy is active. - :paramtype start: str - :keyword expiry: the date-time the policy expires. - :paramtype expiry: str - :keyword permission: the permissions for the acl policy. - :paramtype permission: str - """ - super().__init__(**kwargs) - self.start = start - self.expiry = expiry - self.permission = permission - - -class CorsRule(_serialization.Model): - """CORS is an HTTP feature that enables a web application running under one domain to access - resources in another domain. Web browsers implement a security restriction known as same-origin - policy that prevents a web page from calling APIs in a different domain; CORS provides a secure - way to allow one domain (the origin domain) to call APIs in another domain. - - All required parameters must be populated in order to send to server. - - :ivar allowed_origins: The origin domains that are permitted to make a request against the - storage service via CORS. The origin domain is the domain from which the request originates. - Note that the origin must be an exact case-sensitive match with the origin that the user age - sends to the service. You can also use the wildcard character '*' to allow all origin domains - to make requests via CORS. Required. - :vartype allowed_origins: str - :ivar allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. (comma separated). Required. - :vartype allowed_methods: str - :ivar allowed_headers: the request headers that the origin domain may specify on the CORS - request. Required. - :vartype allowed_headers: str - :ivar exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. Required. - :vartype exposed_headers: str - :ivar max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. Required. - :vartype max_age_in_seconds: int - """ - - _validation = { - "allowed_origins": {"required": True}, - "allowed_methods": {"required": True}, - "allowed_headers": {"required": True}, - "exposed_headers": {"required": True}, - "max_age_in_seconds": {"required": True, "minimum": 0}, - } - - _attribute_map = { - "allowed_origins": {"key": "AllowedOrigins", "type": "str"}, - "allowed_methods": {"key": "AllowedMethods", "type": "str"}, - "allowed_headers": {"key": "AllowedHeaders", "type": "str"}, - "exposed_headers": {"key": "ExposedHeaders", "type": "str"}, - "max_age_in_seconds": {"key": "MaxAgeInSeconds", "type": "int"}, - } - - def __init__( - self, - *, - allowed_origins: str, - allowed_methods: str, - allowed_headers: str, - exposed_headers: str, - max_age_in_seconds: int, - **kwargs: Any - ) -> None: - """ - :keyword allowed_origins: The origin domains that are permitted to make a request against the - storage service via CORS. The origin domain is the domain from which the request originates. - Note that the origin must be an exact case-sensitive match with the origin that the user age - sends to the service. You can also use the wildcard character '*' to allow all origin domains - to make requests via CORS. Required. - :paramtype allowed_origins: str - :keyword allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. (comma separated). Required. - :paramtype allowed_methods: str - :keyword allowed_headers: the request headers that the origin domain may specify on the CORS - request. Required. - :paramtype allowed_headers: str - :keyword exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. Required. - :paramtype exposed_headers: str - :keyword max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. Required. - :paramtype max_age_in_seconds: int - """ - super().__init__(**kwargs) - self.allowed_origins = allowed_origins - self.allowed_methods = allowed_methods - self.allowed_headers = allowed_headers - self.exposed_headers = exposed_headers - self.max_age_in_seconds = max_age_in_seconds - - -class DequeuedMessageItem(_serialization.Model): - """The object returned in the QueueMessageList array when calling Get Messages on a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_id: The Id of the Message. Required. - :vartype message_id: str - :ivar insertion_time: The time the Message was inserted into the Queue. Required. - :vartype insertion_time: ~datetime.datetime - :ivar expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :vartype expiration_time: ~datetime.datetime - :ivar pop_receipt: This value is required to delete the Message. If deletion fails using this - popreceipt then the message has been dequeued by another client. Required. - :vartype pop_receipt: str - :ivar time_next_visible: The time that the message will again become visible in the Queue. - Required. - :vartype time_next_visible: ~datetime.datetime - :ivar dequeue_count: The number of times the message has been dequeued. Required. - :vartype dequeue_count: int - :ivar message_text: The content of the Message. Required. - :vartype message_text: str - """ - - _validation = { - "message_id": {"required": True}, - "insertion_time": {"required": True}, - "expiration_time": {"required": True}, - "pop_receipt": {"required": True}, - "time_next_visible": {"required": True}, - "dequeue_count": {"required": True}, - "message_text": {"required": True}, - } - - _attribute_map = { - "message_id": {"key": "MessageId", "type": "str"}, - "insertion_time": {"key": "InsertionTime", "type": "rfc-1123"}, - "expiration_time": {"key": "ExpirationTime", "type": "rfc-1123"}, - "pop_receipt": {"key": "PopReceipt", "type": "str"}, - "time_next_visible": {"key": "TimeNextVisible", "type": "rfc-1123"}, - "dequeue_count": {"key": "DequeueCount", "type": "int"}, - "message_text": {"key": "MessageText", "type": "str"}, - } - _xml_map = {"name": "QueueMessage"} - - def __init__( - self, - *, - message_id: str, - insertion_time: datetime.datetime, - expiration_time: datetime.datetime, - pop_receipt: str, - time_next_visible: datetime.datetime, - dequeue_count: int, - message_text: str, - **kwargs: Any - ) -> None: - """ - :keyword message_id: The Id of the Message. Required. - :paramtype message_id: str - :keyword insertion_time: The time the Message was inserted into the Queue. Required. - :paramtype insertion_time: ~datetime.datetime - :keyword expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :paramtype expiration_time: ~datetime.datetime - :keyword pop_receipt: This value is required to delete the Message. If deletion fails using - this popreceipt then the message has been dequeued by another client. Required. - :paramtype pop_receipt: str - :keyword time_next_visible: The time that the message will again become visible in the Queue. - Required. - :paramtype time_next_visible: ~datetime.datetime - :keyword dequeue_count: The number of times the message has been dequeued. Required. - :paramtype dequeue_count: int - :keyword message_text: The content of the Message. Required. - :paramtype message_text: str - """ - super().__init__(**kwargs) - self.message_id = message_id - self.insertion_time = insertion_time - self.expiration_time = expiration_time - self.pop_receipt = pop_receipt - self.time_next_visible = time_next_visible - self.dequeue_count = dequeue_count - self.message_text = message_text - - -class EnqueuedMessage(_serialization.Model): - """The object returned in the QueueMessageList array when calling Put Message on a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_id: The Id of the Message. Required. - :vartype message_id: str - :ivar insertion_time: The time the Message was inserted into the Queue. Required. - :vartype insertion_time: ~datetime.datetime - :ivar expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :vartype expiration_time: ~datetime.datetime - :ivar pop_receipt: This value is required to delete the Message. If deletion fails using this - popreceipt then the message has been dequeued by another client. Required. - :vartype pop_receipt: str - :ivar time_next_visible: The time that the message will again become visible in the Queue. - Required. - :vartype time_next_visible: ~datetime.datetime - """ - - _validation = { - "message_id": {"required": True}, - "insertion_time": {"required": True}, - "expiration_time": {"required": True}, - "pop_receipt": {"required": True}, - "time_next_visible": {"required": True}, - } - - _attribute_map = { - "message_id": {"key": "MessageId", "type": "str"}, - "insertion_time": {"key": "InsertionTime", "type": "rfc-1123"}, - "expiration_time": {"key": "ExpirationTime", "type": "rfc-1123"}, - "pop_receipt": {"key": "PopReceipt", "type": "str"}, - "time_next_visible": {"key": "TimeNextVisible", "type": "rfc-1123"}, - } - _xml_map = {"name": "QueueMessage"} - - def __init__( - self, - *, - message_id: str, - insertion_time: datetime.datetime, - expiration_time: datetime.datetime, - pop_receipt: str, - time_next_visible: datetime.datetime, - **kwargs: Any - ) -> None: - """ - :keyword message_id: The Id of the Message. Required. - :paramtype message_id: str - :keyword insertion_time: The time the Message was inserted into the Queue. Required. - :paramtype insertion_time: ~datetime.datetime - :keyword expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :paramtype expiration_time: ~datetime.datetime - :keyword pop_receipt: This value is required to delete the Message. If deletion fails using - this popreceipt then the message has been dequeued by another client. Required. - :paramtype pop_receipt: str - :keyword time_next_visible: The time that the message will again become visible in the Queue. - Required. - :paramtype time_next_visible: ~datetime.datetime - """ - super().__init__(**kwargs) - self.message_id = message_id - self.insertion_time = insertion_time - self.expiration_time = expiration_time - self.pop_receipt = pop_receipt - self.time_next_visible = time_next_visible - - -class GeoReplication(_serialization.Model): - """GeoReplication. - - All required parameters must be populated in order to send to server. - - :ivar status: The status of the secondary location. Required. Known values are: "live", - "bootstrap", and "unavailable". - :vartype status: str or ~azure.storage.queue.models.GeoReplicationStatusType - :ivar last_sync_time: A GMT date/time value, to the second. All primary writes preceding this - value are guaranteed to be available for read operations at the secondary. Primary writes after - this point in time may or may not be available for reads. Required. - :vartype last_sync_time: ~datetime.datetime - """ - - _validation = { - "status": {"required": True}, - "last_sync_time": {"required": True}, - } - - _attribute_map = { - "status": {"key": "Status", "type": "str"}, - "last_sync_time": {"key": "LastSyncTime", "type": "rfc-1123"}, - } - - def __init__( - self, - *, - status: Union[str, "_models.GeoReplicationStatusType"], - last_sync_time: datetime.datetime, - **kwargs: Any - ) -> None: - """ - :keyword status: The status of the secondary location. Required. Known values are: "live", - "bootstrap", and "unavailable". - :paramtype status: str or ~azure.storage.queue.models.GeoReplicationStatusType - :keyword last_sync_time: A GMT date/time value, to the second. All primary writes preceding - this value are guaranteed to be available for read operations at the secondary. Primary writes - after this point in time may or may not be available for reads. Required. - :paramtype last_sync_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.status = status - self.last_sync_time = last_sync_time - - -class KeyInfo(_serialization.Model): - """Key information. - - All required parameters must be populated in order to send to server. - - :ivar start: The date-time the key is active in ISO 8601 UTC time. - :vartype start: str - :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :vartype expiry: str - :ivar delegated_user_tid: The delegated user tenant id in Azure AD. - :vartype delegated_user_tid: str - """ - - _validation = { - "expiry": {"required": True}, - } - - _attribute_map = { - "start": {"key": "Start", "type": "str"}, - "expiry": {"key": "Expiry", "type": "str"}, - "delegated_user_tid": {"key": "DelegatedUserTid", "type": "str"}, - } - - def __init__( - self, *, expiry: str, start: Optional[str] = None, delegated_user_tid: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword start: The date-time the key is active in ISO 8601 UTC time. - :paramtype start: str - :keyword expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :paramtype expiry: str - :keyword delegated_user_tid: The delegated user tenant id in Azure AD. - :paramtype delegated_user_tid: str - """ - super().__init__(**kwargs) - self.start = start - self.expiry = expiry - self.delegated_user_tid = delegated_user_tid - - -class ListQueuesSegmentResponse(_serialization.Model): - """The object returned when calling List Queues on a Queue Service. - - All required parameters must be populated in order to send to server. - - :ivar service_endpoint: Required. - :vartype service_endpoint: str - :ivar prefix: Required. - :vartype prefix: str - :ivar marker: - :vartype marker: str - :ivar max_results: Required. - :vartype max_results: int - :ivar queue_items: - :vartype queue_items: list[~azure.storage.queue.models.QueueItem] - :ivar next_marker: Required. - :vartype next_marker: str - """ - - _validation = { - "service_endpoint": {"required": True}, - "prefix": {"required": True}, - "max_results": {"required": True}, - "next_marker": {"required": True}, - } - - _attribute_map = { - "service_endpoint": { - "key": "ServiceEndpoint", - "type": "str", - "xml": {"attr": True}, - }, - "prefix": {"key": "Prefix", "type": "str"}, - "marker": {"key": "Marker", "type": "str"}, - "max_results": {"key": "MaxResults", "type": "int"}, - "queue_items": { - "key": "QueueItems", - "type": "[QueueItem]", - "xml": {"name": "Queues", "wrapped": True, "itemsName": "Queue"}, - }, - "next_marker": {"key": "NextMarker", "type": "str"}, - } - _xml_map = {"name": "EnumerationResults"} - - def __init__( - self, - *, - service_endpoint: str, - prefix: str, - max_results: int, - next_marker: str, - marker: Optional[str] = None, - queue_items: Optional[list["_models.QueueItem"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword service_endpoint: Required. - :paramtype service_endpoint: str - :keyword prefix: Required. - :paramtype prefix: str - :keyword marker: - :paramtype marker: str - :keyword max_results: Required. - :paramtype max_results: int - :keyword queue_items: - :paramtype queue_items: list[~azure.storage.queue.models.QueueItem] - :keyword next_marker: Required. - :paramtype next_marker: str - """ - super().__init__(**kwargs) - self.service_endpoint = service_endpoint - self.prefix = prefix - self.marker = marker - self.max_results = max_results - self.queue_items = queue_items - self.next_marker = next_marker - - -class Logging(_serialization.Model): - """Azure Analytics Logging settings. - - All required parameters must be populated in order to send to server. - - :ivar version: The version of Storage Analytics to configure. Required. - :vartype version: str - :ivar delete: Indicates whether all delete requests should be logged. Required. - :vartype delete: bool - :ivar read: Indicates whether all read requests should be logged. Required. - :vartype read: bool - :ivar write: Indicates whether all write requests should be logged. Required. - :vartype write: bool - :ivar retention_policy: the retention policy. Required. - :vartype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - - _validation = { - "version": {"required": True}, - "delete": {"required": True}, - "read": {"required": True}, - "write": {"required": True}, - "retention_policy": {"required": True}, - } - - _attribute_map = { - "version": {"key": "Version", "type": "str"}, - "delete": {"key": "Delete", "type": "bool"}, - "read": {"key": "Read", "type": "bool"}, - "write": {"key": "Write", "type": "bool"}, - "retention_policy": {"key": "RetentionPolicy", "type": "RetentionPolicy"}, - } - - def __init__( - self, - *, - version: str, - delete: bool, - read: bool, - write: bool, - retention_policy: "_models.RetentionPolicy", - **kwargs: Any - ) -> None: - """ - :keyword version: The version of Storage Analytics to configure. Required. - :paramtype version: str - :keyword delete: Indicates whether all delete requests should be logged. Required. - :paramtype delete: bool - :keyword read: Indicates whether all read requests should be logged. Required. - :paramtype read: bool - :keyword write: Indicates whether all write requests should be logged. Required. - :paramtype write: bool - :keyword retention_policy: the retention policy. Required. - :paramtype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - super().__init__(**kwargs) - self.version = version - self.delete = delete - self.read = read - self.write = write - self.retention_policy = retention_policy - - -class Metrics(_serialization.Model): - """a summary of request statistics grouped by API in hour or minute aggregates for queues. - - All required parameters must be populated in order to send to server. - - :ivar version: The version of Storage Analytics to configure. - :vartype version: str - :ivar enabled: Indicates whether metrics are enabled for the Queue service. Required. - :vartype enabled: bool - :ivar include_apis: Indicates whether metrics should generate summary statistics for called API - operations. - :vartype include_apis: bool - :ivar retention_policy: the retention policy. - :vartype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - - _validation = { - "enabled": {"required": True}, - } - - _attribute_map = { - "version": {"key": "Version", "type": "str"}, - "enabled": {"key": "Enabled", "type": "bool"}, - "include_apis": {"key": "IncludeAPIs", "type": "bool"}, - "retention_policy": {"key": "RetentionPolicy", "type": "RetentionPolicy"}, - } - - def __init__( - self, - *, - enabled: bool, - version: Optional[str] = None, - include_apis: Optional[bool] = None, - retention_policy: Optional["_models.RetentionPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword version: The version of Storage Analytics to configure. - :paramtype version: str - :keyword enabled: Indicates whether metrics are enabled for the Queue service. Required. - :paramtype enabled: bool - :keyword include_apis: Indicates whether metrics should generate summary statistics for called - API operations. - :paramtype include_apis: bool - :keyword retention_policy: the retention policy. - :paramtype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - super().__init__(**kwargs) - self.version = version - self.enabled = enabled - self.include_apis = include_apis - self.retention_policy = retention_policy - - -class PeekedMessageItem(_serialization.Model): - """The object returned in the QueueMessageList array when calling Peek Messages on a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_id: The Id of the Message. Required. - :vartype message_id: str - :ivar insertion_time: The time the Message was inserted into the Queue. Required. - :vartype insertion_time: ~datetime.datetime - :ivar expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :vartype expiration_time: ~datetime.datetime - :ivar dequeue_count: The number of times the message has been dequeued. Required. - :vartype dequeue_count: int - :ivar message_text: The content of the Message. Required. - :vartype message_text: str - """ - - _validation = { - "message_id": {"required": True}, - "insertion_time": {"required": True}, - "expiration_time": {"required": True}, - "dequeue_count": {"required": True}, - "message_text": {"required": True}, - } - - _attribute_map = { - "message_id": {"key": "MessageId", "type": "str"}, - "insertion_time": {"key": "InsertionTime", "type": "rfc-1123"}, - "expiration_time": {"key": "ExpirationTime", "type": "rfc-1123"}, - "dequeue_count": {"key": "DequeueCount", "type": "int"}, - "message_text": {"key": "MessageText", "type": "str"}, - } - _xml_map = {"name": "QueueMessage"} - - def __init__( - self, - *, - message_id: str, - insertion_time: datetime.datetime, - expiration_time: datetime.datetime, - dequeue_count: int, - message_text: str, - **kwargs: Any - ) -> None: - """ - :keyword message_id: The Id of the Message. Required. - :paramtype message_id: str - :keyword insertion_time: The time the Message was inserted into the Queue. Required. - :paramtype insertion_time: ~datetime.datetime - :keyword expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :paramtype expiration_time: ~datetime.datetime - :keyword dequeue_count: The number of times the message has been dequeued. Required. - :paramtype dequeue_count: int - :keyword message_text: The content of the Message. Required. - :paramtype message_text: str - """ - super().__init__(**kwargs) - self.message_id = message_id - self.insertion_time = insertion_time - self.expiration_time = expiration_time - self.dequeue_count = dequeue_count - self.message_text = message_text - - -class QueueItem(_serialization.Model): - """An Azure Storage Queue. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the Queue. Required. - :vartype name: str - :ivar metadata: Dictionary of :code:``. - :vartype metadata: dict[str, str] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "Name", "type": "str"}, - "metadata": {"key": "Metadata", "type": "{str}"}, - } - _xml_map = {"name": "Queue"} - - def __init__(self, *, name: str, metadata: Optional[dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the Queue. Required. - :paramtype name: str - :keyword metadata: Dictionary of :code:``. - :paramtype metadata: dict[str, str] - """ - super().__init__(**kwargs) - self.name = name - self.metadata = metadata - - -class QueueMessage(_serialization.Model): - """A Message object which can be stored in a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_text: The content of the message. Required. - :vartype message_text: str - """ - - _validation = { - "message_text": {"required": True}, - } - - _attribute_map = { - "message_text": {"key": "MessageText", "type": "str"}, - } - - def __init__(self, *, message_text: str, **kwargs: Any) -> None: - """ - :keyword message_text: The content of the message. Required. - :paramtype message_text: str - """ - super().__init__(**kwargs) - self.message_text = message_text - - -class RetentionPolicy(_serialization.Model): - """the retention policy. - - All required parameters must be populated in order to send to server. - - :ivar enabled: Indicates whether a retention policy is enabled for the storage service. - Required. - :vartype enabled: bool - :ivar days: Indicates the number of days that metrics or logging or soft-deleted data should be - retained. All data older than this value will be deleted. - :vartype days: int - """ - - _validation = { - "enabled": {"required": True}, - "days": {"minimum": 1}, - } - - _attribute_map = { - "enabled": {"key": "Enabled", "type": "bool"}, - "days": {"key": "Days", "type": "int"}, - } - - def __init__(self, *, enabled: bool, days: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword enabled: Indicates whether a retention policy is enabled for the storage service. - Required. - :paramtype enabled: bool - :keyword days: Indicates the number of days that metrics or logging or soft-deleted data should - be retained. All data older than this value will be deleted. - :paramtype days: int - """ - super().__init__(**kwargs) - self.enabled = enabled - self.days = days - - -class SignedIdentifier(_serialization.Model): - """signed identifier. - - All required parameters must be populated in order to send to server. - - :ivar id: a unique id. Required. - :vartype id: str - :ivar access_policy: The access policy. - :vartype access_policy: ~azure.storage.queue.models.AccessPolicy - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "Id", "type": "str"}, - "access_policy": {"key": "AccessPolicy", "type": "AccessPolicy"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - access_policy: Optional["_models.AccessPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: a unique id. Required. - :paramtype id: str - :keyword access_policy: The access policy. - :paramtype access_policy: ~azure.storage.queue.models.AccessPolicy - """ - super().__init__(**kwargs) - self.id = id - self.access_policy = access_policy - - -class StorageError(_serialization.Model): - """StorageError. - - :ivar message: - :vartype message: str - """ - - _attribute_map = { - "message": {"key": "Message", "type": "str"}, - } - - def __init__(self, *, message: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword message: - :paramtype message: str - """ - super().__init__(**kwargs) - self.message = message - - -class StorageServiceProperties(_serialization.Model): - """Storage Service Properties. - - :ivar logging: Azure Analytics Logging settings. - :vartype logging: ~azure.storage.queue.models.Logging - :ivar hour_metrics: A summary of request statistics grouped by API in hourly aggregates for - queues. - :vartype hour_metrics: ~azure.storage.queue.models.Metrics - :ivar minute_metrics: a summary of request statistics grouped by API in minute aggregates for - queues. - :vartype minute_metrics: ~azure.storage.queue.models.Metrics - :ivar cors: The set of CORS rules. - :vartype cors: list[~azure.storage.queue.models.CorsRule] - """ - - _attribute_map = { - "logging": {"key": "Logging", "type": "Logging"}, - "hour_metrics": {"key": "HourMetrics", "type": "Metrics"}, - "minute_metrics": {"key": "MinuteMetrics", "type": "Metrics"}, - "cors": {"key": "Cors", "type": "[CorsRule]", "xml": {"wrapped": True}}, - } - - def __init__( - self, - *, - logging: Optional["_models.Logging"] = None, - hour_metrics: Optional["_models.Metrics"] = None, - minute_metrics: Optional["_models.Metrics"] = None, - cors: Optional[list["_models.CorsRule"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword logging: Azure Analytics Logging settings. - :paramtype logging: ~azure.storage.queue.models.Logging - :keyword hour_metrics: A summary of request statistics grouped by API in hourly aggregates for - queues. - :paramtype hour_metrics: ~azure.storage.queue.models.Metrics - :keyword minute_metrics: a summary of request statistics grouped by API in minute aggregates - for queues. - :paramtype minute_metrics: ~azure.storage.queue.models.Metrics - :keyword cors: The set of CORS rules. - :paramtype cors: list[~azure.storage.queue.models.CorsRule] - """ - super().__init__(**kwargs) - self.logging = logging - self.hour_metrics = hour_metrics - self.minute_metrics = minute_metrics - self.cors = cors - - -class StorageServiceStats(_serialization.Model): - """Stats for the storage service. - - :ivar geo_replication: Geo-Replication information for the Secondary Storage Service. - :vartype geo_replication: ~azure.storage.queue.models.GeoReplication - """ - - _attribute_map = { - "geo_replication": {"key": "GeoReplication", "type": "GeoReplication"}, - } - - def __init__(self, *, geo_replication: Optional["_models.GeoReplication"] = None, **kwargs: Any) -> None: - """ - :keyword geo_replication: Geo-Replication information for the Secondary Storage Service. - :paramtype geo_replication: ~azure.storage.queue.models.GeoReplication - """ - super().__init__(**kwargs) - self.geo_replication = geo_replication - - -class UserDelegationKey(_serialization.Model): - """A user delegation key. - - All required parameters must be populated in order to send to server. - - :ivar signed_oid: The Azure Active Directory object ID in GUID format. Required. - :vartype signed_oid: str - :ivar signed_tid: The Azure Active Directory tenant ID in GUID format. Required. - :vartype signed_tid: str - :ivar signed_start: The date-time the key is active. Required. - :vartype signed_start: ~datetime.datetime - :ivar signed_expiry: The date-time the key expires. Required. - :vartype signed_expiry: ~datetime.datetime - :ivar signed_service: Abbreviation of the Azure Storage service that accepts the key. Required. - :vartype signed_service: str - :ivar signed_version: The service version that created the key. Required. - :vartype signed_version: str - :ivar signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if - DelegatedUserTid is specified. - :vartype signed_delegated_user_tid: str - :ivar value: The key as a base64 string. Required. - :vartype value: str - """ - - _validation = { - "signed_oid": {"required": True}, - "signed_tid": {"required": True}, - "signed_start": {"required": True}, - "signed_expiry": {"required": True}, - "signed_service": {"required": True}, - "signed_version": {"required": True}, - "value": {"required": True}, - } - - _attribute_map = { - "signed_oid": {"key": "SignedOid", "type": "str"}, - "signed_tid": {"key": "SignedTid", "type": "str"}, - "signed_start": {"key": "SignedStart", "type": "iso-8601"}, - "signed_expiry": {"key": "SignedExpiry", "type": "iso-8601"}, - "signed_service": {"key": "SignedService", "type": "str"}, - "signed_version": {"key": "SignedVersion", "type": "str"}, - "signed_delegated_user_tid": {"key": "SignedDelegatedUserTid", "type": "str"}, - "value": {"key": "Value", "type": "str"}, - } - - def __init__( - self, - *, - signed_oid: str, - signed_tid: str, - signed_start: datetime.datetime, - signed_expiry: datetime.datetime, - signed_service: str, - signed_version: str, - value: str, - signed_delegated_user_tid: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword signed_oid: The Azure Active Directory object ID in GUID format. Required. - :paramtype signed_oid: str - :keyword signed_tid: The Azure Active Directory tenant ID in GUID format. Required. - :paramtype signed_tid: str - :keyword signed_start: The date-time the key is active. Required. - :paramtype signed_start: ~datetime.datetime - :keyword signed_expiry: The date-time the key expires. Required. - :paramtype signed_expiry: ~datetime.datetime - :keyword signed_service: Abbreviation of the Azure Storage service that accepts the key. - Required. - :paramtype signed_service: str - :keyword signed_version: The service version that created the key. Required. - :paramtype signed_version: str - :keyword signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if - DelegatedUserTid is specified. - :paramtype signed_delegated_user_tid: str - :keyword value: The key as a base64 string. Required. - :paramtype value: str - """ - super().__init__(**kwargs) - self.signed_oid = signed_oid - self.signed_tid = signed_tid - self.signed_start = signed_start - self.signed_expiry = signed_expiry - self.signed_service = signed_service - self.signed_version = signed_version - self.signed_delegated_user_tid = signed_delegated_user_tid - self.value = value diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py index 2e25743cab74..c414d071566a 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py @@ -1,17 +1,61 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, List + +from .._utils.model_base import Model as _Model, _MyMutableMapping + +__all__: List[str] = [] + + +# --------------------------------------------------------------------------- +# Backcompat shim for legacy ``knack.util.todict`` consumers (e.g. Azure CLI). +# knack checks ``hasattr(obj, '_asdict')`` (namedtuple convention) BEFORE +# falling back to ``obj.__dict__``. TypeSpec ``_Model`` instances stash all +# fields in ``__dict__['_data']`` so a naive ``__dict__`` walk sees nothing. +# Returning the model contents with REST wire-name keys at every level +# matches what msrest models exposed when knack walked their ``__dict__`` +# and camelCased the snake_case attributes -- preserving the JSON shape the +# Azure CLI's ``_transformers.py`` expects. +# --------------------------------------------------------------------------- + + +def _asdict_value(v: Any) -> Any: + if v is None: + return None + if isinstance(v, _MyMutableMapping): + return _patched_namedtuple_asdict(v) + if isinstance(v, dict): + return {k: _asdict_value(val) for k, val in v.items()} + if isinstance(v, (list, tuple, set)): + return type(v)(_asdict_value(x) for x in v) + return v + + +def _patched_namedtuple_asdict(self) -> dict: + """Mirror msrest behaviour: include every declared field (REST wire + name) even when the value was never set, so legacy CLI consumers + that subscript by key (e.g. ``result['start']``) don't raise + ``KeyError`` for omitted optional fields.""" + result: dict = {} + rest_fields = getattr(type(self), "_attr_to_rest_field", None) or {} + data = getattr(self, "_data", {}) or {} + for rf in rest_fields.values(): + result[rf._rest_name] = _asdict_value(data.get(rf._rest_name)) + for k, v in data.items(): + if k not in result: + result[k] = _asdict_value(v) + return result -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +_Model._asdict = _patched_namedtuple_asdict def patch_sdk(): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py index e53a2d5483fd..3fb890991836 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,10 +12,8 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._service_operations import ServiceOperations # type: ignore -from ._queue_operations import QueueOperations # type: ignore -from ._messages_operations import MessagesOperations # type: ignore -from ._message_id_operations import MessageIdOperations # type: ignore +from ._operations import ServiceOperations # type: ignore +from ._operations import QueueOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -24,8 +22,6 @@ __all__ = [ "ServiceOperations", "QueueOperations", - "MessagesOperations", - "MessageIdOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_message_id_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_message_id_operations.py deleted file mode 100644 index 39c22976afbe..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_message_id_operations.py +++ /dev/null @@ -1,302 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureQueueStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_update_request( - url: str, - *, - pop_receipt: str, - visibilitytimeout: int, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") - _params["visibilitytimeout"] = _SERIALIZER.query( - "visibilitytimeout", visibilitytimeout, "int", maximum=604800, minimum=0 - ) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_delete_request( - url: str, - *, - pop_receipt: str, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class MessageIdOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`message_id` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def update( # pylint: disable=inconsistent-return-statements - self, - pop_receipt: str, - visibilitytimeout: int, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - queue_message: Optional[_models.QueueMessage] = None, - **kwargs: Any - ) -> None: - """The Update operation was introduced with version 2011-08-18 of the Queue service API. The - Update Message operation updates the visibility timeout of a message. You can also use this - operation to update the contents of a message. A message must be in a format that can be - included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in - size. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Required. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Delete operation deletes the specified message. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param timeout: The The timeout parameter is expressed in seconds. For more information, see HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if number_of_messages is not None: - _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int", minimum=1) - if visibilitytimeout is not None: - _params["visibilitytimeout"] = _SERIALIZER.query( - "visibilitytimeout", visibilitytimeout, "int", maximum=604800, minimum=0 - ) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_clear_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_enqueue_request( - url: str, - *, - content: Any, - version: str, - visibilitytimeout: Optional[int] = None, - message_time_to_live: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if visibilitytimeout is not None: - _params["visibilitytimeout"] = _SERIALIZER.query( - "visibilitytimeout", visibilitytimeout, "int", maximum=604800, minimum=0 - ) - if message_time_to_live is not None: - _params["messagettl"] = _SERIALIZER.query("message_time_to_live", message_time_to_live, "int", minimum=-1) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_peek_request( - url: str, - *, - version: str, - number_of_messages: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - peekonly: Literal["true"] = kwargs.pop("peekonly", _params.pop("peekonly", "true")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["peekonly"] = _SERIALIZER.query("peekonly", peekonly, "str") - if number_of_messages is not None: - _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int", minimum=1) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class MessagesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`messages` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def dequeue( - self, - number_of_messages: Optional[int] = None, - visibilitytimeout: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> list[_models.DequeuedMessageItem]: - """The Dequeue operation retrieves one or more messages from the front of the queue. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Default value is None. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Clear operation deletes all messages from the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.EnqueuedMessage]: - """The Enqueue operation adds a new message to the back of the message queue. A visibility timeout - can also be specified to make the message invisible until the visibility timeout expires. A - message must be in a format that can be included in an XML request with UTF-8 encoding. The - encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size - for previous versions. - - :param queue_message: A Message object which can be stored in a Queue. Required. - :type queue_message: ~azure.storage.queue.models.QueueMessage - :param visibilitytimeout: Optional. If specified, the request must be made using an - x-ms-version of 2011-08-18 or later. If not specified, the default value is 0. Specifies the - new visibility timeout value, in seconds, relative to server time. The new value must be larger - than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message - cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value - smaller than the time-to-live value. Default value is None. - :type visibilitytimeout: int - :param message_time_to_live: Optional. Specifies the time-to-live interval for the message, in - seconds. Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For version - 2017-07-29 or later, the maximum time-to-live can be any positive number, as well as -1 - indicating that the message does not expire. If this parameter is omitted, the default - time-to-live is 7 days. Default value is None. - :type message_time_to_live: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.PeekedMessageItem]: - """The Peek operation retrieves one or more messages from the front of the queue, but does not - alter the visibility of the message. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?restype=service&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_properties_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=service&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_statistics_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=service&comp=stats" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_user_delegation_key_request( # pylint: disable=name-too-long + *, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=service&comp=userdelegationkey" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_queues_request( + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?comp=list" + + # Construct parameters + if prefix is not None: + _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if maxresults is not None: + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if include is not None: + _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_create_request( + *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_get_properties_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?comp=metadata" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_delete_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_set_metadata_request( + *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?comp=metadata" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_get_access_policy_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?comp=acl" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_set_access_policy_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?comp=acl" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_receive_messages_request( + *, + number_of_messages: Optional[int] = None, + visibility_timeout: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/messages" + + # Construct parameters + if number_of_messages is not None: + _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int") + if visibility_timeout is not None: + _params["visibilitytimeout"] = _SERIALIZER.query("visibility_timeout", visibility_timeout, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_clear_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "/messages" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_send_message_request( + *, + visibility_timeout: Optional[int] = None, + message_time_to_live: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/messages" + + # Construct parameters + if visibility_timeout is not None: + _params["visibilitytimeout"] = _SERIALIZER.query("visibility_timeout", visibility_timeout, "int") + if message_time_to_live is not None: + _params["messagettl"] = _SERIALIZER.query("message_time_to_live", message_time_to_live, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_peek_messages_request( + *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/messages?peekonly=true" + + # Construct parameters + if number_of_messages is not None: + _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_update_message_request( + message_id: str, *, pop_receipt: str, visibility_timeout: int, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "/messages/{messageId}" + path_format_arguments = { + "messageId": _SERIALIZER.url("message_id", message_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") + _params["visibilitytimeout"] = _SERIALIZER.query("visibility_timeout", visibility_timeout, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_delete_message_request( + message_id: str, *, pop_receipt: str, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "/messages/{messageId}" + path_format_arguments = { + "messageId": _SERIALIZER.url("message_id", message_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.queue.QueuesClient`'s + :attr:`service` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def set_properties( # pylint: disable=inconsistent-return-statements + self, queue_service_properties: _models.QueueServiceProperties, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Sets properties for a storage account's Queue service endpoint, including properties for + Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :param queue_service_properties: The storage service properties to set. Required. + :type queue_service_properties: ~azure.storage.queue._generated.models.QueueServiceProperties + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(queue_service_properties) + + _request = build_service_set_properties_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceProperties: + """Retrieves properties of a storage account's Queue service, including properties for Storage + Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceProperties. The QueueServiceProperties is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceProperties] = kwargs.pop("cls", None) + + _request = build_service_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceProperties, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceStats: + """Retrieves statistics related to replication for the Queue service. It is only available on the + secondary location endpoint when read-access geo-redundant replication is enabled for the + storage account. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceStats. The QueueServiceStats is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceStats + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceStats] = kwargs.pop("cls", None) + + _request = build_service_get_statistics_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceStats, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_user_delegation_key( + self, key_info: _models.KeyInfo, *, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.UserDelegationKey: + """Retrieves a user delegation key for the Queue service. This is only a valid operation when + using bearer token authentication. + + :param key_info: Key information. Required. + :type key_info: ~azure.storage.queue._generated.models.KeyInfo + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.UserDelegationKey + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) + + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.UserDelegationKey, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_queues( + self, + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, + **kwargs: Any + ) -> _models.ListQueuesResponse: + """returns a list of the queues under the specified account. + + :keyword prefix: Filters the results to return only queues whose name begins with the specified + prefix. Default value is None. + :paramtype prefix: str + :keyword marker: A string value that identifies the portion of the list of queues to be + returned with the next listing operation. The operation returns the NextMarker value within the + response body if the listing operation did not return all queues remaining to be listed with + the current page. The NextMarker value can be used as the value for the marker parameter in a + subsequent call to request the next page of list items. The marker value is opaque to the + client. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of queues to return. If the request does not + specify maxresults, or specifies a value greater than 5000, the server will return up to 5000 + items. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :keyword include: Include this parameter to specify that the queue's metadata be returned as + part of the response body. Default value is None. + :paramtype include: list[str or ~azure.storage.queue.models.ListQueuesIncludeType] + :return: ListQueuesResponse. The ListQueuesResponse is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ListQueuesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListQueuesResponse] = kwargs.pop("cls", None) + + _request = build_service_get_queues_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, + timeout=timeout, + include=include, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListQueuesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class QueueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.queue.QueuesClient`'s + :attr:`queue` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def create( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any + ) -> None: + """Creates a new queue under the specified account. If a queue with the same name already exists, + the operation succeeds when the metadata is identical and returns 204; if the metadata differs, + the operation returns 409. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_create_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_properties( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """returns all user-defined metadata and system properties for the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("str", response.headers.get("x-ms-meta")) + response_headers["x-ms-approximate-messages-count"] = self._deserialize( + "int", response.headers.get("x-ms-approximate-messages-count") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """operation permanently deletes the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def set_metadata( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any + ) -> None: + """operation sets one or more user-defined name-value pairs for the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_set_metadata_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.SignedIdentifiers: + """gets the permissions for the specified queue. The permissions indicate whether queue data may + be accessed publicly. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.SignedIdentifiers + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + + _request = build_queue_get_access_policy_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.SignedIdentifiers, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def set_access_policy( # pylint: disable=inconsistent-return-statements + self, queue_acl: Optional[_models.SignedIdentifiers] = None, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """sets the permissions for the specified queue. + + :param queue_acl: The access control list for the queue. Default value is None. + :type queue_acl: ~azure.storage.queue._generated.models.SignedIdentifiers + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_acl else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_acl is not None: + _content = _get_element(queue_acl) + else: + _content = None + + _request = build_queue_set_access_policy_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def receive_messages( + self, + *, + number_of_messages: Optional[int] = None, + visibility_timeout: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any + ) -> _models.ReceivedMessages: + """The Dequeue operation retrieves one or more messages from the front of the queue. + + :keyword number_of_messages: Optional. A nonzero integer value that specifies the number of + messages to + retrieve from the queue, up to a maximum of 32. If fewer are visible, the + visible messages are returned. By default, a single message is retrieved from + the queue with this operation. Default value is None. + :paramtype number_of_messages: int + :keyword visibility_timeout: Specifies the new visibility timeout value, in seconds, relative + to server time. The default value is 30 seconds. A specified value must be larger than or equal + to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions + prior to version 2011-08-18. The visibility timeout of a message can be set to a value later + than the expiry time. Default value is None. + :paramtype visibility_timeout: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: ReceivedMessages. The ReceivedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ReceivedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ReceivedMessages] = kwargs.pop("cls", None) + + _request = build_queue_receive_messages_request( + number_of_messages=number_of_messages, + visibility_timeout=visibility_timeout, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ReceivedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def clear( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """The Clear operation deletes all messages from the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_clear_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def send_message( + self, + queue_message: _models.QueueMessage, + *, + visibility_timeout: Optional[int] = None, + message_time_to_live: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any + ) -> _models.ListOfSentMessage: + """The Enqueue operation adds a new message to the back of the message queue. A visibility timeout + can also be specified to make the message invisible until the visibility timeout expires. A + message must be in a format that can be included in an XML request with UTF-8 encoding. The + encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size + for previous versions. + + :param queue_message: A Message object which can be stored in a Queue. Required. + :type queue_message: ~azure.storage.queue._generated.models.QueueMessage + :keyword visibility_timeout: Specifies the new visibility timeout value, in seconds, relative + to server time. The default value is 30 seconds. A specified value must be larger than or equal + to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions + prior to version 2011-08-18. The visibility timeout of a message can be set to a value later + than the expiry time. Default value is None. + :paramtype visibility_timeout: int + :keyword message_time_to_live: Optional. Specifies the time-to-live interval for the message, + in seconds. + Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For + version 2017-07-29 or later, the maximum time-to-live can be any positive + number, as well as -1 indicating that the message does not expire. If this + parameter is omitted, the default time-to-live is 7 days. Default value is None. + :paramtype message_time_to_live: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: ListOfSentMessage. The ListOfSentMessage is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ListOfSentMessage + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.ListOfSentMessage] = kwargs.pop("cls", None) + + _content = _get_element(queue_message) + + _request = build_queue_send_message_request( + visibility_timeout=visibility_timeout, + message_time_to_live=message_time_to_live, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListOfSentMessage, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def peek_messages( + self, *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.PeekedMessages: + """The Peek operation retrieves one or more messages from the front of the queue, but does not + alter the visibility of the message. + + :keyword number_of_messages: Optional. A nonzero integer value that specifies the number of + messages to + retrieve from the queue, up to a maximum of 32. If fewer are visible, the + visible messages are returned. By default, a single message is retrieved from + the queue with this operation. Default value is None. + :paramtype number_of_messages: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: PeekedMessages. The PeekedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.PeekedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PeekedMessages] = kwargs.pop("cls", None) + + _request = build_queue_peek_messages_request( + number_of_messages=number_of_messages, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.PeekedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def update_message( # pylint: disable=inconsistent-return-statements + self, + message_id: str, + queue_message: Optional[_models.QueueMessage] = None, + *, + pop_receipt: str, + visibility_timeout: int, + timeout: Optional[int] = None, + **kwargs: Any + ) -> None: + """The Update operation was introduced with version 2011-08-18 of the Queue service API. The + Update Message operation updates the visibility timeout of a message. You can also use this + operation to update the contents of a message. A message must be in a format that can be + included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in + size. + + :param message_id: The id of the queue message. Required. + :type message_id: str + :param queue_message: A Message object which can be stored in a Queue. Default value is None. + :type queue_message: ~azure.storage.queue._generated.models.QueueMessage + :keyword pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier + call to the Get Messages or Update Message operation. Required. + :paramtype pop_receipt: str + :keyword visibility_timeout: Specifies the new visibility timeout value, in seconds, relative + to server time. The default value is 30 seconds. A specified value must be larger than or equal + to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions + prior to version 2011-08-18. The visibility timeout of a message can be set to a value later + than the expiry time. Required. + :paramtype visibility_timeout: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_message else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_message is not None: + _content = _get_element(queue_message) + else: + _content = None + + _request = build_queue_update_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + visibility_timeout=visibility_timeout, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-popreceipt"] = self._deserialize("str", response.headers.get("x-ms-popreceipt")) + response_headers["x-ms-time-next-visible"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-time-next-visible") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def delete_message( # pylint: disable=inconsistent-return-statements + self, message_id: str, *, pop_receipt: str, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """The Delete operation deletes the specified message. + + :param message_id: The id of the queue message. Required. + :type message_id: str + :keyword pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier + call to the Get Messages or Update Message operation. Required. + :paramtype pop_receipt: str + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py index 2e25743cab74..87676c65a8f0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py @@ -1,17 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_queue_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_queue_operations.py deleted file mode 100644 index ddd138f17de9..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_queue_operations.py +++ /dev/null @@ -1,707 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureQueueStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_properties_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_metadata_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_access_policy_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_access_policy_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -class QueueOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`queue` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def create( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """creates a new queue under the given account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """operation permanently deletes the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """Retrieves user-defined metadata and queue properties on the specified queue. Metadata is - associated with the queue as name-values pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets user-defined metadata on the specified queue. Metadata is associated with the queue as - name-value pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.SignedIdentifier]: - """returns details about any stored access policies specified on the queue that may be used with - Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets stored access policies for the queue that may be used with Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_get_properties_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_statistics_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["stats"] = kwargs.pop("comp", _params.pop("comp", "stats")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_user_delegation_key_request( - url: str, - *, - content: Any, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["userdelegationkey"] = kwargs.pop("comp", _params.pop("comp", "userdelegationkey")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_list_queues_segment_request( - url: str, - *, - version: str, - prefix: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - include: Optional[list[Literal["metadata"]]] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if prefix is not None: - _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if maxresults is not None: - _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int", minimum=1) - if include is not None: - _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ServiceOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`service` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements - self, - storage_service_properties: _models.StorageServiceProperties, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """Sets properties for a storage account's Queue service endpoint, including properties for - Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param storage_service_properties: The StorageService properties. Required. - :type storage_service_properties: ~azure.storage.queue.models.StorageServiceProperties - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceProperties: - """gets the properties of a storage account's Queue service, including properties for Storage - Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceStats: - """Retrieves statistics related to replication for the Queue service. It is only available on the - secondary location endpoint when read-access geo-redundant replication is enabled for the - storage account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.UserDelegationKey: - """Retrieves a user delegation key for the Queue service. This is only a valid operation when - using bearer token authentication. - - :param key_info: Key information. Required. - :type key_info: ~azure.storage.queue.models.KeyInfo - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.ListQueuesSegmentResponse: - """The List Queues Segment operation returns a list of the queues under the specified account. - - :param prefix: Filters the results to return only queues whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param marker: A string value that identifies the portion of the list of queues to be returned - with the next listing operation. The operation returns the NextMarker value within the response - body if the listing operation did not return all queues remaining to be listed with the current - page. The NextMarker value can be used as the value for the marker parameter in a subsequent - call to request the next page of list items. The marker value is opaque to the client. Default - value is None. - :type marker: str - :param maxresults: Specifies the maximum number of queues to return. If the request does not - specify maxresults, or specifies a value greater than 5000, the server will return up to 5000 - items. Note that if the listing operation crosses a partition boundary, then the service will - return a continuation token for retrieving the remainder of the results. For this reason, it is - possible that the service will return fewer results than specified by maxresults, or than the - default of 5000. Default value is None. - :type maxresults: int - :param include: Include this parameter to specify that the queues' metadata be returned as part - of the response body. Default value is None. - :type include: list[str] - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: self.resolver = None def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[str, Any]) -> object: - for message in obj: + messages = obj.items_property if hasattr(obj, "items_property") else obj + for message in messages or []: if message.message_text in [None, "", b""]: continue content = message.message_text @@ -89,7 +90,10 @@ def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[st self.key_encryption_key, self.resolver, ) - message.message_text = self.decode(content, response) + decoded = self.decode(content, response) + # Store decoded content on a side attribute to bypass the _RestField + # descriptor which would re-serialize bytes back to base64. + message._decoded_content = decoded return obj def configure( diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py index 5fd01179d74e..acb38ebc8caf 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -42,16 +42,10 @@ class RetentionPolicy(GeneratedRetentionPolicy): be deleted. """ - enabled: bool = False - """Indicates whether a retention policy is enabled for the storage service.""" - days: Optional[int] = None - """Indicates the number of days that metrics or logging or soft-deleted data should be retained.""" - def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: - self.enabled = enabled - self.days = days - if self.enabled and (self.days is None): + if enabled and days is None: raise ValueError("If policy is enabled, 'days' must be specified.") + super().__init__(enabled=enabled, days=days) @classmethod def _from_generated(cls, generated: Any) -> Self: @@ -75,23 +69,14 @@ class QueueAnalyticsLogging(GeneratedLogging): :keyword ~azure.storage.queue.RetentionPolicy retention_policy: The retention policy for the metrics. """ - version: str = "1.0" - """The version of Storage Analytics to configure.""" - delete: bool = False - """Indicates whether all delete requests should be logged.""" - read: bool = False - """Indicates whether all read requests should be logged.""" - write: bool = False - """Indicates whether all write requests should be logged.""" - retention_policy: RetentionPolicy = RetentionPolicy() - """The retention policy for the metrics.""" - def __init__(self, **kwargs: Any) -> None: - self.version = kwargs.get("version", "1.0") - self.delete = kwargs.get("delete", False) - self.read = kwargs.get("read", False) - self.write = kwargs.get("write", False) - self.retention_policy = kwargs.get("retention_policy") or RetentionPolicy() + super().__init__( + version=kwargs.get("version", "1.0"), + delete=kwargs.get("delete", False), + read=kwargs.get("read", False), + write=kwargs.get("write", False), + retention_policy=kwargs.get("retention_policy") or RetentionPolicy(), + ) @classmethod def _from_generated(cls, generated: Any) -> Self: @@ -120,20 +105,13 @@ class Metrics(GeneratedMetrics): :keyword ~azure.storage.queue.RetentionPolicy retention_policy: The retention policy for the metrics. """ - version: str = "1.0" - """The version of Storage Analytics to configure.""" - enabled: bool = False - """Indicates whether metrics are enabled for the service.""" - include_apis: Optional[bool] - """Indicates whether metrics should generate summary statistics for called API operations.""" - retention_policy: RetentionPolicy = RetentionPolicy() - """The retention policy for the metrics.""" - def __init__(self, **kwargs: Any) -> None: - self.version = kwargs.get("version", "1.0") - self.enabled = kwargs.get("enabled", False) - self.include_apis = kwargs.get("include_apis") - self.retention_policy = kwargs.get("retention_policy") or RetentionPolicy() + super().__init__( + version=kwargs.get("version", "1.0"), + enabled=kwargs.get("enabled", False), + include_apis=kwargs.get("include_apis"), + retention_policy=kwargs.get("retention_policy") or RetentionPolicy(), + ) @classmethod def _from_generated(cls, generated: Any) -> Self: @@ -179,26 +157,14 @@ class CorsRule(GeneratedCorsRule): headers. Each header can be up to 256 characters. """ - allowed_origins: str - """The comma-delimited string representation of the list of origin domains that will be allowed via - CORS, or "*" to allow all domains.""" - allowed_methods: str - """The comma-delimited string representation of the list HTTP methods that are allowed to be executed - by the origin.""" - max_age_in_seconds: int - """The number of seconds that the client/browser should cache a pre-flight response.""" - exposed_headers: str - """The comma-delimited string representation of the list of response headers to expose to CORS clients.""" - allowed_headers: str - """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin - request.""" - def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: - self.allowed_origins = ",".join(allowed_origins) - self.allowed_methods = ",".join(allowed_methods) - self.allowed_headers = ",".join(kwargs.get("allowed_headers", [])) - self.exposed_headers = ",".join(kwargs.get("exposed_headers", [])) - self.max_age_in_seconds = kwargs.get("max_age_in_seconds", 0) + super().__init__( + allowed_origins=",".join(allowed_origins), + allowed_methods=",".join(allowed_methods), + allowed_headers=",".join(kwargs.get("allowed_headers", [])), + exposed_headers=",".join(kwargs.get("exposed_headers", [])), + max_age_in_seconds=kwargs.get("max_age_in_seconds", 0), + ) @staticmethod def _to_generated( @@ -340,13 +306,9 @@ class AccessPolicy(GenAccessPolicy): be interpreted as UTC. """ - permission: Optional[Union[QueueSasPermissions, str]] # type: ignore [assignment] - """The permissions associated with the shared access signature. The user is restricted to - operations allowed by the permissions.""" - expiry: Optional[Union["datetime", str]] # type: ignore [assignment] - """The time at which the shared access signature becomes invalid.""" - start: Optional[Union["datetime", str]] # type: ignore [assignment] - """The time at which the shared access signature becomes valid.""" + start: Optional[Union["datetime", str]] # type: ignore[assignment] + expiry: Optional[Union["datetime", str]] # type: ignore[assignment] + permission: Optional[Union[QueueSasPermissions, str]] # type: ignore[assignment] def __init__( self, @@ -354,9 +316,11 @@ def __init__( expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - self.start = start - self.expiry = expiry - self.permission = permission + super().__init__( + start=start, # type: ignore[arg-type] + expiry=expiry, # type: ignore[arg-type] + permission=permission, # type: ignore[arg-type] + ) class QueueMessage(DictMixin): @@ -397,7 +361,13 @@ def __init__(self, content: Optional[Any] = None, **kwargs: Any) -> None: @classmethod def _from_generated(cls, generated: Any) -> Self: - message = cls(content=generated.message_text) + # Prefer _decoded_content if set by MessageDecodePolicy (handles base64 decoding and decryption). + # The decode policy stores results in _decoded_content because the generated model's message_text + # RestField descriptor may re-serialize bytes back to base64 if set directly. + content = getattr(generated, "_decoded_content", None) + if content is None: + content = generated.message_text + message = cls(content=content) message.id = generated.message_id message.inserted_on = generated.insertion_time message.expires_on = generated.expiration_time @@ -457,11 +427,13 @@ def _get_next_cb(self, continuation_token: Optional[str]) -> Any: def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: # There is no concept of continuation token, so raising on my own condition - if not messages: + if not messages or not messages.items_property: raise StopIteration("End of paging") if self._max_messages is not None: - self._max_messages = self._max_messages - len(messages) - return "TOKEN_IGNORED", [QueueMessage._from_generated(q) for q in messages] # pylint: disable=protected-access + self._max_messages = self._max_messages - len(messages.items_property) + return "TOKEN_IGNORED", [ + QueueMessage._from_generated(q) for q in messages.items_property # pylint: disable=protected-access + ] class QueueProperties(DictMixin): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_client.py index 17205bbf69eb..c3aedc31c8fc 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_client.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -15,8 +16,8 @@ from azure.core.tracing.decorator import distributed_trace from ._deserialize import deserialize_queue_creation, deserialize_queue_properties from ._encryption import modify_user_agent_for_encryption, StorageEncryptionMixin -from ._generated import AzureQueueStorage -from ._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier +from ._generated import QueuesClient as AzureQueueStorage +from ._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers from ._message_encoding import NoDecodePolicy, NoEncodePolicy from ._models import AccessPolicy, MessagesPaged, QueueMessage from ._queue_client_helpers import _format_url, _from_queue_url, _parse_url @@ -133,12 +134,7 @@ def __init__( ) self._message_encode_policy = message_encode_policy or NoEncodePolicy() self._message_decode_policy = message_decode_policy or NoDecodePolicy() - self._client = AzureQueueStorage( - self.url, - get_api_version(api_version), - base_url=self.url, - pipeline=self._pipeline, - ) + self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) self._configure_encryption(kwargs) def __enter__(self) -> Self: @@ -489,12 +485,27 @@ def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An """ try: _, identifiers = cast( - Tuple[Dict, List], + Tuple[Dict, SignedIdentifiers], self._client.queue.get_access_policy(timeout=timeout, cls=return_headers_and_deserialized, **kwargs), ) except HttpResponseError as error: process_storage_error(error) - return {s.id: s.access_policy or AccessPolicy() for s in identifiers} + return ( + { + s.id: ( + AccessPolicy( + permission=s.access_policy.permission, + expiry=s.access_policy.expiry, + start=s.access_policy.start, + ) + if s.access_policy + else AccessPolicy() + ) + for s in (identifiers.items_property or []) + } + if identifiers + else {} + ) @distributed_trace def set_queue_access_policy( @@ -546,8 +557,9 @@ def set_queue_access_policy( value.start = serialize_iso(value.start) value.expiry = serialize_iso(value.expiry) identifiers.append(SignedIdentifier(id=key, access_policy=value)) + signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: - self._client.queue.set_access_policy(queue_acl=identifiers or None, timeout=timeout, **kwargs) + self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -641,20 +653,20 @@ def send_message( new_message = GenQueueMessage(message_text=encoded_content) try: - enqueued = self._client.messages.enqueue( + enqueued = self._client.queue.send_message( queue_message=new_message, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, message_time_to_live=time_to_live, timeout=timeout, **kwargs ) queue_message = QueueMessage( content=content, - id=enqueued[0].message_id, - inserted_on=enqueued[0].insertion_time, - expires_on=enqueued[0].expiration_time, - pop_receipt=enqueued[0].pop_receipt, - next_visible_on=enqueued[0].time_next_visible, + id=enqueued.items_property[0].message_id, + inserted_on=enqueued.items_property[0].insertion_time, + expires_on=enqueued.items_property[0].expiration_time, + pop_receipt=enqueued.items_property[0].pop_receipt, + next_visible_on=enqueued.items_property[0].time_next_visible, ) return queue_message except HttpResponseError as error: @@ -715,15 +727,17 @@ def receive_message( resolver=self.key_resolver_function, ) try: - message = self._client.messages.dequeue( + message = self._client.queue.receive_messages( number_of_messages=1, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message[0]) if message != [] else None # pylint: disable=protected-access + QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access + if message.items_property + else None ) return wrapped_message except HttpResponseError as error: @@ -812,8 +826,8 @@ def receive_messages( ) try: command = functools.partial( - self._client.messages.dequeue, - visibilitytimeout=visibility_timeout, + self._client.queue.receive_messages, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs @@ -943,13 +957,13 @@ def update_message( try: response = cast( QueueMessage, - self._client.message_id.update( + self._client.queue.update_message( queue_message=updated, - visibilitytimeout=visibility_timeout or 0, + visibility_timeout=visibility_timeout or 0, timeout=timeout, pop_receipt=receipt, cls=return_response_headers, - queue_message_id=message_id, + message_id=message_id, **kwargs ), ) @@ -1026,11 +1040,11 @@ def peek_messages( resolver=self.key_resolver_function, ) try: - messages = self._client.messages.peek( + messages = self._client.queue.peek_messages( number_of_messages=max_messages, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_messages = [] - for peeked in messages: + for peeked in messages.items_property or []: wrapped_messages.append(QueueMessage._from_generated(peeked)) # pylint: disable=protected-access return wrapped_messages except HttpResponseError as error: @@ -1057,7 +1071,7 @@ def clear_messages(self, *, timeout: Optional[int] = None, **kwargs: Any) -> Non :caption: Clears all messages. """ try: - self._client.messages.clear(timeout=timeout, **kwargs) + self._client.queue.clear(timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -1115,6 +1129,6 @@ def delete_message( if receipt is None: raise ValueError("pop_receipt must be present") try: - self._client.message_id.delete(pop_receipt=receipt, timeout=timeout, queue_message_id=message_id, **kwargs) + self._client.queue.delete_message(pop_receipt=receipt, timeout=timeout, message_id=message_id, **kwargs) except HttpResponseError as error: process_storage_error(error) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_service_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_service_client.py index 84fbef762fe0..00aa98bda6e2 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_service_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_service_client.py @@ -14,8 +14,8 @@ from azure.core.pipeline import Pipeline from azure.core.tracing.decorator import distributed_trace from ._encryption import StorageEncryptionMixin -from ._generated import AzureQueueStorage -from ._generated.models import KeyInfo, StorageServiceProperties +from ._generated import QueuesClient as AzureQueueStorage +from ._generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties from ._models import ( CorsRule, QueueProperties, @@ -133,12 +133,7 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage( - self.url, - get_api_version(api_version), - base_url=self.url, - pipeline=self._pipeline, - ) + self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) self._configure_encryption(kwargs) def __enter__(self) -> Self: @@ -440,7 +435,7 @@ def list_queues( """ include = ["metadata"] if include_metadata else None command = functools.partial( - self._client.service.list_queues_segment, + self._client.service.get_queues, prefix=name_starts_with, include=include, timeout=timeout, diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/authentication.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/authentication.py index cdbeeace2427..f778dc71eec4 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/authentication.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/authentication.py @@ -16,9 +16,7 @@ pass try: - from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import - AioHttpTransport, - ) + from azure.core.pipeline.transport import AioHttpTransport # pylint: disable=non-abstract-transport-import except ImportError: AioHttpTransport = None @@ -154,16 +152,9 @@ def _get_canonicalized_resource(self, request): try: if ( isinstance(request.context.transport, AioHttpTransport) + or isinstance(getattr(request.context.transport, "_transport", None), AioHttpTransport) or isinstance( - getattr(request.context.transport, "_transport", None), - AioHttpTransport, - ) - or isinstance( - getattr( - getattr(request.context.transport, "_transport", None), - "_transport", - None, - ), + getattr(getattr(request.context.transport, "_transport", None), "_transport", None), AioHttpTransport, ) ): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client.py index 86734de7a20b..fb62552c15b4 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client.py @@ -17,11 +17,7 @@ ) from urllib.parse import parse_qs, quote -from azure.core.credentials import ( - AzureSasCredential, - AzureNamedKeyCredential, - TokenCredential, -) +from azure.core.credentials import AzureSasCredential, AzureNamedKeyCredential, TokenCredential from azure.core.exceptions import HttpResponseError from azure.core.pipeline import Pipeline from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import, no-name-in-module @@ -68,10 +64,7 @@ if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential - from azure.core.pipeline.transport import ( # pylint: disable=C4756 - HttpRequest, - HttpResponse, - ) + from azure.core.pipeline.transport import HttpRequest, HttpResponse # pylint: disable=C4756 _LOGGER = logging.getLogger(__name__) _SERVICE_PARAMS = { @@ -174,12 +167,7 @@ def __init__( if not self._hosts: if kwargs.get("secondary_hostname"): secondary_hostname = kwargs["secondary_hostname"] - if not primary_hostname: - primary_hostname = (parsed_url.netloc + parsed_url.path).rstrip("/") - self._hosts = { - LocationMode.PRIMARY: primary_hostname, - LocationMode.SECONDARY: secondary_hostname, - } + self._hosts = {LocationMode.PRIMARY: primary_hostname, LocationMode.SECONDARY: secondary_hostname} self._sdk_moniker = f"storage-{service}/{VERSION}" self._config, self._pipeline = self._create_pipeline(self.credential, sdk_moniker=self._sdk_moniker, **kwargs) @@ -273,27 +261,12 @@ def _format_query_string( self, sas_token: Optional[str], credential: Optional[ - Union[ - str, - Dict[str, str], - "AzureNamedKeyCredential", - "AzureSasCredential", - TokenCredential, - ] + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", TokenCredential] ], snapshot: Optional[str] = None, share_snapshot: Optional[str] = None, ) -> Tuple[ - str, - Optional[ - Union[ - str, - Dict[str, str], - "AzureNamedKeyCredential", - "AzureSasCredential", - TokenCredential, - ] - ], + str, Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", TokenCredential]] ]: query_str = "?" if snapshot: @@ -315,13 +288,7 @@ def _format_query_string( def _create_pipeline( self, credential: Optional[ - Union[ - str, - Dict[str, str], - AzureNamedKeyCredential, - AzureSasCredential, - TokenCredential, - ] + Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential] ] = None, **kwargs: Any, ) -> Tuple[StorageConfiguration, Pipeline]: @@ -417,9 +384,7 @@ def _batch_send(self, *reqs: "HttpRequest", **kwargs: Any) -> Iterator["HttpResp parts = list(response.parts()) if any(p for p in parts if not 200 <= p.status_code < 300): error = PartialBatchErrorException( - message="There is a partial failure in the batch operation.", - response=response, - parts=parts, + message="There is a partial failure in the batch operation.", response=response, parts=parts ) raise error return iter(parts) @@ -456,14 +421,7 @@ def __exit__(self, *args): def _format_shared_key_credential( account_name: Optional[str], credential: Optional[ - Union[ - str, - Dict[str, str], - AzureNamedKeyCredential, - AzureSasCredential, - "AsyncTokenCredential", - TokenCredential, - ] + Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "AsyncTokenCredential", TokenCredential] ] = None, ) -> Any: if isinstance(credential, str): @@ -483,28 +441,12 @@ def _format_shared_key_credential( def parse_connection_str( conn_str: str, - credential: Optional[ - Union[ - str, - Dict[str, str], - AzureNamedKeyCredential, - AzureSasCredential, - TokenCredential, - ] - ], + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]], service: str, ) -> Tuple[ str, Optional[str], - Optional[ - Union[ - str, - Dict[str, str], - AzureNamedKeyCredential, - AzureSasCredential, - TokenCredential, - ] - ], + Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]], ]: conn_str = conn_str.rstrip(";") conn_settings_list = [s.split("=", 1) for s in conn_str.split(";")] @@ -518,10 +460,7 @@ def parse_connection_str( secondary = None if not credential: try: - credential = { - "account_name": conn_settings["ACCOUNTNAME"], - "account_key": conn_settings["ACCOUNTKEY"], - } + credential = {"account_name": conn_settings["ACCOUNTNAME"], "account_key": conn_settings["ACCOUNTKEY"]} except KeyError: credential = conn_settings.get("SHAREDACCESSSIGNATURE") if endpoints["primary"] in conn_settings: diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client_async.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client_async.py index 993c2cfb354f..d3403af8eaae 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client_async.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/base_client_async.py @@ -49,10 +49,7 @@ from .._shared_access_signature import _is_credential_sastoken if TYPE_CHECKING: - from azure.core.pipeline.transport import ( # pylint: disable=C4756 - HttpRequest, - HttpResponse, - ) + from azure.core.pipeline.transport import HttpRequest, HttpResponse # pylint: disable=C4756 _LOGGER = logging.getLogger(__name__) _SERVICE_PARAMS = { @@ -69,27 +66,12 @@ def _format_query_string( self, sas_token: Optional[str], credential: Optional[ - Union[ - str, - Dict[str, str], - "AzureNamedKeyCredential", - "AzureSasCredential", - AsyncTokenCredential, - ] + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", AsyncTokenCredential] ], snapshot: Optional[str] = None, share_snapshot: Optional[str] = None, ) -> Tuple[ - str, - Optional[ - Union[ - str, - Dict[str, str], - "AzureNamedKeyCredential", - "AzureSasCredential", - AsyncTokenCredential, - ] - ], + str, Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", AsyncTokenCredential]] ]: query_str = "?" if snapshot: @@ -110,22 +92,12 @@ def _format_query_string( def _create_pipeline( self, credential: Optional[ - Union[ - str, - Dict[str, str], - AzureNamedKeyCredential, - AzureSasCredential, - AsyncTokenCredential, - ] + Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential] ] = None, **kwargs: Any, ) -> Tuple[StorageConfiguration, AsyncPipeline]: self._credential_policy: Optional[ - Union[ - AsyncStorageBearerTokenCredentialPolicy, - SharedKeyCredentialPolicy, - AzureSasCredentialPolicy, - ] + Union[AsyncStorageBearerTokenCredentialPolicy, SharedKeyCredentialPolicy, AzureSasCredentialPolicy] ] = None if hasattr(credential, "get_token"): if kwargs.get("audience"): @@ -229,28 +201,12 @@ async def _batch_send(self, *reqs: "HttpRequest", **kwargs: Any) -> AsyncList["H def parse_connection_str( conn_str: str, - credential: Optional[ - Union[ - str, - Dict[str, str], - AzureNamedKeyCredential, - AzureSasCredential, - AsyncTokenCredential, - ] - ], + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential]], service: str, ) -> Tuple[ str, Optional[str], - Optional[ - Union[ - str, - Dict[str, str], - AzureNamedKeyCredential, - AzureSasCredential, - AsyncTokenCredential, - ] - ], + Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential]], ]: conn_str = conn_str.rstrip(";") conn_settings_list = [s.split("=", 1) for s in conn_str.split(";")] @@ -264,10 +220,7 @@ def parse_connection_str( secondary = None if not credential: try: - credential = { - "account_name": conn_settings["ACCOUNTNAME"], - "account_key": conn_settings["ACCOUNTKEY"], - } + credential = {"account_name": conn_settings["ACCOUNTNAME"], "account_key": conn_settings["ACCOUNTKEY"]} except KeyError: credential = conn_settings.get("SHAREDACCESSSIGNATURE") if endpoints["primary"] in conn_settings: diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/constants.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/constants.py index c9c2ba8f74d0..bd6ff89771be 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/constants.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/constants.py @@ -6,6 +6,7 @@ from .._serialize import _SUPPORTED_API_VERSIONS + X_MS_VERSION = _SUPPORTED_API_VERSIONS[-1] # Connection defaults @@ -13,9 +14,9 @@ READ_TIMEOUT = 60 DATA_BLOCK_SIZE = 256 * 1024 +DEFAULT_MAX_CONCURRENCY = 1 + DEFAULT_OAUTH_SCOPE = "/.default" STORAGE_OAUTH_SCOPE = "https://storage.azure.com/.default" SERVICE_HOST_BASE = "core.windows.net" - -DEFAULT_MAX_CONCURRENCY = 1 diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/models.py index 51565b636f6c..aa900a4f404a 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/models.py @@ -292,10 +292,7 @@ class ResourceTypes(object): _str: str def __init__( - self, - service: bool = False, - container: bool = False, - object: bool = False, # pylint: disable=redefined-builtin + self, service: bool = False, container: bool = False, object: bool = False # pylint: disable=redefined-builtin ) -> None: self.service = service self.container = container diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/parser.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/parser.py index f16230c9d702..7755398d8090 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/parser.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/parser.py @@ -53,10 +53,7 @@ def _filetime_to_datetime(filetime: str) -> Optional[datetime]: if temp_filetime == 0: return None - return datetime.fromtimestamp( - (temp_filetime - EPOCH_AS_FILETIME) / HUNDREDS_OF_NANOSECONDS, - tz=timezone.utc, - ) + return datetime.fromtimestamp((temp_filetime - EPOCH_AS_FILETIME) / HUNDREDS_OF_NANOSECONDS, tz=timezone.utc) except ValueError: pass diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies.py index f4f602d1c669..6948ec6a0755 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies.py @@ -72,12 +72,7 @@ def encode_base64(data: Union[bytes, str]) -> str: # Are we out of retries? def is_exhausted(settings): - retry_counts = ( - settings["total"], - settings["connect"], - settings["read"], - settings["status"], - ) + retry_counts = (settings["total"], settings["connect"], settings["read"], settings["status"]) retry_counts = list(filter(None, retry_counts)) if not retry_counts: return False @@ -147,12 +142,6 @@ def urljoin(base_url, stub_url): class QueueMessagePolicy(SansIOHTTPPolicy): def on_request(self, request): - # Hack to fix generated code adding '/messages' after SAS parameters - includes_messages = request.http_request.url.endswith("/messages") - if includes_messages: - request.http_request.url = request.http_request.url[: -(len("/messages"))] - request.http_request.url = urljoin(request.http_request.url, "messages") - message_id = request.context.options.pop("queue_message_id", None) if message_id: request.http_request.url = urljoin(request.http_request.url, message_id) @@ -269,16 +258,7 @@ def on_request(self, request: "PipelineRequest") -> None: parsed_qs["sig"] = "*****" # the SAS needs to be put back together - value = urlunparse( - ( - scheme, - netloc, - path, - params, - urlencode(parsed_qs), - fragment, - ) - ) + value = urlunparse((scheme, netloc, path, params, urlencode(parsed_qs), fragment)) _LOGGER.debug(" %r: %r", header, value) _LOGGER.debug("Request body:") @@ -674,16 +654,11 @@ def send(self, request): response = self.next.send(request) if is_retry(response, retry_settings["mode"]) or is_checksum_retry(response): retries_remaining = self.increment( - retry_settings, - request=request.http_request, - response=response.http_response, + retry_settings, request=request.http_request, response=response.http_response ) if retries_remaining: retry_hook( - retry_settings, - request=request.http_request, - response=response.http_response, - error=None, + retry_settings, request=request.http_request, response=response.http_response, error=None ) self.sleep(retry_settings, request.context.transport) continue @@ -693,12 +668,7 @@ def send(self, request): raise retries_remaining = self.increment(retry_settings, request=request.http_request, error=err) if retries_remaining: - retry_hook( - retry_settings, - request=request.http_request, - response=None, - error=err, - ) + retry_hook(retry_settings, request=request.http_request, response=None, error=err) self.sleep(retry_settings, request.context.transport) continue raise err diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies_async.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies_async.py index e1d13b1a83fa..a7891ec66456 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies_async.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies_async.py @@ -11,10 +11,7 @@ from typing import Any, Dict, TYPE_CHECKING from azure.core.exceptions import AzureError, StreamClosedError, StreamConsumedError -from azure.core.pipeline.policies import ( - AsyncBearerTokenCredentialPolicy, - AsyncHTTPPolicy, -) +from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy, AsyncHTTPPolicy from .authentication import AzureSigningError, StorageHttpChallenge from .constants import DEFAULT_OAUTH_SCOPE @@ -170,16 +167,11 @@ async def send(self, request): response = await self.next.send(request) if is_retry(response, retry_settings["mode"]) or await is_checksum_retry(response): retries_remaining = self.increment( - retry_settings, - request=request.http_request, - response=response.http_response, + retry_settings, request=request.http_request, response=response.http_response ) if retries_remaining: await retry_hook( - retry_settings, - request=request.http_request, - response=response.http_response, - error=None, + retry_settings, request=request.http_request, response=response.http_response, error=None ) await self.sleep(retry_settings, request.context.transport) continue @@ -189,12 +181,7 @@ async def send(self, request): raise retries_remaining = self.increment(retry_settings, request=request.http_request, error=err) if retries_remaining: - await retry_hook( - retry_settings, - request=request.http_request, - response=None, - error=err, - ) + await retry_hook(retry_settings, request=request.http_request, response=None, error=err) await self.sleep(retry_settings, request.context.transport) continue raise err diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/request_handlers.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/request_handlers.py index 699635565b18..b23f65859690 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/request_handlers.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/request_handlers.py @@ -12,6 +12,7 @@ import isodate + _LOGGER = logging.getLogger(__name__) _REQUEST_DELIMITER_PREFIX = "batch_" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/response_handlers.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/response_handlers.py index 5d9a5ee30fe9..19f9d1086c66 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/response_handlers.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/response_handlers.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -21,6 +22,7 @@ from .models import get_enum_value, StorageErrorCode, UserDelegationKey from .parser import _to_utc_datetime + SV_DOCS_URL = "https://learn.microsoft.com/rest/api/storageservices/versioning-for-the-azure-storage-services" _LOGGER = logging.getLogger(__name__) @@ -79,10 +81,7 @@ def return_context_and_deserialized(response, deserialized, response_headers): def return_raw_deserialized(response, *_): - return ( - response.http_response.location_mode, - response.context[ContentDecodePolicy.CONTEXT_NAME], - ) + return response.http_response.location_mode, response.context[ContentDecodePolicy.CONTEXT_NAME] def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # pylint:disable=too-many-statements, too-many-branches @@ -98,12 +97,7 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p # If it is one of those three then it has been serialized prior by the generated layer. if isinstance( storage_error, - ( - PartialBatchErrorException, - ClientAuthenticationError, - ResourceNotFoundError, - ResourceExistsError, - ), + (PartialBatchErrorException, ClientAuthenticationError, ResourceNotFoundError, ResourceExistsError), ): serialized = True error_code = storage_error.response.headers.get("x-ms-error-code") @@ -125,8 +119,7 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p error_dict = error_body.get("error", {}) elif not error_code: _LOGGER.warning( - "Unexpected return type %s from ContentDecodePolicy.deserialize_from_http_generics.", - type(error_body), + "Unexpected return type %s from ContentDecodePolicy.deserialize_from_http_generics.", type(error_body) ) error_dict = {"message": str(error_body)} @@ -143,15 +136,9 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p # This check would be unnecessary if we have already serialized the error if error_code and not serialized: error_code = StorageErrorCode(error_code) - if error_code in [ - StorageErrorCode.condition_not_met, - StorageErrorCode.blob_overwritten, - ]: + if error_code in [StorageErrorCode.condition_not_met, StorageErrorCode.blob_overwritten]: raise_error = ResourceModifiedError - if error_code in [ - StorageErrorCode.invalid_authentication_info, - StorageErrorCode.authentication_failed, - ]: + if error_code in [StorageErrorCode.invalid_authentication_info, StorageErrorCode.authentication_failed]: raise_error = ClientAuthenticationError if error_code in [ StorageErrorCode.resource_not_found, @@ -223,8 +210,16 @@ def parse_to_internal_user_delegation_key(service_user_delegation_key): internal_user_delegation_key.signed_oid = service_user_delegation_key.signed_oid internal_user_delegation_key.signed_tid = service_user_delegation_key.signed_tid internal_user_delegation_key.signed_delegated_user_tid = service_user_delegation_key.signed_delegated_user_tid - internal_user_delegation_key.signed_start = _to_utc_datetime(service_user_delegation_key.signed_start) - internal_user_delegation_key.signed_expiry = _to_utc_datetime(service_user_delegation_key.signed_expiry) + internal_user_delegation_key.signed_start = ( + service_user_delegation_key.signed_start + if isinstance(service_user_delegation_key.signed_start, str) + else _to_utc_datetime(service_user_delegation_key.signed_start) + ) + internal_user_delegation_key.signed_expiry = ( + service_user_delegation_key.signed_expiry + if isinstance(service_user_delegation_key.signed_expiry, str) + else _to_utc_datetime(service_user_delegation_key.signed_expiry) + ) internal_user_delegation_key.signed_service = service_user_delegation_key.signed_service internal_user_delegation_key.signed_version = service_user_delegation_key.signed_version internal_user_delegation_key.value = service_user_delegation_key.value diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/shared_access_signature.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/shared_access_signature.py index 60d2a3475f94..0f7016f11d96 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/shared_access_signature.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/shared_access_signature.py @@ -117,15 +117,7 @@ def __init__(self, account_name, account_key, x_ms_version=X_MS_VERSION): self.x_ms_version = x_ms_version def generate_account( - self, - services, - resource_types, - permission, - expiry, - start=None, - ip=None, - protocol=None, - sts_hook=None, + self, services, resource_types, permission, expiry, start=None, ip=None, protocol=None, sts_hook=None, **kwargs ) -> str: """ Generates a shared access signature for the account. @@ -167,6 +159,9 @@ def generate_account( :param str protocol: Specifies the protocol permitted for a request made. The default value is https,http. See :class:`~azure.storage.common.models.Protocol` for possible values. + :keyword str encryption_scope: + Optional. If specified, this is the encryption scope to use when sending requests + authorized with this SAS URI. :param sts_hook: For debugging purposes only. If provided, the hook is called with the string to sign that was used to generate the SAS. @@ -177,6 +172,7 @@ def generate_account( sas = _SharedAccessHelper() sas.add_base(permission, expiry, start, ip, protocol, self.x_ms_version) sas.add_account(services, resource_types) + sas.add_encryption_scope(**kwargs) sas.add_account_signature(self.account_name, self.account_key) if sts_hook is not None: @@ -198,6 +194,9 @@ def _add_query(self, name, val): if val: self.query_dict[name] = str(val) if val is not None else None + def add_encryption_scope(self, **kwargs): + self._add_query(QueryStringConstants.SIGNED_ENCRYPTION_SCOPE, kwargs.pop("encryption_scope", None)) + def add_base(self, permission, expiry, start, ip, protocol, x_ms_version): if isinstance(start, date): start = _to_utc_datetime(start) @@ -226,12 +225,7 @@ def add_account(self, services, resource_types): self._add_query(QueryStringConstants.SIGNED_RESOURCE_TYPES, resource_types) def add_override_response_headers( - self, - cache_control, - content_disposition, - content_encoding, - content_language, - content_type, + self, cache_control, content_disposition, content_encoding, content_language, content_type ): self._add_query(QueryStringConstants.SIGNED_CACHE_CONTROL, cache_control) self._add_query(QueryStringConstants.SIGNED_CONTENT_DISPOSITION, content_disposition) @@ -277,13 +271,10 @@ def get_value_to_append(query): + get_value_to_append(QueryStringConstants.SIGNED_IP) + get_value_to_append(QueryStringConstants.SIGNED_PROTOCOL) + get_value_to_append(QueryStringConstants.SIGNED_VERSION) - + "\n" # Signed Encryption Scope - always empty for queue + + get_value_to_append(QueryStringConstants.SIGNED_ENCRYPTION_SCOPE) ) - self._add_query( - QueryStringConstants.SIGNED_SIGNATURE, - sign_string(account_key, string_to_sign), - ) + self._add_query(QueryStringConstants.SIGNED_SIGNATURE, sign_string(account_key, string_to_sign)) self.string_to_sign = string_to_sign def get_token(self) -> str: diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads.py index 341d034fd07c..8eacc59d1a27 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads.py @@ -16,6 +16,7 @@ from .request_handlers import get_length from .response_handlers import return_response_headers + _LARGE_BLOB_UPLOAD_MAX_READ_BUFFER_SIZE = 4 * 1024 * 1024 _ERROR_VALUE_SHOULD_BE_SEEKABLE_STREAM = "{0} should be a seekable file-like/io.IOBase type stream object." @@ -112,12 +113,7 @@ def upload_substream_blocks( executor.submit(with_current_context(uploader.process_substream_block), u) for u in islice(upload_tasks, 0, max_concurrency) ] - range_ids = _parallel_uploads( - executor, - uploader.process_substream_block, - upload_tasks, - running_futures, - ) + range_ids = _parallel_uploads(executor, uploader.process_substream_block, upload_tasks, running_futures) else: range_ids = [uploader.process_substream_block(b) for b in uploader.get_substream_blocks()] if any(range_ids): @@ -170,10 +166,7 @@ def get_chunk_streams(self): # Buffer until we either reach the end of the stream or get a whole chunk. while True: if self.total_size: - read_size = min( - self.chunk_size - len(data), - self.total_size - (index + len(data)), - ) + read_size = min(self.chunk_size - len(data), self.total_size - (index + len(data))) temp = self.stream.read(read_size) if not isinstance(temp, bytes): raise TypeError("Blob data should be of type bytes.") @@ -269,9 +262,9 @@ def _upload_chunk(self, chunk_offset, chunk_data): index = f"{chunk_offset:032d}" block_id = encode_base64(url_quote(encode_base64(index))) self.service.stage_block( - block_id, - len(chunk_data), - chunk_data, + block_id=block_id, + content_length=len(chunk_data), + body=chunk_data, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -282,9 +275,9 @@ def _upload_substream_block(self, index, block_stream): try: block_id = f"BlockId{(index//self.chunk_size):05}" self.service.stage_block( - block_id, - len(block_stream), - block_stream, + block_id=block_id, + content_length=len(block_stream), + body=block_stream, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -318,8 +311,8 @@ def _upload_chunk(self, chunk_offset, chunk_data): **self.request_options, ) - if not self.parallel and self.request_options.get("modified_access_conditions"): - self.request_options["modified_access_conditions"].if_match = self.response_headers["etag"] + if not self.parallel and self.request_options.get("etag"): + self.request_options["etag"] = self.response_headers["etag"] def _upload_substream_block(self, index, block_stream): pass @@ -343,9 +336,7 @@ def _upload_chunk(self, chunk_offset, chunk_data): ) self.current_length = int(self.response_headers["blob_append_offset"]) else: - self.request_options["append_position_access_conditions"].append_position = ( - self.current_length + chunk_offset - ) + self.request_options["append_position"] = self.current_length + chunk_offset self.response_headers = self.service.append_block( body=chunk_data, content_length=len(chunk_data), diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads_async.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads_async.py index 388429a288a4..35787ea27ac5 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads_async.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/uploads_async.py @@ -189,10 +189,7 @@ async def get_chunk_streams(self): # Buffer until we either reach the end of the stream or get a whole chunk. while True: if self.total_size: - read_size = min( - self.chunk_size - len(data), - self.total_size - (index + len(data)), - ) + read_size = min(self.chunk_size - len(data), self.total_size - (index + len(data))) temp = self.stream.read(read_size) if inspect.isawaitable(temp): temp = await temp @@ -290,8 +287,8 @@ async def _upload_chunk(self, chunk_offset, chunk_data): index = f"{chunk_offset:032d}" block_id = encode_base64(url_quote(encode_base64(index))) await self.service.stage_block( - block_id, - len(chunk_data), + block_id=block_id, + content_length=len(chunk_data), body=chunk_data, data_stream_total=self.total_size, upload_stream_current=self.progress_total, @@ -303,9 +300,9 @@ async def _upload_substream_block(self, index, block_stream): try: block_id = f"BlockId{(index//self.chunk_size):05}" await self.service.stage_block( - block_id, - len(block_stream), - block_stream, + block_id=block_id, + content_length=len(block_stream), + body=block_stream, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -342,8 +339,8 @@ async def _upload_chunk(self, chunk_offset, chunk_data): **self.request_options, ) - if not self.parallel and self.request_options.get("modified_access_conditions"): - self.request_options["modified_access_conditions"].if_match = self.response_headers["etag"] + if not self.parallel and self.request_options.get("etag"): + self.request_options["etag"] = self.response_headers["etag"] async def _upload_substream_block(self, index, block_stream): pass @@ -367,9 +364,7 @@ async def _upload_chunk(self, chunk_offset, chunk_data): ) self.current_length = int(self.response_headers["blob_append_offset"]) else: - self.request_options["append_position_access_conditions"].append_position = ( - self.current_length + chunk_offset - ) + self.request_options["append_position"] = self.current_length + chunk_offset self.response_headers = await self.service.append_block( body=chunk_data, content_length=len(chunk_data), @@ -440,11 +435,7 @@ class AsyncIterStreamer: File-like streaming object for AsyncGenerators. """ - def __init__( - self, - generator: AsyncGenerator[Union[bytes, str], None], - encoding: str = "UTF-8", - ): + def __init__(self, generator: AsyncGenerator[Union[bytes, str], None], encoding: str = "UTF-8"): self.iterator = generator.__aiter__() self.leftover = b"" self.encoding = encoding diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py index a2ba5779ef0d..195162b92aac 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py @@ -1,7 +1,9 @@ +# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- VERSION = "12.18.0b1" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py index cbd506fbd183..90b04166b7ec 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py @@ -65,11 +65,13 @@ async def _get_next_cb(self, continuation_token: Optional[str]) -> Any: async def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: # There is no concept of continuation token, so raising on my own condition - if not messages: + if not messages or not messages.items_property: raise StopAsyncIteration("End of paging") if self._max_messages is not None: - self._max_messages = self._max_messages - len(messages) - return "TOKEN_IGNORED", [QueueMessage._from_generated(q) for q in messages] # pylint: disable=protected-access + self._max_messages = self._max_messages - len(messages.items_property) + return "TOKEN_IGNORED", [ + QueueMessage._from_generated(q) for q in messages.items_property # pylint: disable=protected-access + ] class QueuePropertiesPaged(AsyncPageIterator): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_client_async.py b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_client_async.py index ed1c7e8b64b6..98dc37871edd 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_client_async.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_client_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -17,8 +18,8 @@ from ._models import MessagesPaged from .._deserialize import deserialize_queue_creation, deserialize_queue_properties from .._encryption import modify_user_agent_for_encryption, StorageEncryptionMixin -from .._generated.aio import AzureQueueStorage -from .._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier +from .._generated.aio import QueuesClient as AzureQueueStorage +from .._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers from .._message_encoding import NoDecodePolicy, NoEncodePolicy from .._models import AccessPolicy, QueueMessage from .._queue_client_helpers import _format_url, _from_queue_url, _parse_url @@ -145,13 +146,7 @@ def __init__( self._message_encode_policy = message_encode_policy or NoEncodePolicy() self._message_decode_policy = message_decode_policy or NoDecodePolicy() - self._client = AzureQueueStorage( - self.url, - get_api_version(api_version), - base_url=self.url, - pipeline=self._pipeline, - loop=loop, - ) + self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) self._loop = loop self._configure_encryption(kwargs) @@ -503,14 +498,29 @@ async def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwar """ try: _, identifiers = cast( - Tuple[Dict, List], + Tuple[Dict, SignedIdentifiers], await self._client.queue.get_access_policy( timeout=timeout, cls=return_headers_and_deserialized, **kwargs ), ) except HttpResponseError as error: process_storage_error(error) - return {s.id: s.access_policy or AccessPolicy() for s in identifiers} + return ( + { + s.id: ( + AccessPolicy( + permission=s.access_policy.permission, + expiry=s.access_policy.expiry, + start=s.access_policy.start, + ) + if s.access_policy + else AccessPolicy() + ) + for s in (identifiers.items_property or []) + } + if identifiers + else {} + ) @distributed_trace_async async def set_queue_access_policy( @@ -562,8 +572,9 @@ async def set_queue_access_policy( value.start = serialize_iso(value.start) value.expiry = serialize_iso(value.expiry) identifiers.append(SignedIdentifier(id=key, access_policy=value)) + signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: - await self._client.queue.set_access_policy(queue_acl=identifiers or None, timeout=timeout, **kwargs) + await self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -657,20 +668,20 @@ async def send_message( new_message = GenQueueMessage(message_text=encoded_content) try: - enqueued = await self._client.messages.enqueue( + enqueued = await self._client.queue.send_message( queue_message=new_message, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, message_time_to_live=time_to_live, timeout=timeout, **kwargs ) queue_message = QueueMessage( content=content, - id=enqueued[0].message_id, - inserted_on=enqueued[0].insertion_time, - expires_on=enqueued[0].expiration_time, - pop_receipt=enqueued[0].pop_receipt, - next_visible_on=enqueued[0].time_next_visible, + id=enqueued.items_property[0].message_id, + inserted_on=enqueued.items_property[0].insertion_time, + expires_on=enqueued.items_property[0].expiration_time, + pop_receipt=enqueued.items_property[0].pop_receipt, + next_visible_on=enqueued.items_property[0].time_next_visible, ) return queue_message except HttpResponseError as error: @@ -731,15 +742,17 @@ async def receive_message( resolver=self.key_resolver_function, ) try: - message = await self._client.messages.dequeue( + message = await self._client.queue.receive_messages( number_of_messages=1, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message[0]) if message != [] else None # pylint: disable=protected-access + QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access + if message.items_property + else None ) return wrapped_message except HttpResponseError as error: @@ -818,8 +831,8 @@ def receive_messages( ) try: command = functools.partial( - self._client.messages.dequeue, - visibilitytimeout=visibility_timeout, + self._client.queue.receive_messages, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs @@ -949,13 +962,13 @@ async def update_message( try: response = cast( QueueMessage, - await self._client.message_id.update( + await self._client.queue.update_message( queue_message=updated, - visibilitytimeout=visibility_timeout or 0, + visibility_timeout=visibility_timeout or 0, timeout=timeout, pop_receipt=receipt, cls=return_response_headers, - queue_message_id=message_id, + message_id=message_id, **kwargs ), ) @@ -1032,11 +1045,11 @@ async def peek_messages( resolver=self.key_resolver_function, ) try: - messages = await self._client.messages.peek( + messages = await self._client.queue.peek_messages( number_of_messages=max_messages, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_messages = [] - for peeked in messages: + for peeked in messages.items_property or []: wrapped_messages.append(QueueMessage._from_generated(peeked)) # pylint: disable=protected-access return wrapped_messages except HttpResponseError as error: @@ -1063,7 +1076,7 @@ async def clear_messages(self, *, timeout: Optional[int] = None, **kwargs: Any) :caption: Clears all messages. """ try: - await self._client.messages.clear(timeout=timeout, **kwargs) + await self._client.queue.clear(timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -1121,8 +1134,8 @@ async def delete_message( if receipt is None: raise ValueError("pop_receipt must be present") try: - await self._client.message_id.delete( - pop_receipt=receipt, timeout=timeout, queue_message_id=message_id, **kwargs + await self._client.queue.delete_message( + pop_receipt=receipt, timeout=timeout, message_id=message_id, **kwargs ) except HttpResponseError as error: process_storage_error(error) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_service_client_async.py b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_service_client_async.py index bd694412a038..4340adad3871 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_service_client_async.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_service_client_async.py @@ -17,14 +17,9 @@ from ._models import QueuePropertiesPaged from ._queue_client_async import QueueClient from .._encryption import StorageEncryptionMixin -from .._generated.aio import AzureQueueStorage -from .._generated.models import KeyInfo, StorageServiceProperties -from .._models import ( - CorsRule, - QueueProperties, - service_properties_deserialize, - service_stats_deserialize, -) +from .._generated.aio import QueuesClient as AzureQueueStorage +from .._generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties +from .._models import CorsRule, QueueProperties, service_properties_deserialize, service_stats_deserialize from .._queue_service_client_helpers import _parse_url from .._serialize import get_api_version from .._shared.base_client import StorageAccountHostsMixin @@ -133,13 +128,7 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage( - self.url, - get_api_version(api_version), - base_url=self.url, - pipeline=self._pipeline, - loop=loop, - ) + self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) self._loop = loop self._configure_encryption(kwargs) @@ -441,7 +430,7 @@ def list_queues( """ include = ["metadata"] if include_metadata else None command = functools.partial( - self._client.service.list_queues_segment, + self._client.service.get_queues, prefix=name_starts_with, include=include, timeout=timeout, diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed b/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed index e69de29bb2d1..e5aff4f83af8 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index e0b490cb8fec..03e25174e0c7 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -1,3 +1,71 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-storage-queue" +authors = [ + { name = "Microsoft Corporation", email = "ascl@microsoft.com" }, +] +description = "Microsoft Corporation Azure Storage Queue Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.38.3", + "typing-extensions>=4.6.0", + "cryptography>=2.1.4", +] +dynamic = [ +"version", "readme" +] + +[project.optional-dependencies] +aio = [ + "azure-core[aio]>=1.38.3", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.storage.queue._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.storage", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] + [tool.azure-sdk-build] mypy = true pyright = false diff --git a/sdk/storage/azure-storage-queue/setup.py b/sdk/storage/azure-storage-queue/setup.py deleted file mode 100644 index a3791f2a8895..000000000000 --- a/sdk/storage/azure-storage-queue/setup.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import re -import os.path -from io import open -from setuptools import find_packages, setup # type: ignore - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-storage-queue" -PACKAGE_PPRINT_NAME = "Azure Queue Storage" - -# a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace("-", "/") -# a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace("-", ".") - -# Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) # type: ignore - -if not version: - raise RuntimeError("Cannot find version information") - -with open("README.md", encoding="utf-8") as f: - readme = f.read() -with open("CHANGELOG.md", encoding="utf-8") as f: - changelog = f.read() - -setup( - name=PACKAGE_NAME, - version=version, - include_package_data=True, - description=f"Microsoft Azure {PACKAGE_PPRINT_NAME} Client Library for Python", - long_description=readme + "\n\n" + changelog, - long_description_content_type="text/markdown", - license="MIT License", - author="Microsoft Corporation", - author_email="ascl@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-queue", - keywords="azure, azure sdk", - classifiers=[ - "Development Status :: 4 - Beta", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Programming Language :: Python :: 3.14", - "License :: OSI Approved :: MIT License", - ], - zip_safe=False, - packages=find_packages( - exclude=[ - # Exclude packages that will be covered by PEP420 or nspkg - "azure", - "azure.storage", - "tests", - "tests.queue", - "tests.common", - ] - ), - python_requires=">=3.9", - install_requires=[ - "azure-core>=1.37.0", - "cryptography>=2.1.4", - "typing-extensions>=4.6.0", - "isodate>=0.6.1", - ], - extras_require={ - "aio": [ - "azure-core[aio]>=1.37.0", - ], - }, -) diff --git a/sdk/storage/azure-storage-queue/tests/conftest.py b/sdk/storage/azure-storage-queue/tests/conftest.py index 8a80ea7d6c86..b247291ef191 100644 --- a/sdk/storage/azure-storage-queue/tests/conftest.py +++ b/sdk/storage/azure-storage-queue/tests/conftest.py @@ -14,6 +14,8 @@ add_header_regex_sanitizer, add_oauth_response_sanitizer, add_uri_string_sanitizer, + add_remove_header_sanitizer, + set_custom_default_matcher, add_uri_regex_sanitizer, test_proxy, ) @@ -37,6 +39,8 @@ def add_sanitizers(test_proxy): ) add_uri_string_sanitizer(target=".preprod.", value=".") + add_remove_header_sanitizer(headers="Accept") + set_custom_default_matcher(ignore_query_ordering=True) add_uri_regex_sanitizer( regex=r"(?<=[?&]sktid=)[^&#]+", value="00000000-0000-0000-0000-000000000000", diff --git a/sdk/storage/azure-storage-queue/tests/test_queue.py b/sdk/storage/azure-storage-queue/tests/test_queue.py index 9d52bed47640..03be57921936 100644 --- a/sdk/storage/azure-storage-queue/tests/test_queue.py +++ b/sdk/storage/azure-storage-queue/tests/test_queue.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/storage/azure-storage-queue/tests/test_queue_async.py b/sdk/storage/azure-storage-queue/tests/test_queue_async.py index afd0c99f95c5..ad7b6fa9484a 100644 --- a/sdk/storage/azure-storage-queue/tests/test_queue_async.py +++ b/sdk/storage/azure-storage-queue/tests/test_queue_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/storage/azure-storage-queue/tsp-location.yaml b/sdk/storage/azure-storage-queue/tsp-location.yaml new file mode 100644 index 000000000000..b785991fc1da --- /dev/null +++ b/sdk/storage/azure-storage-queue/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/storage/Microsoft.QueueStorage +commit: +repo: +additionalDirectories: