From e9affdb474ebfa4f0cc9c95a64447beead73aa71 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 10 Mar 2026 12:28:45 -0700 Subject: [PATCH 001/102] storage queue --- .../storage/queue/_generated/CHANGELOG.md | 7 + .../azure/storage/queue/_generated/LICENSE | 21 + .../storage/queue/_generated/MANIFEST.in | 7 + .../azure/storage/queue/_generated/README.md | 78 + .../storage/queue/_generated/_metadata.json | 6 + .../azure/storage/queue/_generated/_patch.py | 33 - .../storage/queue/_generated/aio/_patch.py | 33 - .../aio/operations/_message_id_operations.py | 220 -- .../aio/operations/_messages_operations.py | 388 ---- .../aio/operations/_queue_operations.py | 502 ----- .../aio/operations/_service_operations.py | 471 ----- .../queue/_generated/apiview-properties.json | 64 + .../queue/_generated/azure/__init__.py | 1 + .../_generated/azure/storage/__init__.py | 1 + .../{aio => azure/storage/queues}/__init__.py | 9 +- .../storage/queues/_client.py} | 64 +- .../storage/queues}/_configuration.py | 41 +- .../storage/queues}/_patch.py | 15 +- .../storage/queues}/_utils/__init__.py | 2 +- .../azure/storage/queues/_utils/model_base.py | 1362 ++++++++++++ .../storage/queues}/_utils/serialization.py | 2 +- .../azure/storage/queues/_version.py | 9 + .../storage/queues/aio}/__init__.py | 6 +- .../storage/queues/aio/_client.py} | 64 +- .../storage/queues}/aio/_configuration.py | 41 +- .../storage/queues/aio}/_patch.py | 15 +- .../queues}/aio/operations/__init__.py | 10 +- .../queues/aio/operations/_operations.py | 1445 +++++++++++++ .../storage/queues}/aio/operations/_patch.py | 15 +- .../storage/queues}/models/__init__.py | 44 +- .../storage/queues/models/_enums.py} | 73 +- .../azure/storage/queues/models/_models.py | 1263 +++++++++++ .../azure/storage/queues/models/_patch.py | 21 + .../storage/queues}/operations/__init__.py | 10 +- .../storage/queues/operations/_operations.py | 1843 +++++++++++++++++ .../azure/storage/queues/operations/_patch.py | 21 + .../{ => azure/storage/queues}/py.typed | 0 .../queue/_generated/dev_requirements.txt | 4 + .../queue/_generated/models/_models_py3.py | 947 --------- .../operations/_message_id_operations.py | 302 --- .../operations/_messages_operations.py | 541 ----- .../operations/_queue_operations.py | 704 ------- .../operations/_service_operations.py | 665 ------ .../storage/queue/_generated/pyproject.toml | 61 + .../queue/_generated/tsp-location.yaml | 4 + 45 files changed, 6474 insertions(+), 4961 deletions(-) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_metadata.json delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_messages_operations.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_queue_operations.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_service_operations.py create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/apiview-properties.json create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/__init__.py create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/__init__.py rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{aio => azure/storage/queues}/__init__.py (82%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{_azure_queue_storage.py => azure/storage/queues/_client.py} (60%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/_configuration.py (52%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{models => azure/storage/queues}/_patch.py (52%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/_utils/__init__.py (86%) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/model_base.py rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/_utils/serialization.py (99%) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_version.py rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues/aio}/__init__.py (84%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{aio/_azure_queue_storage.py => azure/storage/queues/aio/_client.py} (63%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/aio/_configuration.py (52%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{operations => azure/storage/queues/aio}/_patch.py (52%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/aio/operations/__init__.py (68%) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_operations.py rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/aio/operations/_patch.py (52%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/models/__init__.py (65%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{models/_azure_queue_storage_enums.py => azure/storage/queues/models/_enums.py} (61%) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_patch.py rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/operations/__init__.py (68%) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_operations.py create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_patch.py rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{ => azure/storage/queues}/py.typed (100%) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_message_id_operations.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_messages_operations.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_queue_operations.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_service_operations.py create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/pyproject.toml create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md new file mode 100644 index 000000000000..b957b2575b48 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0b1 (1970-01-01) + +### Other Changes + + - Initial version \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in new file mode 100644 index 000000000000..abf72b906875 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in @@ -0,0 +1,7 @@ +include *.md +include LICENSE +include azure/storage/queues/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/storage/__init__.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md new file mode 100644 index 000000000000..ae056634e4cf --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md @@ -0,0 +1,78 @@ +# Azure Storage Queue client library for Python + + +## Getting started + +### Install the package + +```bash +python -m pip install azure-storage-queue +``` + +#### Prequisites + +- Python 3.9 or later is required to use this package. +- You need an [Azure subscription][azure_sub] to use this package. +- An existing Azure Storage Queue instance. + +#### Create with an Azure Active Directory Credential +To use an [Azure Active Directory (AAD) token credential][authenticate_with_token], +provide an instance of the desired credential type obtained from the +[azure-identity][azure_identity_credentials] library. + +To authenticate with AAD, you must first [pip][pip] install [`azure-identity`][azure_identity_pip] + +After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use. +As an example, [DefaultAzureCredential][default_azure_credential] can be used to authenticate the client: + +Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: +`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET` + +Use the returned token credential to authenticate the client: + +```python +>>> from azure.storage.queues import QueuesClient +>>> from azure.identity import DefaultAzureCredential +>>> client = QueuesClient(endpoint='', credential=DefaultAzureCredential()) +``` + +## Examples + +```python +>>> from azure.storage.queues import QueuesClient +>>> from azure.identity import DefaultAzureCredential +>>> from azure.core.exceptions import HttpResponseError + +>>> client = QueuesClient(endpoint='', credential=DefaultAzureCredential()) +>>> try: + + except HttpResponseError as e: + print('service responds error: {}'.format(e.response.json())) + +``` + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct][code_of_conduct]. For more information, +see the Code of Conduct FAQ or contact opencode@microsoft.com with any +additional questions or comments. + + +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ +[authenticate_with_token]: https://docs.microsoft.com/azure/cognitive-services/authentication?tabs=powershell#authenticate-with-an-authentication-token +[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials +[azure_identity_pip]: https://pypi.org/project/azure-identity/ +[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential +[pip]: https://pypi.org/project/pip/ +[azure_sub]: https://azure.microsoft.com/free/ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_metadata.json b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_metadata.json new file mode 100644 index 000000000000..722c39b95657 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_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/azure/storage/queue/_generated/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py deleted file mode 100644 index 4688ca7f8ac2..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py +++ /dev/null @@ -1,33 +0,0 @@ -# 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. -# -# -------------------------------------------------------------------------- - -# 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 - - -def patch_sdk(): - pass 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 deleted file mode 100644 index 4688ca7f8ac2..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py +++ /dev/null @@ -1,33 +0,0 @@ -# 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. -# -# -------------------------------------------------------------------------- - -# 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 - - -def patch_sdk(): - pass 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 997087907907..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py +++ /dev/null @@ -1,220 +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: 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: - 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: @@ -62,24 +61,21 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential 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 @@ -92,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/azure/storage/queues/_configuration.py similarity index 52% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_configuration.py index 04adef0da253..dbd3023cb4b2 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_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" and None. 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/models/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py similarity index 52% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py index 5755fd181b3f..87676c65a8f0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py @@ -1,16 +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/_utils/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/__init__.py similarity index 86% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_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/azure/storage/queues/_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/azure/storage/queues/_utils/model_base.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/model_base.py new file mode 100644 index 000000000000..9616929f7415 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/model_base.py @@ -0,0 +1,1362 @@ +# 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: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + 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 = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + 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 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 = prop_meta.get("ns", model_meta.get("ns", None)) + 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 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._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_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: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("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} + + # if no ns for prop, use model's + 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): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + 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 = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "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: + 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": parent_meta.get("itemsNs", parent_meta.get("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: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + 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 _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + ET.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/azure/storage/queues/_utils/serialization.py similarity index 99% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/serialization.py index 6da830e0cf4a..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/azure/storage/queues/_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. # -------------------------------------------------------------------------- diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_version.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_version.py new file mode 100644 index 000000000000..be71c81bd282 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_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/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/__init__.py similarity index 84% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/__init__.py index a743737977f3..e6fceae27b60 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/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/azure/storage/queues/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/azure/storage/queues/aio/_client.py index 3b6b202768e2..67b9d0ff6415 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/azure/storage/queues/aio/_client.py @@ -2,48 +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 + :vartype service: azure.storage.queues.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. + :vartype queue: azure.storage.queues.aio.operations.QueueOperations + :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" and None. 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: @@ -62,18 +61,15 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential 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. @@ -81,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 @@ -94,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/azure/storage/queues/aio/_configuration.py similarity index 52% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_configuration.py index 1c90497920fe..8a5f480b8121 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/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" and None. 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/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py similarity index 52% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py index 5755fd181b3f..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/azure/storage/queues/aio/_patch.py @@ -1,16 +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/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/__init__.py similarity index 68% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/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/azure/storage/queues/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/azure/storage/queues/aio/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_operations.py new file mode 100644 index 000000000000..7d9cd9ac4557 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_operations.py @@ -0,0 +1,1445 @@ +# 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. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar, Union + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + 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.model_base import _deserialize_xml, _failsafe_deserialize_xml, _get_element +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_queue_clear_request, + build_queue_create_request, + build_queue_delete_message_request, + build_queue_delete_request, + build_queue_get_access_policy_request, + build_queue_get_metadata_request, + build_queue_peek_messages_request, + build_queue_receive_messages_request, + build_queue_send_message_request, + build_queue_set_access_policy_request, + build_queue_set_metadata_request, + build_queue_update_request, + build_service_get_properties_request, + build_service_get_queues_request, + build_service_get_statistics_request, + build_service_get_user_delegation_key_request, + build_service_set_properties_request, +) +from .._configuration import QueuesClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.queues.aio.QueuesClient`'s + :attr:`service` 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 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.queues.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.queues.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.queues.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.queues.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.queues.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.queues.models.ListQueuesIncludeType] + :return: ListQueuesResponse. The ListQueuesResponse is compatible with MutableMapping + :rtype: ~azure.storage.queues.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.queues.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 the queue with the same name already + exists, the operation fails. + + :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]: + 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_metadata(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_metadata_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, *, metadata: str, timeout: Optional[int] = None, **kwargs: Any) -> None: + """operation sets one or more user-defined name-value pairs for the specified queue. + + :keyword metadata: The metadata headers. Required. + :paramtype metadata: 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_set_metadata_request( + metadata=metadata, + 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 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.queues.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: _models.SignedIdentifiers, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """sets the permissions for the specified queue. + + :param queue_acl: The access control list for the queue. Required. + :type queue_acl: ~azure.storage.queues.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: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(queue_acl) + + _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.ListOfReceivedMessage: + """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: ListOfReceivedMessage. The ListOfReceivedMessage is compatible with MutableMapping + :rtype: ~azure.storage.queues.models.ListOfReceivedMessage + :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.ListOfReceivedMessage] = 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.ListOfReceivedMessage, 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.queues.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.queues.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.ListOfPeekedMessage: + """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: ListOfPeekedMessage. The ListOfPeekedMessage is compatible with MutableMapping + :rtype: ~azure.storage.queues.models.ListOfPeekedMessage + :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.ListOfPeekedMessage] = 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.ListOfPeekedMessage, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def update( + 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.queues.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_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/azure/storage/queues/aio/operations/_patch.py similarity index 52% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_patch.py index 5755fd181b3f..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/azure/storage/queues/aio/operations/_patch.py @@ -1,16 +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/models/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/__init__.py similarity index 65% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/__init__.py index c482b2b16d64..5e01d6501d1e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/__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 @@ -13,29 +13,34 @@ from ._patch import * # pylint: disable=unused-wildcard-import -from ._models_py3 import ( # type: ignore +from ._models import ( # type: ignore AccessPolicy, CorsRule, - DequeuedMessageItem, - EnqueuedMessage, + Error, GeoReplication, KeyInfo, - ListQueuesSegmentResponse, + ListOfPeekedMessage, + ListOfReceivedMessage, + ListOfSentMessage, + ListQueuesResponse, Logging, Metrics, - PeekedMessageItem, + PeekedMessage, QueueItem, QueueMessage, + QueueServiceProperties, + QueueServiceStats, + ReceivedMessage, RetentionPolicy, + SentMessage, SignedIdentifier, - StorageError, - StorageServiceProperties, - StorageServiceStats, + SignedIdentifiers, UserDelegationKey, ) -from ._azure_queue_storage_enums import ( # type: ignore +from ._enums import ( # type: ignore GeoReplicationStatusType, + ListQueuesIncludeType, StorageErrorCode, ) from ._patch import __all__ as _patch_all @@ -45,23 +50,28 @@ __all__ = [ "AccessPolicy", "CorsRule", - "DequeuedMessageItem", - "EnqueuedMessage", + "Error", "GeoReplication", "KeyInfo", - "ListQueuesSegmentResponse", + "ListOfPeekedMessage", + "ListOfReceivedMessage", + "ListOfSentMessage", + "ListQueuesResponse", "Logging", "Metrics", - "PeekedMessageItem", + "PeekedMessage", "QueueItem", "QueueMessage", + "QueueServiceProperties", + "QueueServiceStats", + "ReceivedMessage", "RetentionPolicy", + "SentMessage", "SignedIdentifier", - "StorageError", - "StorageServiceProperties", - "StorageServiceStats", + "SignedIdentifiers", "UserDelegationKey", "GeoReplicationStatusType", + "ListQueuesIncludeType", "StorageErrorCode", ] __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/models/_azure_queue_storage_enums.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_enums.py similarity index 61% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_azure_queue_storage_enums.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_enums.py index 8cc82a0f6df4..922eb5338c62 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_azure_queue_storage_enums.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_enums.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. # -------------------------------------------------------------------------- @@ -11,70 +11,139 @@ class GeoReplicationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The status of the secondary location.""" + """The geo replication status.""" LIVE = "live" + """The geo replication is live.""" BOOTSTRAP = "bootstrap" + """The geo replication is bootstrap.""" UNAVAILABLE = "unavailable" + """The geo replication is unavailable.""" + + +class ListQueuesIncludeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Include this parameter to specify that the queue's metadata be returned as part of the response + body. + """ + + METADATA = "metadata" + """Include metadata.""" class StorageErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Error codes returned by the service.""" ACCOUNT_ALREADY_EXISTS = "AccountAlreadyExists" + """AccountAlreadyExists.""" ACCOUNT_BEING_CREATED = "AccountBeingCreated" + """AccountBeingCreated.""" ACCOUNT_IS_DISABLED = "AccountIsDisabled" + """AccountIsDisabled.""" AUTHENTICATION_FAILED = "AuthenticationFailed" + """AuthenticationFailed.""" AUTHORIZATION_FAILURE = "AuthorizationFailure" + """AuthorizationFailure.""" CONDITION_HEADERS_NOT_SUPPORTED = "ConditionHeadersNotSupported" + """ConditionHeadersNotSupported.""" CONDITION_NOT_MET = "ConditionNotMet" + """ConditionNotMet.""" EMPTY_METADATA_KEY = "EmptyMetadataKey" + """EmptyMetadataKey.""" INSUFFICIENT_ACCOUNT_PERMISSIONS = "InsufficientAccountPermissions" + """InsufficientAccountPermissions.""" INTERNAL_ERROR = "InternalError" + """InternalError.""" INVALID_AUTHENTICATION_INFO = "InvalidAuthenticationInfo" + """InvalidAuthenticationInfo.""" INVALID_HEADER_VALUE = "InvalidHeaderValue" + """InvalidHeaderValue.""" INVALID_HTTP_VERB = "InvalidHttpVerb" + """InvalidHttpVerb.""" INVALID_INPUT = "InvalidInput" + """InvalidInput.""" INVALID_MD5 = "InvalidMd5" + """InvalidMd5.""" INVALID_METADATA = "InvalidMetadata" + """InvalidMetadata.""" INVALID_QUERY_PARAMETER_VALUE = "InvalidQueryParameterValue" + """InvalidQueryParameterValue.""" INVALID_RANGE = "InvalidRange" + """InvalidRange.""" INVALID_RESOURCE_NAME = "InvalidResourceName" + """InvalidResourceName.""" INVALID_URI = "InvalidUri" + """InvalidUri.""" INVALID_XML_DOCUMENT = "InvalidXmlDocument" + """InvalidXmlDocument.""" INVALID_XML_NODE_VALUE = "InvalidXmlNodeValue" + """InvalidXmlNodeValue.""" MD5_MISMATCH = "Md5Mismatch" + """Md5Mismatch.""" METADATA_TOO_LARGE = "MetadataTooLarge" + """MetadataTooLarge.""" MISSING_CONTENT_LENGTH_HEADER = "MissingContentLengthHeader" + """MissingContentLengthHeader.""" MISSING_REQUIRED_QUERY_PARAMETER = "MissingRequiredQueryParameter" + """MissingRequiredQueryParameter.""" MISSING_REQUIRED_HEADER = "MissingRequiredHeader" + """MissingRequiredHeader.""" MISSING_REQUIRED_XML_NODE = "MissingRequiredXmlNode" + """MissingRequiredXmlNode.""" MULTIPLE_CONDITION_HEADERS_NOT_SUPPORTED = "MultipleConditionHeadersNotSupported" + """MultipleConditionHeadersNotSupported.""" OPERATION_TIMED_OUT = "OperationTimedOut" + """OperationTimedOut.""" OUT_OF_RANGE_INPUT = "OutOfRangeInput" + """OutOfRangeInput.""" OUT_OF_RANGE_QUERY_PARAMETER_VALUE = "OutOfRangeQueryParameterValue" + """OutOfRangeQueryParameterValue.""" REQUEST_BODY_TOO_LARGE = "RequestBodyTooLarge" + """RequestBodyTooLarge.""" RESOURCE_TYPE_MISMATCH = "ResourceTypeMismatch" + """ResourceTypeMismatch.""" REQUEST_URL_FAILED_TO_PARSE = "RequestUrlFailedToParse" + """RequestUrlFailedToParse.""" RESOURCE_ALREADY_EXISTS = "ResourceAlreadyExists" + """ResourceAlreadyExists.""" RESOURCE_NOT_FOUND = "ResourceNotFound" + """ResourceNotFound.""" SERVER_BUSY = "ServerBusy" + """ServerBusy.""" UNSUPPORTED_HEADER = "UnsupportedHeader" + """UnsupportedHeader.""" UNSUPPORTED_XML_NODE = "UnsupportedXmlNode" + """UnsupportedXmlNode.""" UNSUPPORTED_QUERY_PARAMETER = "UnsupportedQueryParameter" + """UnsupportedQueryParameter.""" UNSUPPORTED_HTTP_VERB = "UnsupportedHttpVerb" + """UnsupportedHttpVerb.""" INVALID_MARKER = "InvalidMarker" + """InvalidMarker.""" MESSAGE_NOT_FOUND = "MessageNotFound" + """MessageNotFound.""" MESSAGE_TOO_LARGE = "MessageTooLarge" + """MessageTooLarge.""" POP_RECEIPT_MISMATCH = "PopReceiptMismatch" + """PopReceiptMismatch.""" QUEUE_ALREADY_EXISTS = "QueueAlreadyExists" + """QueueAlreadyExists.""" QUEUE_BEING_DELETED = "QueueBeingDeleted" + """QueueBeingDeleted.""" QUEUE_DISABLED = "QueueDisabled" + """QueueDisabled.""" QUEUE_NOT_EMPTY = "QueueNotEmpty" + """QueueNotEmpty.""" QUEUE_NOT_FOUND = "QueueNotFound" + """QueueNotFound.""" AUTHORIZATION_SOURCE_IP_MISMATCH = "AuthorizationSourceIPMismatch" + """AuthorizationSourceIPMismatch.""" AUTHORIZATION_PROTOCOL_MISMATCH = "AuthorizationProtocolMismatch" + """AuthorizationProtocolMismatch.""" AUTHORIZATION_PERMISSION_MISMATCH = "AuthorizationPermissionMismatch" + """AuthorizationPermissionMismatch.""" AUTHORIZATION_SERVICE_MISMATCH = "AuthorizationServiceMismatch" + """AuthorizationServiceMismatch.""" AUTHORIZATION_RESOURCE_TYPE_MISMATCH = "AuthorizationResourceTypeMismatch" + """AuthorizationResourceTypeMismatch.""" FEATURE_VERSION_MISMATCH = "FeatureVersionMismatch" + """FeatureVersionMismatch.""" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py new file mode 100644 index 000000000000..88142f05df56 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py @@ -0,0 +1,1263 @@ +# pylint: disable=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=useless-super-delegation + +import datetime +from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class AccessPolicy(_Model): + """Represents an access policy. + + :ivar start: The date-time the policy is active. + :vartype start: ~datetime.datetime + :ivar expiry: The date-time the policy expires. + :vartype expiry: ~datetime.datetime + :ivar permission: The permissions for acl the policy. + :vartype permission: str + """ + + start: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + ) + """The date-time the policy is active.""" + expiry: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, + ) + """The date-time the policy expires.""" + permission: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Permission", "text": False, "unwrapped": False}, + ) + """The permissions for acl the policy.""" + + _xml = {"attribute": False, "name": "AccessPolicy", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + start: Optional[datetime.datetime] = None, + expiry: Optional[datetime.datetime] = None, + permission: 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 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. + + This defines the wire format only. Language SDKs wrap this in idiomatic error types. + + :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.queues.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.queues.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 + """ + + status: Union[str, "_models.GeoReplicationStatusType"] = 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.GeoReplicationStatusType"], + 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: ~datetime.datetime + :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. + :vartype expiry: ~datetime.datetime + :ivar delegated_user_tid: The delegated user tenant id in Azure AD. + :vartype delegated_user_tid: str + """ + + start: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + ) + """The date-time the key is active in ISO 8601 UTC time.""" + expiry: datetime.datetime = rest_field( + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + 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: datetime.datetime, + start: Optional[datetime.datetime] = 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 ListOfPeekedMessage(_Model): + """List wrapper for PeekedMessageItem array. + + :ivar items_property: The list of peeked messages. Required. + :vartype items_property: ~azure.storage.queues.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 ListOfReceivedMessage(_Model): + """List wrapper for DequeuedMessageItem array. + + :ivar items_property: The list of dequeued messages. Required. + :vartype items_property: ~azure.storage.queues.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 ListOfSentMessage(_Model): + """List wrapper for EnqueuedMessage array. + + :ivar items_property: The list of enqueued messages. Required. + :vartype items_property: ~azure.storage.queues.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.queues.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.queues.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.queues.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": "PeekedMessage", "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 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.queues.models.Logging + :ivar hour_metrics: The hour metrics properties. + :vartype hour_metrics: ~azure.storage.queues.models.Metrics + :ivar minute_metrics: The minute metrics properties. + :vartype minute_metrics: ~azure.storage.queues.models.Metrics + :ivar cors: The CORS properties. + :vartype cors: ~azure.storage.queues.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.queues.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": "ReceivedMessage", "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 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": "SentMessage", "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.queues.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.queues.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: ~datetime.datetime + :ivar signed_expiry: The date-time the key expires. Required. + :vartype signed_expiry: ~datetime.datetime + :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: datetime.datetime = rest_field( + name="signedStart", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "SignedStart", "text": False, "unwrapped": False}, + ) + """The date-time the key is active. Required.""" + signed_expiry: datetime.datetime = rest_field( + name="signedExpiry", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + 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: datetime.datetime, + signed_expiry: datetime.datetime, + 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/azure/storage/queues/models/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_patch.py @@ -0,0 +1,21 @@ +# 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 +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """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/operations/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/__init__.py similarity index 68% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/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/azure/storage/queues/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/azure/storage/queues/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_operations.py new file mode 100644 index 000000000000..0cceddaa5071 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_operations.py @@ -0,0 +1,1843 @@ +# 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. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar, Union + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + 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 QueuesClientConfiguration +from .._utils.model_base import _deserialize_xml, _failsafe_deserialize_xml, _get_element +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_service_set_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 {}) + + 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_metadata_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(*, metadata: 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 = "?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") + _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: str = kwargs.pop("content_type") + 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") + _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_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: str = kwargs.pop("content_type") + 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") + _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.queues.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.queues.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.queues.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.queues.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.queues.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.queues.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.queues.models.ListQueuesIncludeType] + :return: ListQueuesResponse. The ListQueuesResponse is compatible with MutableMapping + :rtype: ~azure.storage.queues.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.queues.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 the queue with the same name already + exists, the operation fails. + + :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]: + 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_metadata( # 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_metadata_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, *, metadata: str, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """operation sets one or more user-defined name-value pairs for the specified queue. + + :keyword metadata: The metadata headers. Required. + :paramtype metadata: 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_set_metadata_request( + metadata=metadata, + 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 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.queues.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: _models.SignedIdentifiers, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """sets the permissions for the specified queue. + + :param queue_acl: The access control list for the queue. Required. + :type queue_acl: ~azure.storage.queues.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: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(queue_acl) + + _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.ListOfReceivedMessage: + """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: ListOfReceivedMessage. The ListOfReceivedMessage is compatible with MutableMapping + :rtype: ~azure.storage.queues.models.ListOfReceivedMessage + :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.ListOfReceivedMessage] = 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.ListOfReceivedMessage, 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.queues.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.queues.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.ListOfPeekedMessage: + """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: ListOfPeekedMessage. The ListOfPeekedMessage is compatible with MutableMapping + :rtype: ~azure.storage.queues.models.ListOfPeekedMessage + :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.ListOfPeekedMessage] = 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.ListOfPeekedMessage, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def update( # 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.queues.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_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/azure/storage/queues/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_patch.py new file mode 100644 index 000000000000..87676c65a8f0 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_patch.py @@ -0,0 +1,21 @@ +# 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 +""" + + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """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/py.typed b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/py.typed similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/py.typed rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/py.typed diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt new file mode 100644 index 000000000000..ad0907b03b93 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt @@ -0,0 +1,4 @@ +-e ../../../eng/tools/azure-sdk-tools +../../core/azure-core +../../identity/azure-identity +aiohttp \ No newline at end of file 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 825f04418cf0..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py +++ /dev/null @@ -1,947 +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/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 {}) - - 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 =77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-storage-queue" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@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.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.storage.queues._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"] diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml new file mode 100644 index 000000000000..b785991fc1da --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/storage/Microsoft.QueueStorage +commit: +repo: +additionalDirectories: From bffece210b656a3e8d3796dc0b74b144d606d2aa Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 10 Mar 2026 13:03:11 -0700 Subject: [PATCH 002/102] basic changes --- .../_generated/azure/storage/queues/_patch.py | 36 ++++++++++++++++++- .../azure/storage/queues/aio/_patch.py | 36 ++++++++++++++++++- .../azure/storage/queue/_models.py | 10 +++--- .../azure/storage/queue/_queue_client.py | 6 ++-- .../storage/queue/_queue_service_client.py | 6 ++-- .../storage/queue/aio/_queue_client_async.py | 6 ++-- .../queue/aio/_queue_service_client_async.py | 6 ++-- 7 files changed, 87 insertions(+), 19 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py index 87676c65a8f0..3ec106b3b5c2 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py @@ -7,9 +7,43 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, TYPE_CHECKING +from azure.core import PipelineClient -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +from ._configuration import QueuesClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import QueueOperations, ServiceOperations +from ._client import QueuesClient as _QueuesClient + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class QueuesClient(_QueuesClient): + """QueuesClient that supports being instantiated with a pre-built pipeline.""" + + def __init__(self, url: str, credential: "TokenCredential" = None, **kwargs: Any) -> None: + _pipeline = kwargs.pop("pipeline", None) + if _pipeline is not None: + # When a pre-built pipeline is provided, skip the generated credential/policy setup. + _endpoint = "{url}" + self._config = QueuesClientConfiguration.__new__(QueuesClientConfiguration) + version = kwargs.pop("version", "2026-04-06") + self._config.url = url + self._config.credential = credential + self._config.version = version + self._client: PipelineClient = PipelineClient(base_url=_endpoint, 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(): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py index 87676c65a8f0..3824d31d6dc4 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py @@ -7,9 +7,43 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, TYPE_CHECKING +from azure.core import AsyncPipelineClient -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +from .._configuration import QueuesClientConfiguration +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 QueuesClient(_QueuesClient): + """QueuesClient that supports being instantiated with a pre-built pipeline.""" + + def __init__(self, url: str, credential: "AsyncTokenCredential" = None, **kwargs: Any) -> None: + _pipeline = kwargs.pop("pipeline", None) + if _pipeline is not None: + # When a pre-built pipeline is provided, skip the generated credential/policy setup. + _endpoint = "{url}" + self._config = QueuesClientConfiguration.__new__(QueuesClientConfiguration) + version = kwargs.pop("version", "2026-04-06") + self._config.url = url + self._config.credential = credential + self._config.version = version + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, 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(): 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 6d7faf9e860e..4ffc9dde8d41 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -11,11 +11,11 @@ from azure.core.paging import PageIterator from ._shared.response_handlers import process_storage_error, return_context_and_deserialized from ._shared.models import DictMixin -from ._generated.models import AccessPolicy as GenAccessPolicy -from ._generated.models import CorsRule as GeneratedCorsRule -from ._generated.models import Logging as GeneratedLogging -from ._generated.models import Metrics as GeneratedMetrics -from ._generated.models import RetentionPolicy as GeneratedRetentionPolicy +from ._generated.azure.storage.queues.models import AccessPolicy as GenAccessPolicy +from ._generated.azure.storage.queues.models import CorsRule as GeneratedCorsRule +from ._generated.azure.storage.queues.models import Logging as GeneratedLogging +from ._generated.azure.storage.queues.models import Metrics as GeneratedMetrics +from ._generated.azure.storage.queues.models import RetentionPolicy as GeneratedRetentionPolicy if sys.version_info >= (3, 11): from typing import Self 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 7812bffb9602..383ec82763c2 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 @@ -15,8 +15,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.azure.storage.queues import QueuesClient as AzureQueueStorage +from ._generated.azure.storage.queues.models import QueueMessage as GenQueueMessage, SignedIdentifier from ._message_encoding import NoDecodePolicy, NoEncodePolicy from ._models import AccessPolicy, MessagesPaged, QueueMessage from ._queue_client_helpers import _format_url, _from_queue_url, _parse_url @@ -120,7 +120,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.url, version=get_api_version(api_version), pipeline=self._pipeline ) self._configure_encryption(kwargs) 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 4c2004122960..e1067d24e8ad 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.azure.storage.queues import QueuesClient as AzureQueueStorage +from ._generated.azure.storage.queues.models import KeyInfo, QueueServiceProperties as StorageServiceProperties from ._models import ( CorsRule, QueueProperties, @@ -117,7 +117,7 @@ def __init__( **kwargs, ) self._client = AzureQueueStorage( - self.url, get_api_version(api_version), base_url=self.url, pipeline=self._pipeline + self.url, version=get_api_version(api_version), pipeline=self._pipeline ) self._configure_encryption(kwargs) 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 5134ea26a5ad..027a55e70915 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 @@ -17,8 +17,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.azure.storage.queues.aio import QueuesClient as AzureQueueStorage +from .._generated.azure.storage.queues.models import QueueMessage as GenQueueMessage, SignedIdentifier from .._message_encoding import NoDecodePolicy, NoEncodePolicy from .._models import AccessPolicy, QueueMessage from .._queue_client_helpers import _format_url, _from_queue_url, _parse_url @@ -133,7 +133,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.url, version=get_api_version(api_version), pipeline=self._pipeline ) self._loop = loop self._configure_encryption(kwargs) 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 dfb65bfccd3a..1b4ebfafdb55 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,8 +17,8 @@ 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 .._generated.azure.storage.queues.aio import QueuesClient as AzureQueueStorage +from .._generated.azure.storage.queues.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 @@ -116,7 +116,7 @@ def __init__( **kwargs, ) self._client = AzureQueueStorage( - self.url, get_api_version(api_version), base_url=self.url, pipeline=self._pipeline, loop=loop + self.url, version=get_api_version(api_version), pipeline=self._pipeline ) self._loop = loop self._configure_encryption(kwargs) From c8ce399a2f9dea9d3efe14925c50c6c891ada5ed Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 10 Mar 2026 13:08:55 -0700 Subject: [PATCH 003/102] filter conftest --- sdk/storage/azure-storage-queue/tests/conftest.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sdk/storage/azure-storage-queue/tests/conftest.py b/sdk/storage/azure-storage-queue/tests/conftest.py index ca09905c2ca6..859f29f11189 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, test_proxy, ) @@ -33,3 +35,5 @@ def add_sanitizers(test_proxy): add_general_regex_sanitizer(regex=r'"EncryptionLibrary": "Python .*?"', value='"EncryptionLibrary": "Python x.x.x"') add_uri_string_sanitizer(target=".preprod.", value=".") + add_remove_header_sanitizer(headers="Accept") + set_custom_default_matcher(excluded_headers="Accept") From 703f7c143d6d0caa432d16355f3240ac83c3e92b Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 11 Mar 2026 11:42:39 -0700 Subject: [PATCH 004/102] fixing test issues --- .../azure/storage/queue/_message_encoding.py | 3 +- .../azure/storage/queue/_models.py | 47 ++++++++++--------- .../azure/storage/queue/_queue_client.py | 45 +++++++++--------- .../storage/queue/_queue_service_client.py | 2 +- .../azure/storage/queue/aio/_models.py | 6 +-- .../storage/queue/aio/_queue_client_async.py | 47 ++++++++++--------- .../queue/aio/_queue_service_client_async.py | 2 +- .../azure-storage-queue/tests/conftest.py | 2 +- 8 files changed, 80 insertions(+), 74 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py index bd62f9933338..486caaf47996 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py @@ -72,7 +72,8 @@ def __init__(self) -> 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 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 4ffc9dde8d41..afa8caaf1304 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -45,8 +45,7 @@ class RetentionPolicy(GeneratedRetentionPolicy): """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 + super().__init__(enabled=enabled, days=days) if self.enabled and (self.days is None): raise ValueError("If policy is enabled, 'days' must be specified.") @@ -84,11 +83,13 @@ class QueueAnalyticsLogging(GeneratedLogging): """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: @@ -127,10 +128,12 @@ class Metrics(GeneratedMetrics): """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: @@ -191,11 +194,13 @@ class CorsRule(GeneratedCorsRule): 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(rules: Optional[List["CorsRule"]]) -> Optional[List[GeneratedCorsRule]]: @@ -343,9 +348,7 @@ 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, expiry=expiry, permission=permission) class QueueMessage(DictMixin): @@ -446,11 +449,11 @@ 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 383ec82763c2..254c2f2b3058 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 @@ -16,7 +16,7 @@ from ._deserialize import deserialize_queue_creation, deserialize_queue_properties from ._encryption import modify_user_agent_for_encryption, StorageEncryptionMixin from ._generated.azure.storage.queues import QueuesClient as AzureQueueStorage -from ._generated.azure.storage.queues.models import QueueMessage as GenQueueMessage, SignedIdentifier +from ._generated.azure.storage.queues.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 @@ -391,7 +391,7 @@ def get_queue_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) try: response = cast( "QueueProperties", - self._client.queue.get_properties(timeout=timeout, cls=deserialize_queue_properties, **kwargs), + self._client.queue.get_metadata(timeout=timeout, cls=deserialize_queue_properties, **kwargs), ) except HttpResponseError as error: process_storage_error(error) @@ -509,8 +509,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) @@ -601,20 +602,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: @@ -672,15 +673,15 @@ 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]) if message.items_property else None # pylint: disable=protected-access ) return wrapped_message except HttpResponseError as error: @@ -766,8 +767,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 @@ -892,13 +893,13 @@ def update_message( try: response = cast( QueueMessage, - self._client.message_id.update( + self._client.queue.update( 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 ), ) @@ -972,11 +973,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: @@ -1003,7 +1004,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) @@ -1061,6 +1062,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 e1067d24e8ad..c4fc5634d06b 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 @@ -411,7 +411,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/aio/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py index 5a1dfba70bde..4739611c8781 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 @@ -62,11 +62,11 @@ 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 027a55e70915..ae69b14e10a6 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 @@ -18,7 +18,7 @@ from .._deserialize import deserialize_queue_creation, deserialize_queue_properties from .._encryption import modify_user_agent_for_encryption, StorageEncryptionMixin from .._generated.azure.storage.queues.aio import QueuesClient as AzureQueueStorage -from .._generated.azure.storage.queues.models import QueueMessage as GenQueueMessage, SignedIdentifier +from .._generated.azure.storage.queues.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 @@ -405,7 +405,7 @@ async def get_queue_properties(self, *, timeout: Optional[int] = None, **kwargs: try: response = cast( "QueueProperties", - await self._client.queue.get_properties(timeout=timeout, cls=deserialize_queue_properties, **kwargs), + await self._client.queue.get_metadata(timeout=timeout, cls=deserialize_queue_properties, **kwargs), ) except HttpResponseError as error: process_storage_error(error) @@ -525,8 +525,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) @@ -617,20 +618,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: @@ -688,15 +689,15 @@ 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]) if message.items_property else None # pylint: disable=protected-access ) return wrapped_message except HttpResponseError as error: @@ -772,8 +773,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 @@ -898,13 +899,13 @@ async def update_message( try: response = cast( QueueMessage, - await self._client.message_id.update( + await self._client.queue.update( 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 ), ) @@ -978,11 +979,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: @@ -1009,7 +1010,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) @@ -1067,8 +1068,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 1b4ebfafdb55..24ee8ef0fb04 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 @@ -410,7 +410,7 @@ def list_queues( """ include = ["metadata"] if include_metadata else None command = functools.partial( - self._client.service.list_queues_segment, + self._client.service.list_queues, prefix=name_starts_with, include=include, timeout=timeout, diff --git a/sdk/storage/azure-storage-queue/tests/conftest.py b/sdk/storage/azure-storage-queue/tests/conftest.py index 859f29f11189..0b7f0d23f613 100644 --- a/sdk/storage/azure-storage-queue/tests/conftest.py +++ b/sdk/storage/azure-storage-queue/tests/conftest.py @@ -36,4 +36,4 @@ def add_sanitizers(test_proxy): add_uri_string_sanitizer(target=".preprod.", value=".") add_remove_header_sanitizer(headers="Accept") - set_custom_default_matcher(excluded_headers="Accept") + set_custom_default_matcher(excluded_headers="Accept", ignore_query_ordering=True) From 550b8a94354509443011a95adaae9e143ed89d61 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 11 Mar 2026 15:10:16 -0700 Subject: [PATCH 005/102] missing init --- .../azure/storage/queue/_generated/__init__.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py 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 new file mode 100644 index 000000000000..006671542af8 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py @@ -0,0 +1,5 @@ +# 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. +# -------------------------------------------------------------------------- From 14b57c59a5314c3601fe00fdb77e0046951e17cc Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 11 Mar 2026 15:43:36 -0700 Subject: [PATCH 006/102] update response handler to handle stirng --- .../queue/_shared/response_handlers.py | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) 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 40faa840cfbf..a072ebf470a4 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 @@ -176,11 +176,8 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p error_message += f"\n{name}:{info}" if additional_data.get("headername") == "x-ms-version" and error_code == StorageErrorCode.INVALID_HEADER_VALUE: - error_message = ( - "The provided service version is not enabled on this storage account." - + f"Please see {SV_DOCS_URL} for additional information.\n" - + error_message - ) + error_message = ("The provided service version is not enabled on this storage account." + + f"Please see {SV_DOCS_URL} for additional information.\n" + error_message) # No need to create an instance if it has already been serialized by the generated layer if serialized: @@ -205,9 +202,17 @@ 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 - return internal_user_delegation_key + return internal_user_delegation_key \ No newline at end of file From 32083968c64a5931d9daf48beb7559c95a1a554d Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 11 Mar 2026 15:53:20 -0700 Subject: [PATCH 007/102] userdelegationkey --- .../azure/storage/queues/models/_models.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py index 88142f05df56..95c70233a91d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py @@ -1172,9 +1172,9 @@ class UserDelegationKey(_Model): :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 + :vartype signed_start: str :ivar signed_expiry: The date-time the key expires. Required. - :vartype signed_expiry: ~datetime.datetime + :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. @@ -1198,17 +1198,15 @@ class UserDelegationKey(_Model): xml={"attribute": False, "name": "SignedTid", "text": False, "unwrapped": False}, ) """The Azure Active Directory tenant ID in GUID format. Required.""" - signed_start: datetime.datetime = rest_field( + signed_start: str = rest_field( name="signedStart", visibility=["read", "create", "update", "delete", "query"], - format="rfc7231", xml={"attribute": False, "name": "SignedStart", "text": False, "unwrapped": False}, ) """The date-time the key is active. Required.""" - signed_expiry: datetime.datetime = rest_field( + signed_expiry: str = rest_field( name="signedExpiry", visibility=["read", "create", "update", "delete", "query"], - format="rfc7231", xml={"attribute": False, "name": "SignedExpiry", "text": False, "unwrapped": False}, ) """The date-time the key expires. Required.""" @@ -1244,8 +1242,8 @@ def __init__( *, signed_oid: str, signed_tid: str, - signed_start: datetime.datetime, - signed_expiry: datetime.datetime, + signed_start: str, + signed_expiry: str, signed_service: str, signed_version: str, value: str, From 61169cbda3ed42e57dc09dce41d60daeb688243e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 12 Mar 2026 14:17:09 -0700 Subject: [PATCH 008/102] update gen location --- sdk/storage/azure-storage-queue/MANIFEST.in | 7 +- .../azure-storage-queue/_metadata.json | 6 ++ .../apiview-properties.json | 64 +++++++++++++++ .../storage/queue/_generated/__init__.py | 27 +++++++ .../{azure/storage/queues => }/_client.py | 4 +- .../storage/queues => }/_configuration.py | 0 .../{azure/storage/queues => }/_patch.py | 0 .../storage/queues => }/_utils/__init__.py | 0 .../storage/queues => }/_utils/model_base.py | 6 ++ .../queues => }/_utils/serialization.py | 0 .../{azure/storage/queues => }/_version.py | 0 .../storage/queues => }/aio/__init__.py | 0 .../{azure/storage/queues => }/aio/_client.py | 4 +- .../storage/queues => }/aio/_configuration.py | 0 .../{azure/storage/queues => }/aio/_patch.py | 0 .../queues => }/aio/operations/__init__.py | 0 .../queues => }/aio/operations/_operations.py | 32 ++++---- .../queues => }/aio/operations/_patch.py | 0 .../queue/_generated/azure/__init__.py | 1 - .../_generated/azure/storage/__init__.py | 1 - .../azure/storage/queues/__init__.py | 32 -------- .../storage/queues => }/models/__init__.py | 0 .../storage/queues => }/models/_enums.py | 0 .../storage/queues => }/models/_models.py | 30 +++---- .../storage/queues => }/models/_patch.py | 0 .../queues => }/operations/__init__.py | 0 .../queues => }/operations/_operations.py | 48 ++++++------ .../storage/queues => }/operations/_patch.py | 0 .../{azure/storage/queues => }/py.typed | 0 .../azure-storage-queue/pyproject.toml | 63 +++++++++++++++ sdk/storage/azure-storage-queue/setup.py | 78 ------------------- .../azure-storage-queue/tsp-location.yaml | 4 + 32 files changed, 233 insertions(+), 174 deletions(-) create mode 100644 sdk/storage/azure-storage-queue/_metadata.json create mode 100644 sdk/storage/azure-storage-queue/apiview-properties.json rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/_client.py (96%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/_configuration.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/_patch.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/_utils/__init__.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/_utils/model_base.py (99%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/_utils/serialization.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/_version.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/aio/__init__.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/aio/_client.py (96%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/aio/_configuration.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/aio/_patch.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/aio/operations/__init__.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/aio/operations/_operations.py (98%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/aio/operations/_patch.py (100%) delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/__init__.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/__init__.py delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/__init__.py rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/models/__init__.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/models/_enums.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/models/_models.py (97%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/models/_patch.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/operations/__init__.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/operations/_operations.py (98%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/operations/_patch.py (100%) rename sdk/storage/azure-storage-queue/azure/storage/queue/_generated/{azure/storage/queues => }/py.typed (100%) delete mode 100644 sdk/storage/azure-storage-queue/setup.py create mode 100644 sdk/storage/azure-storage-queue/tsp-location.yaml diff --git a/sdk/storage/azure-storage-queue/MANIFEST.in b/sdk/storage/azure-storage-queue/MANIFEST.in index f2919ebac602..bae0431342c4 100644 --- a/sdk/storage/azure-storage-queue/MANIFEST.in +++ b/sdk/storage/azure-storage-queue/MANIFEST.in @@ -1,7 +1,8 @@ include *.md -include azure/__init__.py -include azure/storage/__init__.py include LICENSE +include azure/storage/queue/_generated/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 +include azure/storage/queue/__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..b8c56032e851 --- /dev/null +++ b/sdk/storage/azure-storage-queue/apiview-properties.json @@ -0,0 +1,64 @@ +{ + "CrossLanguagePackageId": "Storage.Queues", + "CrossLanguageDefinitionId": { + "azure.storage.queue._generated.models.AccessPolicy": "Storage.Queues.AccessPolicy", + "azure.storage.queue._generated.models.CorsRule": "Storage.Queues.CorsRule", + "azure.storage.queue._generated.models.Error": "Storage.Queues.Error", + "azure.storage.queue._generated.models.GeoReplication": "Storage.Queues.GeoReplication", + "azure.storage.queue._generated.models.KeyInfo": "Storage.Queues.KeyInfo", + "azure.storage.queue._generated.models.ListOfPeekedMessage": "Storage.Queues.ListOfPeekedMessage", + "azure.storage.queue._generated.models.ListOfReceivedMessage": "Storage.Queues.ListOfReceivedMessage", + "azure.storage.queue._generated.models.ListOfSentMessage": "Storage.Queues.ListOfSentMessage", + "azure.storage.queue._generated.models.ListQueuesResponse": "Storage.Queues.ListQueuesResponse", + "azure.storage.queue._generated.models.Logging": "Storage.Queues.Logging", + "azure.storage.queue._generated.models.Metrics": "Storage.Queues.Metrics", + "azure.storage.queue._generated.models.PeekedMessage": "Storage.Queues.PeekedMessage", + "azure.storage.queue._generated.models.QueueItem": "Storage.Queues.QueueItem", + "azure.storage.queue._generated.models.QueueMessage": "Storage.Queues.QueueMessage", + "azure.storage.queue._generated.models.QueueServiceProperties": "Storage.Queues.QueueServiceProperties", + "azure.storage.queue._generated.models.QueueServiceStats": "Storage.Queues.QueueServiceStats", + "azure.storage.queue._generated.models.ReceivedMessage": "Storage.Queues.ReceivedMessage", + "azure.storage.queue._generated.models.RetentionPolicy": "Storage.Queues.RetentionPolicy", + "azure.storage.queue._generated.models.SentMessage": "Storage.Queues.SentMessage", + "azure.storage.queue._generated.models.SignedIdentifier": "Storage.Queues.SignedIdentifier", + "azure.storage.queue._generated.models.SignedIdentifiers": "Storage.Queues.SignedIdentifiers", + "azure.storage.queue._generated.models.UserDelegationKey": "Storage.Queues.UserDelegationKey", + "azure.storage.queue._generated.models.StorageErrorCode": "Storage.Queues.StorageErrorCode", + "azure.storage.queue._generated.models.GeoReplicationStatusType": "Storage.Queues.GeoReplicationStatusType", + "azure.storage.queue._generated.models.ListQueuesIncludeType": "Storage.Queues.ListQueuesIncludeType", + "azure.storage.queue._generated.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", + "azure.storage.queue._generated.aio.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", + "azure.storage.queue._generated.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", + "azure.storage.queue._generated.aio.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", + "azure.storage.queue._generated.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", + "azure.storage.queue._generated.aio.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", + "azure.storage.queue._generated.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", + "azure.storage.queue._generated.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", + "azure.storage.queue._generated.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", + "azure.storage.queue._generated.aio.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", + "azure.storage.queue._generated.operations.QueueOperations.create": "Storage.Queues.Queue.create", + "azure.storage.queue._generated.aio.operations.QueueOperations.create": "Storage.Queues.Queue.create", + "azure.storage.queue._generated.operations.QueueOperations.get_metadata": "Storage.Queues.Queue.getMetadata", + "azure.storage.queue._generated.aio.operations.QueueOperations.get_metadata": "Storage.Queues.Queue.getMetadata", + "azure.storage.queue._generated.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", + "azure.storage.queue._generated.aio.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", + "azure.storage.queue._generated.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", + "azure.storage.queue._generated.aio.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", + "azure.storage.queue._generated.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", + "azure.storage.queue._generated.aio.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", + "azure.storage.queue._generated.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", + "azure.storage.queue._generated.aio.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", + "azure.storage.queue._generated.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", + "azure.storage.queue._generated.aio.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", + "azure.storage.queue._generated.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", + "azure.storage.queue._generated.aio.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", + "azure.storage.queue._generated.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", + "azure.storage.queue._generated.aio.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", + "azure.storage.queue._generated.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", + "azure.storage.queue._generated.aio.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", + "azure.storage.queue._generated.operations.QueueOperations.update": "Storage.Queues.Queue.update", + "azure.storage.queue._generated.aio.operations.QueueOperations.update": "Storage.Queues.Queue.update", + "azure.storage.queue._generated.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage", + "azure.storage.queue._generated.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 006671542af8..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,4 +2,31 @@ # -------------------------------------------------------------------------- # 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=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import QueuesClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "QueuesClient", +] +__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/azure/storage/queues/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py similarity index 96% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_client.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py index fb90964d3ffa..c04ab9922448 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py @@ -26,9 +26,9 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword """QueuesClient. :ivar service: ServiceOperations operations - :vartype service: azure.storage.queues.operations.ServiceOperations + :vartype service: azure.storage.queue._generated.operations.ServiceOperations :ivar queue: QueueOperations operations - :vartype queue: azure.storage.queues.operations.QueueOperations + :vartype queue: azure.storage.queue._generated.operations.QueueOperations :param url: The host name of the queue storage account, e.g. accountName.queue.core.windows.net. Required. :type url: str diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_configuration.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_configuration.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/model_base.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py similarity index 99% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/model_base.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py index 9616929f7415..a75a22adbb97 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/model_base.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py @@ -630,6 +630,9 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if len(items) > 0: existed_attr_keys.append(xml_name) dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = [] continue # text element is primitive type @@ -905,6 +908,8 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # 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 @@ -1084,6 +1089,7 @@ def __init__( 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 diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/serialization.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_utils/serialization.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_version.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/_version.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py similarity index 96% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_client.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py index 67b9d0ff6415..22f0c6df3b4d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py @@ -26,9 +26,9 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword """QueuesClient. :ivar service: ServiceOperations operations - :vartype service: azure.storage.queues.aio.operations.ServiceOperations + :vartype service: azure.storage.queue._generated.aio.operations.ServiceOperations :ivar queue: QueueOperations operations - :vartype queue: azure.storage.queues.aio.operations.QueueOperations + :vartype queue: azure.storage.queue._generated.aio.operations.QueueOperations :param url: The host name of the queue storage account, e.g. accountName.queue.core.windows.net. Required. :type url: str diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_configuration.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_configuration.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py similarity index 98% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_operations.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py index 7d9cd9ac4557..7453c0d9572e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py @@ -59,7 +59,7 @@ class ServiceOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queues.aio.QueuesClient`'s + :class:`~azure.storage.queue._generated.aio.QueuesClient`'s :attr:`service` attribute. """ @@ -78,7 +78,7 @@ async def set_properties( 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.queues.models.QueueServiceProperties + :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. @@ -152,7 +152,7 @@ async def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: QueueServiceProperties. The QueueServiceProperties is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.QueueServiceProperties + :rtype: ~azure.storage.queue._generated.models.QueueServiceProperties :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -230,7 +230,7 @@ async def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: QueueServiceStats. The QueueServiceStats is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.QueueServiceStats + :rtype: ~azure.storage.queue._generated.models.QueueServiceStats :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -305,13 +305,13 @@ async def get_user_delegation_key( using bearer token authentication. :param key_info: Key information. Required. - :type key_info: ~azure.storage.queues.models.KeyInfo + :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.queues.models.UserDelegationKey + :rtype: ~azure.storage.queue._generated.models.UserDelegationKey :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -416,9 +416,9 @@ async def get_queues( :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.queues.models.ListQueuesIncludeType] + :paramtype include: list[str or ~azure.storage.queue._generated.models.ListQueuesIncludeType] :return: ListQueuesResponse. The ListQueuesResponse is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListQueuesResponse + :rtype: ~azure.storage.queue._generated.models.ListQueuesResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -496,7 +496,7 @@ class QueueOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queues.aio.QueuesClient`'s + :class:`~azure.storage.queue._generated.aio.QueuesClient`'s :attr:`queue` attribute. """ @@ -776,7 +776,7 @@ async def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.SignedIdentifiers + :rtype: ~azure.storage.queue._generated.models.SignedIdentifiers :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -850,7 +850,7 @@ async def set_access_policy( """sets the permissions for the specified queue. :param queue_acl: The access control list for the queue. Required. - :type queue_acl: ~azure.storage.queues.models.SignedIdentifiers + :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. @@ -942,7 +942,7 @@ async def receive_messages( Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: ListOfReceivedMessage. The ListOfReceivedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListOfReceivedMessage + :rtype: ~azure.storage.queue._generated.models.ListOfReceivedMessage :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1090,7 +1090,7 @@ async def send_message( for previous versions. :param queue_message: A Message object which can be stored in a Queue. Required. - :type queue_message: ~azure.storage.queues.models.QueueMessage + :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 @@ -1109,7 +1109,7 @@ async def send_message( Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: ListOfSentMessage. The ListOfSentMessage is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListOfSentMessage + :rtype: ~azure.storage.queue._generated.models.ListOfSentMessage :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1201,7 +1201,7 @@ async def peek_messages( Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: ListOfPeekedMessage. The ListOfPeekedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListOfPeekedMessage + :rtype: ~azure.storage.queue._generated.models.ListOfPeekedMessage :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1289,7 +1289,7 @@ async def update( :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.queues.models.QueueMessage + :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 diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/aio/operations/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/__init__.py deleted file mode 100644 index d55ccad1f573..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/__init__.py deleted file mode 100644 index d55ccad1f573..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/__init__.py deleted file mode 100644 index 0fe6e78452f5..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/__init__.py +++ /dev/null @@ -1,32 +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) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - -from ._client import QueuesClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "QueuesClient", -] -__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/azure/storage/queues/models/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_enums.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_enums.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py similarity index 97% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 95c70233a91d..92d1832a42e8 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -164,7 +164,7 @@ class Error(_Model): "AuthorizationProtocolMismatch", "AuthorizationPermissionMismatch", "AuthorizationServiceMismatch", "AuthorizationResourceTypeMismatch", and "FeatureVersionMismatch". - :vartype code: str or ~azure.storage.queues.models.StorageErrorCode + :vartype code: str or ~azure.storage.queue._generated.models.StorageErrorCode :ivar message: The error message. :vartype message: str """ @@ -224,7 +224,7 @@ class GeoReplication(_Model): :ivar status: The status of the secondary location. Required. Known values are: "live", "bootstrap", and "unavailable". - :vartype status: str or ~azure.storage.queues.models.GeoReplicationStatusType + :vartype status: str or ~azure.storage.queue._generated.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. @@ -324,7 +324,7 @@ class ListOfPeekedMessage(_Model): """List wrapper for PeekedMessageItem array. :ivar items_property: The list of peeked messages. Required. - :vartype items_property: ~azure.storage.queues.models.PeekedMessage + :vartype items_property: ~azure.storage.queue._generated.models.PeekedMessage """ items_property: list["_models.PeekedMessage"] = rest_field( @@ -359,7 +359,7 @@ class ListOfReceivedMessage(_Model): """List wrapper for DequeuedMessageItem array. :ivar items_property: The list of dequeued messages. Required. - :vartype items_property: ~azure.storage.queues.models.ReceivedMessage + :vartype items_property: ~azure.storage.queue._generated.models.ReceivedMessage """ items_property: list["_models.ReceivedMessage"] = rest_field( @@ -394,7 +394,7 @@ class ListOfSentMessage(_Model): """List wrapper for EnqueuedMessage array. :ivar items_property: The list of enqueued messages. Required. - :vartype items_property: ~azure.storage.queues.models.SentMessage + :vartype items_property: ~azure.storage.queue._generated.models.SentMessage """ items_property: list["_models.SentMessage"] = rest_field( @@ -437,7 +437,7 @@ class ListQueuesResponse(_Model): :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.queues.models.QueueItem + :vartype queue_items: ~azure.storage.queue._generated.models.QueueItem :ivar next_marker: The next marker of the queues. Required. :vartype next_marker: str """ @@ -514,7 +514,7 @@ class Logging(_Model): :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.queues.models.RetentionPolicy + :vartype retention_policy: ~azure.storage.queue._generated.models.RetentionPolicy """ version: str = rest_field( @@ -578,7 +578,7 @@ class Metrics(_Model): :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.queues.models.RetentionPolicy + :vartype retention_policy: ~azure.storage.queue._generated.models.RetentionPolicy """ version: Optional[str] = rest_field( @@ -779,13 +779,13 @@ class QueueServiceProperties(_Model): """The service properties. :ivar logging: The logging properties. - :vartype logging: ~azure.storage.queues.models.Logging + :vartype logging: ~azure.storage.queue._generated.models.Logging :ivar hour_metrics: The hour metrics properties. - :vartype hour_metrics: ~azure.storage.queues.models.Metrics + :vartype hour_metrics: ~azure.storage.queue._generated.models.Metrics :ivar minute_metrics: The minute metrics properties. - :vartype minute_metrics: ~azure.storage.queues.models.Metrics + :vartype minute_metrics: ~azure.storage.queue._generated.models.Metrics :ivar cors: The CORS properties. - :vartype cors: ~azure.storage.queues.models.CorsRule + :vartype cors: ~azure.storage.queue._generated.models.CorsRule """ logging: Optional["_models.Logging"] = rest_field( @@ -838,7 +838,7 @@ class QueueServiceStats(_Model): """Stats for the storage service. :ivar geo_replication: The geo replication stats. - :vartype geo_replication: ~azure.storage.queues.models.GeoReplication + :vartype geo_replication: ~azure.storage.queue._generated.models.GeoReplication """ geo_replication: Optional["_models.GeoReplication"] = rest_field( @@ -1087,7 +1087,7 @@ class SignedIdentifier(_Model): :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.queues.models.AccessPolicy + :vartype access_policy: ~azure.storage.queue._generated.models.AccessPolicy """ id: str = rest_field( @@ -1127,7 +1127,7 @@ class SignedIdentifiers(_Model): """Represents an array of signed identifiers. :ivar items_property: The list of signed identifiers. Required. - :vartype items_property: ~azure.storage.queues.models.SignedIdentifier + :vartype items_property: ~azure.storage.queue._generated.models.SignedIdentifier """ items_property: list["_models.SignedIdentifier"] = rest_field( diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/models/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/__init__.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py similarity index 98% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_operations.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py index 0cceddaa5071..6d309c228441 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py @@ -169,7 +169,7 @@ def build_queue_create_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "" + _url = "/" # Construct parameters if timeout is not None: @@ -207,7 +207,7 @@ def build_queue_delete_request(*, timeout: Optional[int] = None, **kwargs: Any) version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "" + _url = "/" # Construct parameters if timeout is not None: @@ -293,7 +293,7 @@ def build_queue_receive_messages_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "messages" + _url = "/messages" # Construct parameters if number_of_messages is not None: @@ -316,7 +316,7 @@ def build_queue_clear_request(*, timeout: Optional[int] = None, **kwargs: Any) - version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "messages" + _url = "/messages" # Construct parameters if timeout is not None: @@ -343,7 +343,7 @@ def build_queue_send_message_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "messages" + _url = "/messages" # Construct parameters if visibility_timeout is not None: @@ -371,7 +371,7 @@ def build_queue_peek_messages_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "messages?peekonly=true" + _url = "/messages?peekonly=true" # Construct parameters if number_of_messages is not None: @@ -395,7 +395,7 @@ def build_queue_update_request( content_type: str = kwargs.pop("content_type") version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "messages/{messageId}" + _url = "/messages/{messageId}" path_format_arguments = { "messageId": _SERIALIZER.url("message_id", message_id, "str"), } @@ -423,7 +423,7 @@ def build_queue_delete_message_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "messages/{messageId}" + _url = "/messages/{messageId}" path_format_arguments = { "messageId": _SERIALIZER.url("message_id", message_id, "str"), } @@ -447,7 +447,7 @@ class ServiceOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queues.QueuesClient`'s + :class:`~azure.storage.queue._generated.QueuesClient`'s :attr:`service` attribute. """ @@ -466,7 +466,7 @@ def set_properties( # pylint: disable=inconsistent-return-statements 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.queues.models.QueueServiceProperties + :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. @@ -540,7 +540,7 @@ def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _mo Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: QueueServiceProperties. The QueueServiceProperties is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.QueueServiceProperties + :rtype: ~azure.storage.queue._generated.models.QueueServiceProperties :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -618,7 +618,7 @@ def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _mo Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: QueueServiceStats. The QueueServiceStats is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.QueueServiceStats + :rtype: ~azure.storage.queue._generated.models.QueueServiceStats :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -693,13 +693,13 @@ def get_user_delegation_key( using bearer token authentication. :param key_info: Key information. Required. - :type key_info: ~azure.storage.queues.models.KeyInfo + :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.queues.models.UserDelegationKey + :rtype: ~azure.storage.queue._generated.models.UserDelegationKey :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -804,9 +804,9 @@ def get_queues( :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.queues.models.ListQueuesIncludeType] + :paramtype include: list[str or ~azure.storage.queue._generated.models.ListQueuesIncludeType] :return: ListQueuesResponse. The ListQueuesResponse is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListQueuesResponse + :rtype: ~azure.storage.queue._generated.models.ListQueuesResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -884,7 +884,7 @@ class QueueOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queues.QueuesClient`'s + :class:`~azure.storage.queue._generated.QueuesClient`'s :attr:`queue` attribute. """ @@ -1172,7 +1172,7 @@ def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: Any) -> Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.SignedIdentifiers + :rtype: ~azure.storage.queue._generated.models.SignedIdentifiers :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1246,7 +1246,7 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements """sets the permissions for the specified queue. :param queue_acl: The access control list for the queue. Required. - :type queue_acl: ~azure.storage.queues.models.SignedIdentifiers + :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. @@ -1338,7 +1338,7 @@ def receive_messages( Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: ListOfReceivedMessage. The ListOfReceivedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListOfReceivedMessage + :rtype: ~azure.storage.queue._generated.models.ListOfReceivedMessage :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1488,7 +1488,7 @@ def send_message( for previous versions. :param queue_message: A Message object which can be stored in a Queue. Required. - :type queue_message: ~azure.storage.queues.models.QueueMessage + :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 @@ -1507,7 +1507,7 @@ def send_message( Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: ListOfSentMessage. The ListOfSentMessage is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListOfSentMessage + :rtype: ~azure.storage.queue._generated.models.ListOfSentMessage :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1599,7 +1599,7 @@ def peek_messages( Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int :return: ListOfPeekedMessage. The ListOfPeekedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queues.models.ListOfPeekedMessage + :rtype: ~azure.storage.queue._generated.models.ListOfPeekedMessage :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1687,7 +1687,7 @@ def update( # pylint: disable=inconsistent-return-statements :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.queues.models.QueueMessage + :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 diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/operations/_patch.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/py.typed b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/py.typed similarity index 100% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/azure/storage/queues/py.typed rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/py.typed diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index e0b490cb8fec..c0c6bf12458e 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -1,3 +1,66 @@ +# -------------------------------------------------------------------------- +# 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 = "azpysdkhelp@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.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.storage.queue._generated._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", + "azure.storage.queue", +] + +[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 ac028b43a7a5..000000000000 --- a/sdk/storage/azure-storage-queue/setup.py +++ /dev/null @@ -1,78 +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/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: From 8687c2811af9163d814774cc67783e177eb4283f Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 12 Mar 2026 14:39:42 -0700 Subject: [PATCH 009/102] pyproject --- sdk/storage/azure-storage-queue/pyproject.toml | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index c0c6bf12458e..fa64a5594671 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -43,20 +43,11 @@ dynamic = [ repository = "https://github.com/Azure/azure-sdk-for-python" [tool.setuptools.dynamic] -version = {attr = "azure.storage.queue._generated._version.VERSION"} +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", - "azure.storage.queue", -] +include = ["azure.storage.queue*"] [tool.setuptools.package-data] pytyped = ["py.typed"] From b1381ee3bc3d0c7ea4a3ad824a49bec217c2d26e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 12 Mar 2026 14:55:32 -0700 Subject: [PATCH 010/102] update imports --- .../azure-storage-queue/azure/storage/queue/_models.py | 10 +++++----- .../azure/storage/queue/_queue_client.py | 2 +- .../azure/storage/queue/_queue_service_client.py | 2 +- .../azure/storage/queue/aio/_queue_client_async.py | 4 ++-- .../storage/queue/aio/_queue_service_client_async.py | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) 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 afa8caaf1304..88619f442b6e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -11,11 +11,11 @@ from azure.core.paging import PageIterator from ._shared.response_handlers import process_storage_error, return_context_and_deserialized from ._shared.models import DictMixin -from ._generated.azure.storage.queues.models import AccessPolicy as GenAccessPolicy -from ._generated.azure.storage.queues.models import CorsRule as GeneratedCorsRule -from ._generated.azure.storage.queues.models import Logging as GeneratedLogging -from ._generated.azure.storage.queues.models import Metrics as GeneratedMetrics -from ._generated.azure.storage.queues.models import RetentionPolicy as GeneratedRetentionPolicy +from _generated.models import AccessPolicy as GenAccessPolicy +from _generated.models import CorsRule as GeneratedCorsRule +from _generated.models import Logging as GeneratedLogging +from _generated.models import Metrics as GeneratedMetrics +from _generated.models import RetentionPolicy as GeneratedRetentionPolicy if sys.version_info >= (3, 11): from typing import Self 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 254c2f2b3058..0b265bc888a8 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 @@ -16,7 +16,7 @@ from ._deserialize import deserialize_queue_creation, deserialize_queue_properties from ._encryption import modify_user_agent_for_encryption, StorageEncryptionMixin from ._generated.azure.storage.queues import QueuesClient as AzureQueueStorage -from ._generated.azure.storage.queues.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers +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 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 c4fc5634d06b..1117bb253e58 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 @@ -15,7 +15,7 @@ from azure.core.tracing.decorator import distributed_trace from ._encryption import StorageEncryptionMixin from ._generated.azure.storage.queues import QueuesClient as AzureQueueStorage -from ._generated.azure.storage.queues.models import KeyInfo, QueueServiceProperties as StorageServiceProperties +from _generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties from ._models import ( CorsRule, QueueProperties, 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 ae69b14e10a6..8bfc375c51fa 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 @@ -17,8 +17,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.azure.storage.queues.aio import QueuesClient as AzureQueueStorage -from .._generated.azure.storage.queues.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers +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 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 24ee8ef0fb04..18c50fe1fd27 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,8 +17,8 @@ from ._models import QueuePropertiesPaged from ._queue_client_async import QueueClient from .._encryption import StorageEncryptionMixin -from .._generated.azure.storage.queues.aio import QueuesClient as AzureQueueStorage -from .._generated.azure.storage.queues.models import KeyInfo, QueueServiceProperties as StorageServiceProperties +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 52380c1ab809401f4e5f75d719cbb24e1ce5b9eb Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 18 Mar 2026 09:09:16 -0700 Subject: [PATCH 011/102] regen + updates --- .../queue/_generated/_utils/model_base.py | 6 - .../_generated/aio/operations/_operations.py | 39 +++-- .../queue/_generated/models/__init__.py | 12 +- .../storage/queue/_generated/models/_enums.py | 2 +- .../queue/_generated/models/_models.py | 162 +++++++++--------- .../_generated/operations/_operations.py | 55 +++--- .../azure/storage/queue/_models.py | 10 +- .../azure/storage/queue/_queue_client.py | 8 +- .../storage/queue/_queue_service_client.py | 4 +- .../storage/queue/aio/_queue_client_async.py | 8 +- .../queue/aio/_queue_service_client_async.py | 6 +- 11 files changed, 152 insertions(+), 160 deletions(-) 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 index a75a22adbb97..9616929f7415 100644 --- 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 @@ -630,9 +630,6 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if len(items) > 0: existed_attr_keys.append(xml_name) dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = [] continue # text element is primitive type @@ -908,8 +905,6 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # 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 @@ -1089,7 +1084,6 @@ def __init__( 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 diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py index 7453c0d9572e..59a6040ca394 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py @@ -34,13 +34,13 @@ build_queue_delete_message_request, build_queue_delete_request, build_queue_get_access_policy_request, - build_queue_get_metadata_request, + build_queue_get_properties_request, build_queue_peek_messages_request, build_queue_receive_messages_request, build_queue_send_message_request, build_queue_set_access_policy_request, build_queue_set_metadata_request, - build_queue_update_request, + build_queue_update_message_request, build_service_get_properties_request, build_service_get_queues_request, build_service_get_statistics_request, @@ -509,8 +509,9 @@ def __init__(self, *args, **kwargs) -> None: @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 the queue with the same name already - exists, the operation fails. + """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 @@ -554,7 +555,7 @@ async def create(self, *, timeout: Optional[int] = None, metadata: Optional[str] response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -574,7 +575,7 @@ async def create(self, *, timeout: Optional[int] = None, metadata: Optional[str] return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_metadata(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: + 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 cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_queue_get_metadata_request( + _request = build_queue_get_properties_request( timeout=timeout, version=self._config.version, headers=_headers, @@ -922,7 +923,7 @@ async def receive_messages( visibility_timeout: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any - ) -> _models.ListOfReceivedMessage: + ) -> _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 @@ -941,8 +942,8 @@ async def receive_messages( href="https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations">Setting Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int - :return: ListOfReceivedMessage. The ListOfReceivedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queue._generated.models.ListOfReceivedMessage + :return: ReceivedMessages. The ReceivedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ReceivedMessages :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -956,7 +957,7 @@ async def receive_messages( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListOfReceivedMessage] = kwargs.pop("cls", None) + cls: ClsType[_models.ReceivedMessages] = kwargs.pop("cls", None) _request = build_queue_receive_messages_request( number_of_messages=number_of_messages, @@ -1004,7 +1005,7 @@ async def receive_messages( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize_xml(_models.ListOfReceivedMessage, response.text()) + deserialized = _deserialize_xml(_models.ReceivedMessages, response.text()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1186,7 +1187,7 @@ async def send_message( @distributed_trace_async async def peek_messages( self, *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any - ) -> _models.ListOfPeekedMessage: + ) -> _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. @@ -1200,8 +1201,8 @@ async def peek_messages( href="https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations">Setting Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int - :return: ListOfPeekedMessage. The ListOfPeekedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queue._generated.models.ListOfPeekedMessage + :return: PeekedMessages. The PeekedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.PeekedMessages :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1215,7 +1216,7 @@ async def peek_messages( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListOfPeekedMessage] = kwargs.pop("cls", None) + cls: ClsType[_models.PeekedMessages] = kwargs.pop("cls", None) _request = build_queue_peek_messages_request( number_of_messages=number_of_messages, @@ -1262,7 +1263,7 @@ async def peek_messages( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize_xml(_models.ListOfPeekedMessage, response.text()) + deserialized = _deserialize_xml(_models.PeekedMessages, response.text()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1270,7 +1271,7 @@ async def peek_messages( return deserialized # type: ignore @distributed_trace_async - async def update( + async def update_message( self, message_id: str, queue_message: Optional[_models.QueueMessage] = None, @@ -1327,7 +1328,7 @@ async def update( else: _content = None - _request = build_queue_update_request( + _request = build_queue_update_message_request( message_id=message_id, pop_receipt=pop_receipt, visibility_timeout=visibility_timeout, diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py index 5e01d6501d1e..e29fa762cee9 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/__init__.py @@ -19,18 +19,18 @@ Error, GeoReplication, KeyInfo, - ListOfPeekedMessage, - ListOfReceivedMessage, ListOfSentMessage, ListQueuesResponse, Logging, Metrics, PeekedMessage, + PeekedMessages, QueueItem, QueueMessage, QueueServiceProperties, QueueServiceStats, ReceivedMessage, + ReceivedMessages, RetentionPolicy, SentMessage, SignedIdentifier, @@ -39,7 +39,7 @@ ) from ._enums import ( # type: ignore - GeoReplicationStatusType, + GeoReplicationStatus, ListQueuesIncludeType, StorageErrorCode, ) @@ -53,24 +53,24 @@ "Error", "GeoReplication", "KeyInfo", - "ListOfPeekedMessage", - "ListOfReceivedMessage", "ListOfSentMessage", "ListQueuesResponse", "Logging", "Metrics", "PeekedMessage", + "PeekedMessages", "QueueItem", "QueueMessage", "QueueServiceProperties", "QueueServiceStats", "ReceivedMessage", + "ReceivedMessages", "RetentionPolicy", "SentMessage", "SignedIdentifier", "SignedIdentifiers", "UserDelegationKey", - "GeoReplicationStatusType", + "GeoReplicationStatus", "ListQueuesIncludeType", "StorageErrorCode", ] diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py index 922eb5338c62..59eeda9aed3e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py @@ -10,7 +10,7 @@ from azure.core import CaseInsensitiveEnumMeta -class GeoReplicationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class GeoReplicationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The geo replication status.""" LIVE = "live" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 92d1832a42e8..3dd68b25c6ee 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -21,22 +21,20 @@ class AccessPolicy(_Model): """Represents an access policy. :ivar start: The date-time the policy is active. - :vartype start: ~datetime.datetime + :vartype start: str :ivar expiry: The date-time the policy expires. - :vartype expiry: ~datetime.datetime + :vartype expiry: str :ivar permission: The permissions for acl the policy. :vartype permission: str """ - start: Optional[datetime.datetime] = rest_field( + start: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, ) """The date-time the policy is active.""" - expiry: Optional[datetime.datetime] = rest_field( + expiry: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, ) """The date-time the policy expires.""" @@ -52,8 +50,8 @@ class AccessPolicy(_Model): def __init__( self, *, - start: Optional[datetime.datetime] = None, - expiry: Optional[datetime.datetime] = None, + start: Optional[str] = None, + expiry: Optional[str] = None, permission: Optional[str] = None, ) -> None: ... @@ -144,8 +142,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class Error(_Model): """The error response. - This defines the wire format only. Language SDKs wrap this in idiomatic error types. - :ivar code: The error code. Known values are: "AccountAlreadyExists", "AccountBeingCreated", "AccountIsDisabled", "AuthenticationFailed", "AuthorizationFailure", "ConditionHeadersNotSupported", "ConditionNotMet", "EmptyMetadataKey", @@ -224,14 +220,14 @@ class GeoReplication(_Model): :ivar status: The status of the secondary location. Required. Known values are: "live", "bootstrap", and "unavailable". - :vartype status: str or ~azure.storage.queue._generated.models.GeoReplicationStatusType + :vartype status: str or ~azure.storage.queue._generated.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.GeoReplicationStatusType"] = rest_field( + status: Union[str, "_models.GeoReplicationStatus"] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Status", "text": False, "unwrapped": False}, ) @@ -253,7 +249,7 @@ class GeoReplication(_Model): def __init__( self, *, - status: Union[str, "_models.GeoReplicationStatusType"], + status: Union[str, "_models.GeoReplicationStatus"], last_sync_time: datetime.datetime, ) -> None: ... @@ -320,76 +316,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ListOfPeekedMessage(_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 ListOfReceivedMessage(_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 ListOfSentMessage(_Model): """List wrapper for EnqueuedMessage array. @@ -700,6 +626,41 @@ 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. @@ -963,6 +924,41 @@ 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. diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py index 6d309c228441..5dabaec56a94 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py @@ -169,7 +169,7 @@ def build_queue_create_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/" + _url = "" # Construct parameters if timeout is not None: @@ -183,7 +183,7 @@ def build_queue_create_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_queue_get_metadata_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: +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 {}) @@ -207,7 +207,7 @@ def build_queue_delete_request(*, timeout: Optional[int] = None, **kwargs: Any) version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/" + _url = "" # Construct parameters if timeout is not None: @@ -293,7 +293,7 @@ def build_queue_receive_messages_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "/messages" + _url = "messages" # Construct parameters if number_of_messages is not None: @@ -316,7 +316,7 @@ def build_queue_clear_request(*, timeout: Optional[int] = None, **kwargs: Any) - version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/messages" + _url = "messages" # Construct parameters if timeout is not None: @@ -343,7 +343,7 @@ def build_queue_send_message_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "/messages" + _url = "messages" # Construct parameters if visibility_timeout is not None: @@ -371,7 +371,7 @@ def build_queue_peek_messages_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "/messages?peekonly=true" + _url = "messages?peekonly=true" # Construct parameters if number_of_messages is not None: @@ -386,7 +386,7 @@ def build_queue_peek_messages_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_queue_update_request( +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 {}) @@ -395,7 +395,7 @@ def build_queue_update_request( content_type: str = kwargs.pop("content_type") version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/messages/{messageId}" + _url = "messages/{messageId}" path_format_arguments = { "messageId": _SERIALIZER.url("message_id", message_id, "str"), } @@ -423,7 +423,7 @@ def build_queue_delete_message_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/messages/{messageId}" + _url = "messages/{messageId}" path_format_arguments = { "messageId": _SERIALIZER.url("message_id", message_id, "str"), } @@ -899,8 +899,9 @@ def __init__(self, *args, **kwargs) -> None: 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 the queue with the same name already - exists, the operation fails. + """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 @@ -944,7 +945,7 @@ def create( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -964,7 +965,7 @@ def create( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_metadata( # pylint: disable=inconsistent-return-statements + 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. @@ -990,7 +991,7 @@ def get_metadata( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_queue_get_metadata_request( + _request = build_queue_get_properties_request( timeout=timeout, version=self._config.version, headers=_headers, @@ -1318,7 +1319,7 @@ def receive_messages( visibility_timeout: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any - ) -> _models.ListOfReceivedMessage: + ) -> _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 @@ -1337,8 +1338,8 @@ def receive_messages( href="https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations">Setting Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int - :return: ListOfReceivedMessage. The ListOfReceivedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queue._generated.models.ListOfReceivedMessage + :return: ReceivedMessages. The ReceivedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ReceivedMessages :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1352,7 +1353,7 @@ def receive_messages( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListOfReceivedMessage] = kwargs.pop("cls", None) + cls: ClsType[_models.ReceivedMessages] = kwargs.pop("cls", None) _request = build_queue_receive_messages_request( number_of_messages=number_of_messages, @@ -1400,7 +1401,7 @@ def receive_messages( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize_xml(_models.ListOfReceivedMessage, response.text()) + deserialized = _deserialize_xml(_models.ReceivedMessages, response.text()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1584,7 +1585,7 @@ def send_message( @distributed_trace def peek_messages( self, *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any - ) -> _models.ListOfPeekedMessage: + ) -> _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. @@ -1598,8 +1599,8 @@ def peek_messages( href="https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations">Setting Timeouts for Queue Service Operations.. Default value is None. :paramtype timeout: int - :return: ListOfPeekedMessage. The ListOfPeekedMessage is compatible with MutableMapping - :rtype: ~azure.storage.queue._generated.models.ListOfPeekedMessage + :return: PeekedMessages. The PeekedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.PeekedMessages :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1613,7 +1614,7 @@ def peek_messages( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListOfPeekedMessage] = kwargs.pop("cls", None) + cls: ClsType[_models.PeekedMessages] = kwargs.pop("cls", None) _request = build_queue_peek_messages_request( number_of_messages=number_of_messages, @@ -1660,7 +1661,7 @@ def peek_messages( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize_xml(_models.ListOfPeekedMessage, response.text()) + deserialized = _deserialize_xml(_models.PeekedMessages, response.text()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1668,7 +1669,7 @@ def peek_messages( return deserialized # type: ignore @distributed_trace - def update( # pylint: disable=inconsistent-return-statements + def update_message( # pylint: disable=inconsistent-return-statements self, message_id: str, queue_message: Optional[_models.QueueMessage] = None, @@ -1725,7 +1726,7 @@ def update( # pylint: disable=inconsistent-return-statements else: _content = None - _request = build_queue_update_request( + _request = build_queue_update_message_request( message_id=message_id, pop_receipt=pop_receipt, visibility_timeout=visibility_timeout, 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 88619f442b6e..ddf3651c15e5 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -11,11 +11,11 @@ from azure.core.paging import PageIterator from ._shared.response_handlers import process_storage_error, return_context_and_deserialized from ._shared.models import DictMixin -from _generated.models import AccessPolicy as GenAccessPolicy -from _generated.models import CorsRule as GeneratedCorsRule -from _generated.models import Logging as GeneratedLogging -from _generated.models import Metrics as GeneratedMetrics -from _generated.models import RetentionPolicy as GeneratedRetentionPolicy +from ._generated.models import AccessPolicy as GenAccessPolicy +from ._generated.models import CorsRule as GeneratedCorsRule +from ._generated.models import Logging as GeneratedLogging +from ._generated.models import Metrics as GeneratedMetrics +from ._generated.models import RetentionPolicy as GeneratedRetentionPolicy if sys.version_info >= (3, 11): from typing import Self 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 0b265bc888a8..3486b94a1870 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 @@ -15,8 +15,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.azure.storage.queues import QueuesClient as AzureQueueStorage -from _generated.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers +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 @@ -391,7 +391,7 @@ def get_queue_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) try: response = cast( "QueueProperties", - self._client.queue.get_metadata(timeout=timeout, cls=deserialize_queue_properties, **kwargs), + self._client.queue.get_properties(timeout=timeout, cls=deserialize_queue_properties, **kwargs), ) except HttpResponseError as error: process_storage_error(error) @@ -893,7 +893,7 @@ def update_message( try: response = cast( QueueMessage, - self._client.queue.update( + self._client.queue.update_message( queue_message=updated, visibility_timeout=visibility_timeout or 0, timeout=timeout, 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 1117bb253e58..631431c4c8a1 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.azure.storage.queues import QueuesClient as AzureQueueStorage -from _generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties +from ._generated import QueuesClient as AzureQueueStorage +from ._generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties from ._models import ( CorsRule, QueueProperties, 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 8bfc375c51fa..d2bd8004bc07 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 @@ -17,8 +17,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 QueuesClient as AzureQueueStorage -from ._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers +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 @@ -405,7 +405,7 @@ async def get_queue_properties(self, *, timeout: Optional[int] = None, **kwargs: try: response = cast( "QueueProperties", - await self._client.queue.get_metadata(timeout=timeout, cls=deserialize_queue_properties, **kwargs), + await self._client.queue.get_properties(timeout=timeout, cls=deserialize_queue_properties, **kwargs), ) except HttpResponseError as error: process_storage_error(error) @@ -899,7 +899,7 @@ async def update_message( try: response = cast( QueueMessage, - await self._client.queue.update( + await self._client.queue.update_message( queue_message=updated, visibility_timeout=visibility_timeout or 0, timeout=timeout, 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 18c50fe1fd27..b999396e8617 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,8 +17,8 @@ from ._models import QueuePropertiesPaged from ._queue_client_async import QueueClient from .._encryption import StorageEncryptionMixin -from ._generated.aio import QueuesClient as AzureQueueStorage -from ._generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties +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 @@ -410,7 +410,7 @@ def list_queues( """ include = ["metadata"] if include_metadata else None command = functools.partial( - self._client.service.list_queues, + self._client.service.get_queues, prefix=name_starts_with, include=include, timeout=timeout, From ac180615cd3036dd3c3546d72b524acc64805ec7 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 18 Mar 2026 09:12:31 -0700 Subject: [PATCH 012/102] change conftest --- sdk/storage/azure-storage-queue/tests/conftest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/tests/conftest.py b/sdk/storage/azure-storage-queue/tests/conftest.py index 0b7f0d23f613..24a229e97814 100644 --- a/sdk/storage/azure-storage-queue/tests/conftest.py +++ b/sdk/storage/azure-storage-queue/tests/conftest.py @@ -36,4 +36,4 @@ def add_sanitizers(test_proxy): add_uri_string_sanitizer(target=".preprod.", value=".") add_remove_header_sanitizer(headers="Accept") - set_custom_default_matcher(excluded_headers="Accept", ignore_query_ordering=True) + set_custom_default_matcher(ignore_query_ordering=True) From b1a40beddcacce16bb3fda6c06029f1f93846bb6 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 18 Mar 2026 14:11:12 -0700 Subject: [PATCH 013/102] mypy + blakc --- .../azure-storage-queue/apiview-properties.json | 14 +++++++------- .../storage/queue/_generated/models/_models.py | 14 ++++++-------- .../azure/storage/queue/_message_encoding.py | 2 +- .../azure/storage/queue/_models.py | 6 ++++-- .../azure/storage/queue/_queue_client.py | 10 +++++----- .../azure/storage/queue/_queue_service_client.py | 4 +--- .../storage/queue/_shared/response_handlers.py | 9 ++++++--- .../azure/storage/queue/aio/_models.py | 4 +++- .../azure/storage/queue/aio/_queue_client_async.py | 10 +++++----- .../queue/aio/_queue_service_client_async.py | 4 +--- sdk/storage/azure-storage-queue/pyproject.toml | 13 +++++++++++-- 11 files changed, 50 insertions(+), 40 deletions(-) diff --git a/sdk/storage/azure-storage-queue/apiview-properties.json b/sdk/storage/azure-storage-queue/apiview-properties.json index b8c56032e851..46775c913b7d 100644 --- a/sdk/storage/azure-storage-queue/apiview-properties.json +++ b/sdk/storage/azure-storage-queue/apiview-properties.json @@ -6,25 +6,25 @@ "azure.storage.queue._generated.models.Error": "Storage.Queues.Error", "azure.storage.queue._generated.models.GeoReplication": "Storage.Queues.GeoReplication", "azure.storage.queue._generated.models.KeyInfo": "Storage.Queues.KeyInfo", - "azure.storage.queue._generated.models.ListOfPeekedMessage": "Storage.Queues.ListOfPeekedMessage", - "azure.storage.queue._generated.models.ListOfReceivedMessage": "Storage.Queues.ListOfReceivedMessage", "azure.storage.queue._generated.models.ListOfSentMessage": "Storage.Queues.ListOfSentMessage", "azure.storage.queue._generated.models.ListQueuesResponse": "Storage.Queues.ListQueuesResponse", "azure.storage.queue._generated.models.Logging": "Storage.Queues.Logging", "azure.storage.queue._generated.models.Metrics": "Storage.Queues.Metrics", "azure.storage.queue._generated.models.PeekedMessage": "Storage.Queues.PeekedMessage", + "azure.storage.queue._generated.models.PeekedMessages": "Storage.Queues.PeekedMessages", "azure.storage.queue._generated.models.QueueItem": "Storage.Queues.QueueItem", "azure.storage.queue._generated.models.QueueMessage": "Storage.Queues.QueueMessage", "azure.storage.queue._generated.models.QueueServiceProperties": "Storage.Queues.QueueServiceProperties", "azure.storage.queue._generated.models.QueueServiceStats": "Storage.Queues.QueueServiceStats", "azure.storage.queue._generated.models.ReceivedMessage": "Storage.Queues.ReceivedMessage", + "azure.storage.queue._generated.models.ReceivedMessages": "Storage.Queues.ReceivedMessages", "azure.storage.queue._generated.models.RetentionPolicy": "Storage.Queues.RetentionPolicy", "azure.storage.queue._generated.models.SentMessage": "Storage.Queues.SentMessage", "azure.storage.queue._generated.models.SignedIdentifier": "Storage.Queues.SignedIdentifier", "azure.storage.queue._generated.models.SignedIdentifiers": "Storage.Queues.SignedIdentifiers", "azure.storage.queue._generated.models.UserDelegationKey": "Storage.Queues.UserDelegationKey", "azure.storage.queue._generated.models.StorageErrorCode": "Storage.Queues.StorageErrorCode", - "azure.storage.queue._generated.models.GeoReplicationStatusType": "Storage.Queues.GeoReplicationStatusType", + "azure.storage.queue._generated.models.GeoReplicationStatus": "Storage.Queues.GeoReplicationStatus", "azure.storage.queue._generated.models.ListQueuesIncludeType": "Storage.Queues.ListQueuesIncludeType", "azure.storage.queue._generated.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", "azure.storage.queue._generated.aio.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", @@ -38,8 +38,8 @@ "azure.storage.queue._generated.aio.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", "azure.storage.queue._generated.operations.QueueOperations.create": "Storage.Queues.Queue.create", "azure.storage.queue._generated.aio.operations.QueueOperations.create": "Storage.Queues.Queue.create", - "azure.storage.queue._generated.operations.QueueOperations.get_metadata": "Storage.Queues.Queue.getMetadata", - "azure.storage.queue._generated.aio.operations.QueueOperations.get_metadata": "Storage.Queues.Queue.getMetadata", + "azure.storage.queue._generated.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", + "azure.storage.queue._generated.aio.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", "azure.storage.queue._generated.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", "azure.storage.queue._generated.aio.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", "azure.storage.queue._generated.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", @@ -56,8 +56,8 @@ "azure.storage.queue._generated.aio.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", "azure.storage.queue._generated.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", "azure.storage.queue._generated.aio.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", - "azure.storage.queue._generated.operations.QueueOperations.update": "Storage.Queues.Queue.update", - "azure.storage.queue._generated.aio.operations.QueueOperations.update": "Storage.Queues.Queue.update", + "azure.storage.queue._generated.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", + "azure.storage.queue._generated.aio.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", "azure.storage.queue._generated.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage", "azure.storage.queue._generated.aio.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage" } diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 3dd68b25c6ee..376c1a558b30 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -268,22 +268,20 @@ 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: ~datetime.datetime + :vartype start: str :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :vartype expiry: ~datetime.datetime + :vartype expiry: str :ivar delegated_user_tid: The delegated user tenant id in Azure AD. :vartype delegated_user_tid: str """ - start: Optional[datetime.datetime] = rest_field( + start: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, ) """The date-time the key is active in ISO 8601 UTC time.""" - expiry: datetime.datetime = rest_field( + expiry: str = rest_field( visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, ) """The date-time the key expires in ISO 8601 UTC time. Required.""" @@ -300,8 +298,8 @@ class KeyInfo(_Model): def __init__( self, *, - expiry: datetime.datetime, - start: Optional[datetime.datetime] = None, + expiry: str, + start: Optional[str] = None, delegated_user_tid: Optional[str] = None, ) -> None: ... diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py index 486caaf47996..37cc2976fb77 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py @@ -73,7 +73,7 @@ def __init__(self) -> None: def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[str, Any]) -> object: messages = obj.items_property if hasattr(obj, "items_property") else obj - for message in (messages or []): + for message in messages or []: if message.message_text in [None, "", b""]: continue content = message.message_text 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 ddf3651c15e5..a5c72bd0a04f 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -348,7 +348,7 @@ def __init__( expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - super().__init__(start=start, expiry=expiry, permission=permission) + super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] class QueueMessage(DictMixin): @@ -453,7 +453,9 @@ def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: raise StopIteration("End of paging") if self._max_messages is not None: 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 + 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 3486b94a1870..95a27d67bf2c 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 @@ -119,9 +119,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, version=get_api_version(api_version), 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: @@ -681,7 +679,9 @@ def receive_message( **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message.items_property[0]) if message.items_property else None # pylint: disable=protected-access + QueueMessage._from_generated(message.items_property[0]) + if message.items_property + else None # pylint: disable=protected-access ) return wrapped_message except HttpResponseError as error: @@ -977,7 +977,7 @@ def peek_messages( number_of_messages=max_messages, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_messages = [] - for peeked in (messages.items_property or []): + 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: 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 631431c4c8a1..e6a6535c4f9c 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 @@ -116,9 +116,7 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage( - self.url, version=get_api_version(api_version), 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: 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 a072ebf470a4..de978d301b79 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 @@ -176,8 +176,11 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p error_message += f"\n{name}:{info}" if additional_data.get("headername") == "x-ms-version" and error_code == StorageErrorCode.INVALID_HEADER_VALUE: - error_message = ("The provided service version is not enabled on this storage account." + - f"Please see {SV_DOCS_URL} for additional information.\n" + error_message) + error_message = ( + "The provided service version is not enabled on this storage account." + + f"Please see {SV_DOCS_URL} for additional information.\n" + + error_message + ) # No need to create an instance if it has already been serialized by the generated layer if serialized: @@ -215,4 +218,4 @@ def parse_to_internal_user_delegation_key(service_user_delegation_key): 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 - return internal_user_delegation_key \ No newline at end of file + return internal_user_delegation_key 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 4739611c8781..3ce81c629984 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 @@ -66,7 +66,9 @@ async def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage] raise StopAsyncIteration("End of paging") if self._max_messages is not None: 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 + 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 d2bd8004bc07..7f02b05c8c35 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 @@ -132,9 +132,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, version=get_api_version(api_version), pipeline=self._pipeline - ) + self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) self._loop = loop self._configure_encryption(kwargs) @@ -697,7 +695,9 @@ async def receive_message( **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message.items_property[0]) if message.items_property else None # pylint: disable=protected-access + QueueMessage._from_generated(message.items_property[0]) + if message.items_property + else None # pylint: disable=protected-access ) return wrapped_message except HttpResponseError as error: @@ -983,7 +983,7 @@ async def peek_messages( number_of_messages=max_messages, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_messages = [] - for peeked in (messages.items_property or []): + 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: 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 b999396e8617..594dc42ea4ca 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 @@ -115,9 +115,7 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage( - self.url, version=get_api_version(api_version), pipeline=self._pipeline - ) + self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) self._loop = loop self._configure_encryption(kwargs) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index fa64a5594671..c0c6bf12458e 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -43,11 +43,20 @@ dynamic = [ repository = "https://github.com/Azure/azure-sdk-for-python" [tool.setuptools.dynamic] -version = {attr = "azure.storage.queue._version.VERSION"} +version = {attr = "azure.storage.queue._generated._version.VERSION"} readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} [tool.setuptools.packages.find] -include = ["azure.storage.queue*"] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.storage", + "azure.storage.queue", +] [tool.setuptools.package-data] pytyped = ["py.typed"] From 38e05ae04b0551e2a03db2246a946e5ca3fbbf27 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 18 Mar 2026 14:13:33 -0700 Subject: [PATCH 014/102] regen --- .../azure/storage/queue/__init__.py | 65 +--------------- .../storage/queue/_generated/CHANGELOG.md | 7 -- .../azure/storage/queue/_generated/LICENSE | 21 ----- .../storage/queue/_generated/MANIFEST.in | 7 -- .../azure/storage/queue/_generated/README.md | 78 ------------------- .../queue/_generated/dev_requirements.txt | 4 - .../storage/queue/_generated/pyproject.toml | 61 --------------- .../queue/_generated/tsp-location.yaml | 4 - .../azure/storage/queue/_queue_client.py | 1 + .../queue/_shared/response_handlers.py | 1 + .../storage/queue/aio/_queue_client_async.py | 1 + .../azure-storage-queue/tests/test_queue.py | 1 + .../tests/test_queue_async.py | 1 + 13 files changed, 6 insertions(+), 246 deletions(-) delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/pyproject.toml delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py index 61b7e3b04c1b..d55ccad1f573 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py @@ -1,64 +1 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from ._version import VERSION -from ._queue_client import QueueClient -from ._queue_service_client import QueueServiceClient -from ._shared_access_signature import generate_account_sas, generate_queue_sas -from ._shared.policies import ExponentialRetry, LinearRetry -from ._shared.models import ( - LocationMode, - ResourceTypes, - AccountSasPermissions, - UserDelegationKey, - StorageErrorCode, - Services, -) -from ._message_encoding import ( - TextBase64EncodePolicy, - TextBase64DecodePolicy, - BinaryBase64EncodePolicy, - BinaryBase64DecodePolicy, -) -from ._models import ( - QueueMessage, - QueueProperties, - QueueSasPermissions, - AccessPolicy, - QueueAnalyticsLogging, - Metrics, - CorsRule, - RetentionPolicy, -) - -__version__ = VERSION - -__all__ = [ - "AccessPolicy", - "AccountSasPermissions", - "BinaryBase64DecodePolicy", - "BinaryBase64EncodePolicy", - "CorsRule", - "ExponentialRetry", - "generate_account_sas", - "generate_queue_sas", - "Metrics", - "LinearRetry", - "LocationMode", - "ResourceTypes", - "StorageErrorCode", - "QueueClient", - "QueueAnalyticsLogging", - "QueueMessage", - "QueueProperties", - "QueueSasPermissions", - "QueueServiceClient", - "RetentionPolicy", - "Services", - "TextBase64EncodePolicy", - "TextBase64DecodePolicy", - "UserDelegationKey", -] +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md deleted file mode 100644 index b957b2575b48..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/CHANGELOG.md +++ /dev/null @@ -1,7 +0,0 @@ -# Release History - -## 1.0.0b1 (1970-01-01) - -### Other Changes - - - Initial version \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE deleted file mode 100644 index 63447fd8bbbf..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) Microsoft Corporation. - -MIT License - -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. \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in deleted file mode 100644 index abf72b906875..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/MANIFEST.in +++ /dev/null @@ -1,7 +0,0 @@ -include *.md -include LICENSE -include azure/storage/queues/py.typed -recursive-include tests *.py -recursive-include samples *.py *.md -include azure/__init__.py -include azure/storage/__init__.py diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md deleted file mode 100644 index ae056634e4cf..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# Azure Storage Queue client library for Python - - -## Getting started - -### Install the package - -```bash -python -m pip install azure-storage-queue -``` - -#### Prequisites - -- Python 3.9 or later is required to use this package. -- You need an [Azure subscription][azure_sub] to use this package. -- An existing Azure Storage Queue instance. - -#### Create with an Azure Active Directory Credential -To use an [Azure Active Directory (AAD) token credential][authenticate_with_token], -provide an instance of the desired credential type obtained from the -[azure-identity][azure_identity_credentials] library. - -To authenticate with AAD, you must first [pip][pip] install [`azure-identity`][azure_identity_pip] - -After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use. -As an example, [DefaultAzureCredential][default_azure_credential] can be used to authenticate the client: - -Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: -`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET` - -Use the returned token credential to authenticate the client: - -```python ->>> from azure.storage.queues import QueuesClient ->>> from azure.identity import DefaultAzureCredential ->>> client = QueuesClient(endpoint='', credential=DefaultAzureCredential()) -``` - -## Examples - -```python ->>> from azure.storage.queues import QueuesClient ->>> from azure.identity import DefaultAzureCredential ->>> from azure.core.exceptions import HttpResponseError - ->>> client = QueuesClient(endpoint='', credential=DefaultAzureCredential()) ->>> try: - - except HttpResponseError as e: - print('service responds error: {}'.format(e.response.json())) - -``` - -## Contributing - -This project welcomes contributions and suggestions. Most contributions require -you to agree to a Contributor License Agreement (CLA) declaring that you have -the right to, and actually do, grant us the rights to use your contribution. -For details, visit https://cla.microsoft.com. - -When you submit a pull request, a CLA-bot will automatically determine whether -you need to provide a CLA and decorate the PR appropriately (e.g., label, -comment). Simply follow the instructions provided by the bot. You will only -need to do this once across all repos using our CLA. - -This project has adopted the -[Microsoft Open Source Code of Conduct][code_of_conduct]. For more information, -see the Code of Conduct FAQ or contact opencode@microsoft.com with any -additional questions or comments. - - -[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ -[authenticate_with_token]: https://docs.microsoft.com/azure/cognitive-services/authentication?tabs=powershell#authenticate-with-an-authentication-token -[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials -[azure_identity_pip]: https://pypi.org/project/azure-identity/ -[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential -[pip]: https://pypi.org/project/pip/ -[azure_sub]: https://azure.microsoft.com/free/ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt deleted file mode 100644 index ad0907b03b93..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/dev_requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ --e ../../../eng/tools/azure-sdk-tools -../../core/azure-core -../../identity/azure-identity -aiohttp \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/pyproject.toml b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/pyproject.toml deleted file mode 100644 index 87ca77de7d66..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/pyproject.toml +++ /dev/null @@ -1,61 +0,0 @@ -# -------------------------------------------------------------------------- -# 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 = "azpysdkhelp@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.37.0", - "typing-extensions>=4.6.0", -] -dynamic = [ -"version", "readme" -] - -[project.urls] -repository = "https://github.com/Azure/azure-sdk-for-python" - -[tool.setuptools.dynamic] -version = {attr = "azure.storage.queues._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"] diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml deleted file mode 100644 index b785991fc1da..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/tsp-location.yaml +++ /dev/null @@ -1,4 +0,0 @@ -directory: specification/storage/Microsoft.QueueStorage -commit: -repo: -additionalDirectories: 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 95a27d67bf2c..8178f1075444 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 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 de978d301b79..1d271a20a66b 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 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 7f02b05c8c35..2ea3bfe92687 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 diff --git a/sdk/storage/azure-storage-queue/tests/test_queue.py b/sdk/storage/azure-storage-queue/tests/test_queue.py index b010159d7490..8fc6a21bed76 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 c79124c5ab6f..bb5b9ad5edcd 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 From 7cf6d0147dbe94832e6b8e7901aa714ba8656613 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 18 Mar 2026 14:33:21 -0700 Subject: [PATCH 015/102] sphinx --- sdk/storage/azure-storage-queue/pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index c0c6bf12458e..3418dbd26e35 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -55,7 +55,6 @@ exclude = [ "doc*", "azure", "azure.storage", - "azure.storage.queue", ] [tool.setuptools.package-data] From 1df6198217b092185db378124e653163ebd1501f Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 19 Mar 2026 09:41:54 -0700 Subject: [PATCH 016/102] regen+fixing apistub --- sdk/storage/azure-storage-queue/pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index 3418dbd26e35..c0c6bf12458e 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -55,6 +55,7 @@ exclude = [ "doc*", "azure", "azure.storage", + "azure.storage.queue", ] [tool.setuptools.package-data] From a049612357ed5b9e091326824b679fcad747cfac Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 19 Mar 2026 12:23:48 -0700 Subject: [PATCH 017/102] version file --- sdk/storage/azure-storage-queue/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index c0c6bf12458e..aaabfab61ab7 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -43,7 +43,7 @@ dynamic = [ repository = "https://github.com/Azure/azure-sdk-for-python" [tool.setuptools.dynamic] -version = {attr = "azure.storage.queue._generated._version.VERSION"} +version = {attr = "azure.storage.queue._version.VERSION"} readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} [tool.setuptools.packages.find] From 6124cf38f47150ebdd74439d4cccb600b2484c9d Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 19 Mar 2026 12:44:30 -0700 Subject: [PATCH 018/102] q --- sdk/storage/azure-storage-queue/pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index aaabfab61ab7..fbf916ed760f 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -55,7 +55,6 @@ exclude = [ "doc*", "azure", "azure.storage", - "azure.storage.queue", ] [tool.setuptools.package-data] From ced01627f2077e9f449018ce39512b21e4ab2479 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 19 Mar 2026 13:05:15 -0700 Subject: [PATCH 019/102] edit --- sdk/storage/azure-storage-queue/MANIFEST.in | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/storage/azure-storage-queue/MANIFEST.in b/sdk/storage/azure-storage-queue/MANIFEST.in index bae0431342c4..8c82f51685f9 100644 --- a/sdk/storage/azure-storage-queue/MANIFEST.in +++ b/sdk/storage/azure-storage-queue/MANIFEST.in @@ -1,5 +1,6 @@ include *.md include LICENSE +include azure/storage/queue/py.typed include azure/storage/queue/_generated/py.typed recursive-include tests *.py recursive-include samples *.py *.md From 21a96ce42059c692adb3dd0f3173c9bf4804adf4 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 19 Mar 2026 13:17:53 -0700 Subject: [PATCH 020/102] pylint fix --- .../azure/storage/queue/__init__.py | 65 ++++++++++++++++++- .../azure/storage/queue/_models.py | 4 +- .../azure/storage/queue/_queue_client.py | 4 +- .../azure/storage/queue/aio/_models.py | 4 +- .../storage/queue/aio/_queue_client_async.py | 4 +- 5 files changed, 72 insertions(+), 9 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py index d55ccad1f573..61b7e3b04c1b 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/__init__.py @@ -1 +1,64 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from ._version import VERSION +from ._queue_client import QueueClient +from ._queue_service_client import QueueServiceClient +from ._shared_access_signature import generate_account_sas, generate_queue_sas +from ._shared.policies import ExponentialRetry, LinearRetry +from ._shared.models import ( + LocationMode, + ResourceTypes, + AccountSasPermissions, + UserDelegationKey, + StorageErrorCode, + Services, +) +from ._message_encoding import ( + TextBase64EncodePolicy, + TextBase64DecodePolicy, + BinaryBase64EncodePolicy, + BinaryBase64DecodePolicy, +) +from ._models import ( + QueueMessage, + QueueProperties, + QueueSasPermissions, + AccessPolicy, + QueueAnalyticsLogging, + Metrics, + CorsRule, + RetentionPolicy, +) + +__version__ = VERSION + +__all__ = [ + "AccessPolicy", + "AccountSasPermissions", + "BinaryBase64DecodePolicy", + "BinaryBase64EncodePolicy", + "CorsRule", + "ExponentialRetry", + "generate_account_sas", + "generate_queue_sas", + "Metrics", + "LinearRetry", + "LocationMode", + "ResourceTypes", + "StorageErrorCode", + "QueueClient", + "QueueAnalyticsLogging", + "QueueMessage", + "QueueProperties", + "QueueSasPermissions", + "QueueServiceClient", + "RetentionPolicy", + "Services", + "TextBase64EncodePolicy", + "TextBase64DecodePolicy", + "UserDelegationKey", +] 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 a5c72bd0a04f..423ed442a1b0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -454,8 +454,8 @@ def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: if self._max_messages is not None: 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 + 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 8178f1075444..f5d27d1cbb95 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 @@ -680,9 +680,9 @@ def receive_message( **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message.items_property[0]) + QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access if message.items_property - else None # pylint: disable=protected-access + else None ) return wrapped_message except HttpResponseError as error: 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 3ce81c629984..e610c34e238a 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 @@ -67,8 +67,8 @@ async def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage] if self._max_messages is not None: 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 + 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 2ea3bfe92687..e857f74ffa73 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 @@ -696,9 +696,9 @@ async def receive_message( **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message.items_property[0]) + QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access if message.items_property - else None # pylint: disable=protected-access + else None ) return wrapped_message except HttpResponseError as error: From 730959c5646d4132aa1a2922c5810bf8d7bb1c81 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 23 Mar 2026 13:49:38 -0700 Subject: [PATCH 021/102] regen --- .../queue/_generated/_utils/model_base.py | 6 + .../_generated/aio/operations/_operations.py | 22 +- .../queue/_generated/models/_models.py | 14 +- .../storage/queue/_generated/models/_patch.py | 226 +++++++++++++++++- .../_generated/operations/_operations.py | 49 ++-- .../azure/storage/queue/_queue_client.py | 2 +- .../azure/storage/queue/aio/_models.py | 2 +- .../storage/queue/aio/_queue_client_async.py | 4 +- 8 files changed, 285 insertions(+), 40 deletions(-) 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 index 9616929f7415..a75a22adbb97 100644 --- 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 @@ -630,6 +630,9 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if len(items) > 0: existed_attr_keys.append(xml_name) dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = [] continue # text element is primitive type @@ -905,6 +908,8 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # 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 @@ -1084,6 +1089,7 @@ def __init__( 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 diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py index 59a6040ca394..e13258c997cc 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py @@ -703,15 +703,17 @@ async def delete(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def set_metadata(self, *, metadata: str, timeout: Optional[int] = None, **kwargs: Any) -> None: + 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 metadata: The metadata headers. Required. - :paramtype metadata: 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 + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -730,8 +732,8 @@ async def set_metadata(self, *, metadata: str, timeout: Optional[int] = None, ** cls: ClsType[None] = kwargs.pop("cls", None) _request = build_queue_set_metadata_request( - metadata=metadata, timeout=timeout, + metadata=metadata, version=self._config.version, headers=_headers, params=_params, @@ -846,11 +848,11 @@ async def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An @distributed_trace_async async def set_access_policy( - self, queue_acl: _models.SignedIdentifiers, *, timeout: Optional[int] = None, **kwargs: Any + 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. Required. + :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 @@ -871,10 +873,14 @@ async def set_access_policy( _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")) + 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) - _content = _get_element(queue_acl) + if queue_acl is not None: + _content = _get_element(queue_acl) + else: + _content = None _request = build_queue_set_access_policy_request( timeout=timeout, diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 376c1a558b30..3dd68b25c6ee 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -268,20 +268,22 @@ 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 + :vartype start: ~datetime.datetime :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :vartype expiry: str + :vartype expiry: ~datetime.datetime :ivar delegated_user_tid: The delegated user tenant id in Azure AD. :vartype delegated_user_tid: str """ - start: Optional[str] = rest_field( + start: Optional[datetime.datetime] = rest_field( visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", 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( + expiry: datetime.datetime = rest_field( visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, ) """The date-time the key expires in ISO 8601 UTC time. Required.""" @@ -298,8 +300,8 @@ class KeyInfo(_Model): def __init__( self, *, - expiry: str, - start: Optional[str] = None, + expiry: datetime.datetime, + start: Optional[datetime.datetime] = None, delegated_user_tid: Optional[str] = None, ) -> None: ... 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 87676c65a8f0..4eeb4b081f0b 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,3 +1,4 @@ +# cod# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,9 +8,230 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +import xml.etree.ElementTree as ET +from typing import List +from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField +from ._models import ( + AccessPolicy as _GenAccessPolicy, + CorsRule as _GenCorsRule, + Logging as _GenLogging, + Metrics as _GenMetrics, + RetentionPolicy as _GenRetentionPolicy, +) -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + +def _lazy_data_getattr(self, name): + """Lazily initialize _data for subclasses that skip super().__init__().""" + if name == "_data": + object.__setattr__(self, "_data", {}) + return self._data + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + +def _model_setattr(self, name, value): + """Route attribute writes through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + # Walk the MRO looking for a _RestField descriptor that may be shadowed + for cls in type(self).__mro__: + member = cls.__dict__.get(name) + if isinstance(member, _RestField): + member.__set__(self, value) + return + object.__setattr__(self, name, value) + + +def _model_getattribute(self, name): + """Route attribute reads through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + try: + rest_fields = type(self)._attr_to_rest_field + except AttributeError: + pass + else: + rf = rest_fields.get(name) + if rf is not None: + return rf.__get__(self, type(self)) + return object.__getattribute__(self, name) + + +_MyMutableMapping.__getattr__ = _lazy_data_getattr +_MyMutableMapping.__setattr__ = _model_setattr +_MyMutableMapping.__getattribute__ = _model_getattribute + + +# --------------------------------------------------------------------------- +# Fix Model.__new__ to resolve _RestField forward references against the +# module that *defined* the field, not whichever subclass is instantiated +# first. The original code does ``rf._module = cls.__module__`` which lets +# an external subclass (e.g. from azure-storage-file-datalake) overwrite +# _module on the shared descriptor, corrupting type resolution for everyone. +# --------------------------------------------------------------------------- +_orig_model_new = _Model.__new__ + + +def _patched_model_new(cls, *args, **kwargs): + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + mros = cls.__mro__[:-9][::-1] + attr_to_rest_field = {} + # Track which MRO class defined each rest_field so we resolve + # forward references against the *defining* module, not cls. + attr_to_defining_class = {} + for mro_class in mros: + for k, v in mro_class.__dict__.items(): + if k[0] != "_" and hasattr(v, "_type"): + attr_to_rest_field[k] = v + attr_to_defining_class[k] = mro_class + + 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(): + # Use the defining class's module for forward-ref resolution + defining_cls = attr_to_defining_class[attr] + rf._module = defining_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(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field = { + _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 object.__new__(cls) + + +_Model.__new__ = _patched_model_new + + +# --------------------------------------------------------------------------- +# Autorest serialization compatibility layer +# --------------------------------------------------------------------------- +# The old autorest serialization pipeline (Serializer/Deserializer from +# _utils.serialization) relies on class-level _attribute_map, _validation, +# _xml_map, is_xml_model(), and _create_xml_node() — none of which exist on +# the new model_base.Model subclasses. The wrappers below add exactly those +# attributes so that the operations code can keep serializing/deserializing +# them unchanged. +# --------------------------------------------------------------------------- + + +def _create_xml_node(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +class _AutorestCompatMixin: + """Adds msrest-style (de)serialization hooks to ``model_base.Model`` subclasses.""" + + _attribute_map: dict = {} + _validation: dict = {} + + @classmethod + def is_xml_model(cls) -> bool: + return bool(getattr(cls, "_xml_map", None)) + + @classmethod + def _create_xml_node(cls): + xml_map = getattr(cls, "_xml_map", {}) + return _create_xml_node( + xml_map.get("name", cls.__name__), + xml_map.get("prefix"), + xml_map.get("ns"), + ) + + +class AccessPolicy(_AutorestCompatMixin, _GenAccessPolicy): + """AccessPolicy with autorest serialization compatibility.""" + + _attribute_map = { + "start": {"key": "Start", "type": "str"}, + "expiry": {"key": "Expiry", "type": "str"}, + "permission": {"key": "Permission", "type": "str"}, + } + + +class CorsRule(_AutorestCompatMixin, _GenCorsRule): + """CorsRule with autorest serialization compatibility.""" + + _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"}, + } + + +class Logging(_AutorestCompatMixin, _GenLogging): + """Logging with autorest serialization compatibility.""" + + _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"}, + } + + +class Metrics(_AutorestCompatMixin, _GenMetrics): + """Metrics with autorest serialization compatibility.""" + + _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"}, + } + + +class RetentionPolicy(_AutorestCompatMixin, _GenRetentionPolicy): + """RetentionPolicy with autorest serialization compatibility.""" + + _validation = { + "enabled": {"required": True}, + "days": {"minimum": 1}, + } + _attribute_map = { + "enabled": {"key": "Enabled", "type": "bool"}, + "days": {"key": "Days", "type": "int"}, + "allow_permanent_delete": {"key": "AllowPermanentDelete", "type": "bool"}, + } + +__all__: List[str] = [ + "AccessPolicy", + "CorsRule", + "Logging", + "Metrics", + "RetentionPolicy", +] def patch_sdk(): @@ -18,4 +240,4 @@ def patch_sdk(): `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 - """ + """ \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py index 5dabaec56a94..3cac2fcbf9cd 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py @@ -219,7 +219,9 @@ def build_queue_delete_request(*, timeout: Optional[int] = None, **kwargs: Any) return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_queue_set_metadata_request(*, metadata: str, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: +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 {}) @@ -233,7 +235,8 @@ def build_queue_set_metadata_request(*, metadata: str, timeout: Optional[int] = # Construct headers _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "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) @@ -263,7 +266,7 @@ def build_queue_set_access_policy_request(*, timeout: Optional[int] = None, **kw _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") + 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" @@ -274,7 +277,8 @@ def build_queue_set_access_policy_request(*, timeout: Optional[int] = None, **kw # Construct headers _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "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) @@ -293,7 +297,7 @@ def build_queue_receive_messages_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "messages" + _url = "/messages" # Construct parameters if number_of_messages is not None: @@ -316,7 +320,7 @@ def build_queue_clear_request(*, timeout: Optional[int] = None, **kwargs: Any) - version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "messages" + _url = "/messages" # Construct parameters if timeout is not None: @@ -343,7 +347,7 @@ def build_queue_send_message_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "messages" + _url = "/messages" # Construct parameters if visibility_timeout is not None: @@ -371,7 +375,7 @@ def build_queue_peek_messages_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "messages?peekonly=true" + _url = "/messages?peekonly=true" # Construct parameters if number_of_messages is not None: @@ -392,10 +396,10 @@ def build_queue_update_message_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") + 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}" + _url = "/messages/{messageId}" path_format_arguments = { "messageId": _SERIALIZER.url("message_id", message_id, "str"), } @@ -410,7 +414,8 @@ def build_queue_update_message_request( # Construct headers _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "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) @@ -423,7 +428,7 @@ def build_queue_delete_message_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "messages/{messageId}" + _url = "/messages/{messageId}" path_format_arguments = { "messageId": _SERIALIZER.url("message_id", message_id, "str"), } @@ -1098,16 +1103,16 @@ def delete( # pylint: disable=inconsistent-return-statements @distributed_trace def set_metadata( # pylint: disable=inconsistent-return-statements - self, *, metadata: str, timeout: Optional[int] = None, **kwargs: Any + 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 metadata: The metadata headers. Required. - :paramtype metadata: 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 + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1126,8 +1131,8 @@ def set_metadata( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) _request = build_queue_set_metadata_request( - metadata=metadata, timeout=timeout, + metadata=metadata, version=self._config.version, headers=_headers, params=_params, @@ -1242,11 +1247,11 @@ def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: Any) -> @distributed_trace def set_access_policy( # pylint: disable=inconsistent-return-statements - self, queue_acl: _models.SignedIdentifiers, *, timeout: Optional[int] = None, **kwargs: Any + 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. Required. + :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 @@ -1267,10 +1272,14 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements _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")) + 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) - _content = _get_element(queue_acl) + if queue_acl is not None: + _content = _get_element(queue_acl) + else: + _content = None _request = build_queue_set_access_policy_request( timeout=timeout, 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 f5d27d1cbb95..08f0a772c48e 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 @@ -456,7 +456,7 @@ def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An ) except HttpResponseError as error: process_storage_error(error) - return {s.id: s.access_policy or AccessPolicy() for s in identifiers} + return {s.id: s.access_policy or AccessPolicy() for s in identifiers.items_property} if identifiers else {} @distributed_trace def set_queue_access_policy( 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 e610c34e238a..13c2e1c707f3 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 @@ -67,7 +67,7 @@ async def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage] if self._max_messages is not None: 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 + QueueMessage._from_generated(q) for q in messages.items_property # pylint: disable=protected-access ] 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 e857f74ffa73..a65e84749a95 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 @@ -472,7 +472,7 @@ async def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwar ) except HttpResponseError as error: process_storage_error(error) - return {s.id: s.access_policy or AccessPolicy() for s in identifiers} + return {s.id: s.access_policy or AccessPolicy() for s in identifiers.items_property} if identifiers else {} @distributed_trace_async async def set_queue_access_policy( @@ -696,7 +696,7 @@ async def receive_message( **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access + QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access if message.items_property else None ) From 5576280164d2671f6c98d47e37d59e8b89a8221f Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 23 Mar 2026 13:49:45 -0700 Subject: [PATCH 022/102] encoding?? --- .../azure/storage/queue/_message_encoding.py | 5 ++++- .../azure-storage-queue/azure/storage/queue/_models.py | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py index 37cc2976fb77..f0ce395082e8 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py @@ -81,7 +81,10 @@ def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[st content = decrypt_queue_message( content, response, self.require_encryption, 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 423ed442a1b0..8a0772b3afa0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -389,7 +389,12 @@ 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 (set by MessageDecodePolicy) over message_text + # because the _RestField descriptor re-serializes bytes to base64 on assignment. + 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 From 03928762c74f779a655a2d9f8ac921f363bb6041 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 23 Mar 2026 15:20:25 -0700 Subject: [PATCH 023/102] regen keyinfo as string --- .../queue/_generated/models/_models.py | 14 ++++++-------- .../storage/queue/_generated/models/_patch.py | 3 ++- .../azure/storage/queue/_models.py | 2 +- .../azure/storage/queue/_queue_client.py | 19 +++++++++++++++++-- .../storage/queue/aio/_queue_client_async.py | 19 +++++++++++++++++-- 5 files changed, 43 insertions(+), 14 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 3dd68b25c6ee..376c1a558b30 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -268,22 +268,20 @@ 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: ~datetime.datetime + :vartype start: str :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :vartype expiry: ~datetime.datetime + :vartype expiry: str :ivar delegated_user_tid: The delegated user tenant id in Azure AD. :vartype delegated_user_tid: str """ - start: Optional[datetime.datetime] = rest_field( + start: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, ) """The date-time the key is active in ISO 8601 UTC time.""" - expiry: datetime.datetime = rest_field( + expiry: str = rest_field( visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, ) """The date-time the key expires in ISO 8601 UTC time. Required.""" @@ -300,8 +298,8 @@ class KeyInfo(_Model): def __init__( self, *, - expiry: datetime.datetime, - start: Optional[datetime.datetime] = None, + expiry: str, + start: Optional[str] = None, delegated_user_tid: Optional[str] = None, ) -> None: ... 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 4eeb4b081f0b..fdd9d5e483d2 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 @@ -225,6 +225,7 @@ class RetentionPolicy(_AutorestCompatMixin, _GenRetentionPolicy): "allow_permanent_delete": {"key": "AllowPermanentDelete", "type": "bool"}, } + __all__: List[str] = [ "AccessPolicy", "CorsRule", @@ -240,4 +241,4 @@ def patch_sdk(): `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 - """ \ No newline at end of file + """ 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 8a0772b3afa0..976e1ac810ab 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -391,7 +391,7 @@ def __init__(self, content: Optional[Any] = None, **kwargs: Any) -> None: def _from_generated(cls, generated: Any) -> Self: # Prefer _decoded_content (set by MessageDecodePolicy) over message_text # because the _RestField descriptor re-serializes bytes to base64 on assignment. - content = getattr(generated, '_decoded_content', None) + content = getattr(generated, "_decoded_content", None) if content is None: content = generated.message_text message = cls(content=content) 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 08f0a772c48e..c11c584466a8 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 @@ -451,12 +451,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.items_property} if identifiers else {} + 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 + } + if identifiers + else {} + ) @distributed_trace def set_queue_access_policy( 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 a65e84749a95..f54ac6616482 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 @@ -465,14 +465,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.items_property} if identifiers else {} + 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 + } + if identifiers + else {} + ) @distributed_trace_async async def set_queue_access_policy( From ca32d824cec616c1243ef56664c2cb9222e642a7 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 23 Mar 2026 15:42:10 -0700 Subject: [PATCH 024/102] pin azure-core --- sdk/storage/azure-storage-queue/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index fbf916ed760f..99bedcc12c98 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -32,7 +32,7 @@ keywords = ["azure", "azure sdk"] dependencies = [ "isodate>=0.6.1", - "azure-core>=1.37.0", + "azure-core>=1.38.3", "typing-extensions>=4.6.0", ] dynamic = [ From 7f37a1cb2584de98aaf1b3af84f4f3b2764aaca9 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 25 Mar 2026 15:15:53 -0700 Subject: [PATCH 025/102] xml.name --- .../azure/storage/queue/_generated/models/_models.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 376c1a558b30..615153e30084 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -600,7 +600,7 @@ class PeekedMessage(_Model): ) """The content of the Message. Required.""" - _xml = {"attribute": False, "name": "PeekedMessage", "text": False, "unwrapped": False} + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} @overload def __init__( @@ -896,7 +896,7 @@ class ReceivedMessage(_Model): ) """The content of the message. Required.""" - _xml = {"attribute": False, "name": "ReceivedMessage", "text": False, "unwrapped": False} + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} @overload def __init__( @@ -1051,7 +1051,7 @@ class SentMessage(_Model): ) """The time that the message will again become visible in the Queue. Required.""" - _xml = {"attribute": False, "name": "SentMessage", "text": False, "unwrapped": False} + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} @overload def __init__( From 6699c41601c092a14f6c8d851ca7b72e3d3f2696 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 10:28:40 -0700 Subject: [PATCH 026/102] update --- .../storage/queue/_generated/models/_patch.py | 225 ++++-------------- .../azure/storage/queue/_models.py | 52 ++-- 2 files changed, 70 insertions(+), 207 deletions(-) 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 fdd9d5e483d2..33311a35a2e4 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,4 +1,4 @@ -# cod# pylint: disable=line-too-long,useless-suppression +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -8,20 +8,13 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import xml.etree.ElementTree as ET -from typing import List +import datetime +from typing import List, Optional -from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField -from ._models import ( - AccessPolicy as _GenAccessPolicy, - CorsRule as _GenCorsRule, - Logging as _GenLogging, - Metrics as _GenMetrics, - RetentionPolicy as _GenRetentionPolicy, -) +from .._utils.model_base import Model as _Model, rest_field, _MyMutableMapping, _RestField -def _lazy_data_getattr(self, name): +def _patched_getattr(self, name): """Lazily initialize _data for subclasses that skip super().__init__().""" if name == "_data": object.__setattr__(self, "_data", {}) @@ -29,19 +22,21 @@ def _lazy_data_getattr(self, name): raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") -def _model_setattr(self, name, value): +def _patched_setattr(self, name, value): """Route attribute writes through _RestField descriptors even when shadowed.""" if not name.startswith("_"): - # Walk the MRO looking for a _RestField descriptor that may be shadowed - for cls in type(self).__mro__: - member = cls.__dict__.get(name) - if isinstance(member, _RestField): - member.__set__(self, value) + try: + rf = type(self)._attr_to_rest_field.get(name) + except AttributeError: + pass + else: + if rf is not None: + rf.__set__(self, value) return object.__setattr__(self, name, value) -def _model_getattribute(self, name): +def _patched_getattribute(self, name): """Route attribute reads through _RestField descriptors even when shadowed.""" if not name.startswith("_"): try: @@ -55,49 +50,39 @@ def _model_getattribute(self, name): return object.__getattribute__(self, name) -_MyMutableMapping.__getattr__ = _lazy_data_getattr -_MyMutableMapping.__setattr__ = _model_setattr -_MyMutableMapping.__getattribute__ = _model_getattribute - +# The original ``Model.__new__`` does ``rf._module = cls.__module__`` which +# lets an external subclass (e.g. from azure-storage-file-datalake) overwrite +# ``_module`` on the *shared* descriptor, corrupting type resolution for +# every class that shares it. This replacement resolves forward references +# against the module that *defined* the rest_field and uses that class's own +# annotations (not merged subclass annotations) to avoid resolving to a type +# whose ``__init__`` can't handle XML elements. -# --------------------------------------------------------------------------- -# Fix Model.__new__ to resolve _RestField forward references against the -# module that *defined* the field, not whichever subclass is instantiated -# first. The original code does ``rf._module = cls.__module__`` which lets -# an external subclass (e.g. from azure-storage-file-datalake) overwrite -# _module on the shared descriptor, corrupting type resolution for everyone. -# --------------------------------------------------------------------------- -_orig_model_new = _Model.__new__ - -def _patched_model_new(cls, *args, **kwargs): +def _patched_new(cls, *args, **kwargs): if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: - mros = cls.__mro__[:-9][::-1] - attr_to_rest_field = {} - # Track which MRO class defined each rest_field so we resolve - # forward references against the *defining* module, not cls. - attr_to_defining_class = {} - for mro_class in mros: + # Walk only user-defined classes (base-first), stopping before the + # framework base. Each _RestField is configured with the module of + # the class that defined it so forward references resolve correctly. + user_classes = [] + for c in cls.__mro__: + if c is _Model: + break + user_classes.append(c) + + attr_to_rest_field: dict[str, _RestField] = {} + for mro_class in reversed(user_classes): + annotations = getattr(mro_class, "__annotations__", {}) for k, v in mro_class.__dict__.items(): - if k[0] != "_" and hasattr(v, "_type"): + if not k.startswith("_") and isinstance(v, _RestField): attr_to_rest_field[k] = v - attr_to_defining_class[k] = mro_class + v._module = mro_class.__module__ + if not v._type: + v._type = v._get_deserialize_callable_from_annotation(annotations.get(k, None)) + if not v._rest_name_input: + v._rest_name_input = k - 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(): - # Use the defining class's module for forward-ref resolution - defining_cls = attr_to_defining_class[attr] - rf._module = defining_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(attr_to_rest_field.items()) + cls._attr_to_rest_field = attr_to_rest_field cls._backcompat_attr_to_rest_field = { _Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf for attr, rf in cls._attr_to_rest_field.items() @@ -107,131 +92,13 @@ def _patched_model_new(cls, *args, **kwargs): return object.__new__(cls) -_Model.__new__ = _patched_model_new - - -# --------------------------------------------------------------------------- -# Autorest serialization compatibility layer -# --------------------------------------------------------------------------- -# The old autorest serialization pipeline (Serializer/Deserializer from -# _utils.serialization) relies on class-level _attribute_map, _validation, -# _xml_map, is_xml_model(), and _create_xml_node() — none of which exist on -# the new model_base.Model subclasses. The wrappers below add exactly those -# attributes so that the operations code can keep serializing/deserializing -# them unchanged. -# --------------------------------------------------------------------------- - - -def _create_xml_node(tag, prefix=None, ns=None): - if prefix and ns: - ET.register_namespace(prefix, ns) - if ns: - return ET.Element("{" + ns + "}" + tag) - return ET.Element(tag) - - -class _AutorestCompatMixin: - """Adds msrest-style (de)serialization hooks to ``model_base.Model`` subclasses.""" - - _attribute_map: dict = {} - _validation: dict = {} - - @classmethod - def is_xml_model(cls) -> bool: - return bool(getattr(cls, "_xml_map", None)) - - @classmethod - def _create_xml_node(cls): - xml_map = getattr(cls, "_xml_map", {}) - return _create_xml_node( - xml_map.get("name", cls.__name__), - xml_map.get("prefix"), - xml_map.get("ns"), - ) - - -class AccessPolicy(_AutorestCompatMixin, _GenAccessPolicy): - """AccessPolicy with autorest serialization compatibility.""" - - _attribute_map = { - "start": {"key": "Start", "type": "str"}, - "expiry": {"key": "Expiry", "type": "str"}, - "permission": {"key": "Permission", "type": "str"}, - } - - -class CorsRule(_AutorestCompatMixin, _GenCorsRule): - """CorsRule with autorest serialization compatibility.""" - - _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"}, - } - - -class Logging(_AutorestCompatMixin, _GenLogging): - """Logging with autorest serialization compatibility.""" - - _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"}, - } - - -class Metrics(_AutorestCompatMixin, _GenMetrics): - """Metrics with autorest serialization compatibility.""" - - _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"}, - } - - -class RetentionPolicy(_AutorestCompatMixin, _GenRetentionPolicy): - """RetentionPolicy with autorest serialization compatibility.""" - - _validation = { - "enabled": {"required": True}, - "days": {"minimum": 1}, - } - _attribute_map = { - "enabled": {"key": "Enabled", "type": "bool"}, - "days": {"key": "Days", "type": "int"}, - "allow_permanent_delete": {"key": "AllowPermanentDelete", "type": "bool"}, - } +_MyMutableMapping.__getattr__ = _patched_getattr +_MyMutableMapping.__setattr__ = _patched_setattr +_MyMutableMapping.__getattribute__ = _patched_getattribute +_Model.__new__ = _patched_new __all__: List[str] = [ - "AccessPolicy", - "CorsRule", - "Logging", - "Metrics", - "RetentionPolicy", ] @@ -241,4 +108,4 @@ def patch_sdk(): `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 - """ + """ \ No newline at end of file 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 976e1ac810ab..abb3e9c184d7 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -45,7 +45,8 @@ class RetentionPolicy(GeneratedRetentionPolicy): """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: - super().__init__(enabled=enabled, days=days) + self.enabled = enabled + self.days = days if self.enabled and (self.days is None): raise ValueError("If policy is enabled, 'days' must be specified.") @@ -83,13 +84,11 @@ class QueueAnalyticsLogging(GeneratedLogging): """The retention policy for the metrics.""" def __init__(self, **kwargs: Any) -> None: - 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(), - ) + 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() @classmethod def _from_generated(cls, generated: Any) -> Self: @@ -128,12 +127,10 @@ class Metrics(GeneratedMetrics): """The retention policy for the metrics.""" def __init__(self, **kwargs: Any) -> None: - 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(), - ) + 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() @classmethod def _from_generated(cls, generated: Any) -> Self: @@ -194,13 +191,11 @@ class CorsRule(GeneratedCorsRule): request.""" def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: - 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), - ) + 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) @staticmethod def _to_generated(rules: Optional[List["CorsRule"]]) -> Optional[List[GeneratedCorsRule]]: @@ -348,7 +343,9 @@ def __init__( expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] + self.start = start + self.expiry = expiry + self.permission = permission class QueueMessage(DictMixin): @@ -389,9 +386,10 @@ def __init__(self, content: Optional[Any] = None, **kwargs: Any) -> None: @classmethod def _from_generated(cls, generated: Any) -> Self: - # Prefer _decoded_content (set by MessageDecodePolicy) over message_text - # because the _RestField descriptor re-serializes bytes to base64 on assignment. - content = getattr(generated, "_decoded_content", None) + # 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) @@ -458,9 +456,7 @@ def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: raise StopIteration("End of paging") if self._max_messages is not None: 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 - ] + return "TOKEN_IGNORED", [QueueMessage._from_generated(q) for q in messages.items_property] # pylint: disable=protected-access class QueueProperties(DictMixin): From ba3c0d06d0738b2745aad8566ccc6181a17f2883 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 10:37:11 -0700 Subject: [PATCH 027/102] regen --- sdk/storage/azure-storage-queue/MANIFEST.in | 1 - .../azure/storage/queue/_generated/_client.py | 4 ++-- .../azure/storage/queue/_generated/_configuration.py | 4 ++-- .../azure/storage/queue/_generated/aio/_client.py | 4 ++-- .../azure/storage/queue/_generated/aio/_configuration.py | 4 ++-- .../azure/storage/queue/_generated/models/_patch.py | 5 ++--- .../azure-storage-queue/azure/storage/queue/_models.py | 6 ++++-- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/sdk/storage/azure-storage-queue/MANIFEST.in b/sdk/storage/azure-storage-queue/MANIFEST.in index 8c82f51685f9..bae0431342c4 100644 --- a/sdk/storage/azure-storage-queue/MANIFEST.in +++ b/sdk/storage/azure-storage-queue/MANIFEST.in @@ -1,6 +1,5 @@ include *.md include LICENSE -include azure/storage/queue/py.typed include azure/storage/queue/_generated/py.typed recursive-include tests *.py recursive-include samples *.py *.md diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py index c04ab9922448..07be44526bb6 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py @@ -35,8 +35,8 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword :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" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ 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 dbd3023cb4b2..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 @@ -28,8 +28,8 @@ class QueuesClientConfiguration: # pylint: disable=too-many-instance-attributes :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" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py index 22f0c6df3b4d..f049fcf84d9e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py @@ -35,8 +35,8 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword :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" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ 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 8a5f480b8121..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 @@ -28,8 +28,8 @@ class QueuesClientConfiguration: # pylint: disable=too-many-instance-attributes :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" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ 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 33311a35a2e4..607f97c89a47 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 @@ -98,8 +98,7 @@ def _patched_new(cls, *args, **kwargs): _Model.__new__ = _patched_new -__all__: List[str] = [ -] +__all__: List[str] = [] def patch_sdk(): @@ -108,4 +107,4 @@ def patch_sdk(): `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 - """ \ No newline at end of file + """ 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 abb3e9c184d7..072dd2c9e76b 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -389,7 +389,7 @@ def _from_generated(cls, generated: Any) -> Self: # 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) + content = getattr(generated, "_decoded_content", None) if content is None: content = generated.message_text message = cls(content=content) @@ -456,7 +456,9 @@ def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: raise StopIteration("End of paging") if self._max_messages is not None: 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 + return "TOKEN_IGNORED", [ + QueueMessage._from_generated(q) for q in messages.items_property + ] # pylint: disable=protected-access class QueueProperties(DictMixin): From 9e5f01b519b827eb12bc1d194f6479d0d5dd53d3 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 13:32:45 -0700 Subject: [PATCH 028/102] fix pylint --- .../azure-storage-queue/azure/storage/queue/_models.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 072dd2c9e76b..ec35881bdd32 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -457,8 +457,8 @@ def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: if self._max_messages is not None: 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 + QueueMessage._from_generated(q) for q in messages.items_property # pylint: disable=protected-access + ] class QueueProperties(DictMixin): From e753cc397b0a9b262e7ce517e9735581ced6c5d2 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 14:35:48 -0700 Subject: [PATCH 029/102] black --- sdk/storage/azure-storage-queue/azure/storage/queue/_models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 ec35881bdd32..3c56a4de737d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -457,7 +457,7 @@ def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: if self._max_messages is not None: 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 + QueueMessage._from_generated(q) for q in messages.items_property # pylint: disable=protected-access ] From a20698aaaf63c71e54ddf88e11cf963624c49a96 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 12:24:58 -0700 Subject: [PATCH 030/102] regen --- .../azure/storage/queue/_generated/_client.py | 2 +- .../queue/_generated/_utils/serialization.py | 51 ++++--------------- .../storage/queue/_generated/aio/_client.py | 2 +- 3 files changed, 11 insertions(+), 44 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py index 1a439ca54204..07be44526bb6 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py @@ -58,7 +58,7 @@ def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> No 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=_endpoint, policies=_policies, **kwargs) 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 85361bf87da6..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 @@ -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/aio/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py index b55b1c470dae..f049fcf84d9e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py @@ -58,7 +58,7 @@ def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) 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=_endpoint, policies=_policies, **kwargs) From 23236f7352713558dfb901c150ffef5abbdc28bf Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 12:39:37 -0700 Subject: [PATCH 031/102] ai version --- .../azure/storage/queue/_generated/_patch.py | 2 +- .../azure/storage/queue/_generated/aio/_patch.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 3ec106b3b5c2..428f6d049aec 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 @@ -29,7 +29,7 @@ def __init__(self, url: str, credential: "TokenCredential" = None, **kwargs: Any # When a pre-built pipeline is provided, skip the generated credential/policy setup. _endpoint = "{url}" self._config = QueuesClientConfiguration.__new__(QueuesClientConfiguration) - version = kwargs.pop("version", "2026-04-06") + version = kwargs.pop("version", "2026-06-06") self._config.url = url self._config.credential = credential self._config.version = version 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 3824d31d6dc4..bfd8573716c5 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 @@ -29,7 +29,7 @@ def __init__(self, url: str, credential: "AsyncTokenCredential" = None, **kwargs # When a pre-built pipeline is provided, skip the generated credential/policy setup. _endpoint = "{url}" self._config = QueuesClientConfiguration.__new__(QueuesClientConfiguration) - version = kwargs.pop("version", "2026-04-06") + version = kwargs.pop("version", "2026-06-06") self._config.url = url self._config.credential = credential self._config.version = version From 63c6f4fecf523a7c6cca9514a4a698bc626607b0 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 13:17:33 -0700 Subject: [PATCH 032/102] pyproject updates --- sdk/storage/azure-storage-queue/pyproject.toml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index 99bedcc12c98..03e25174e0c7 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta" [project] name = "azure-storage-queue" authors = [ - { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, + { name = "Microsoft Corporation", email = "ascl@microsoft.com" }, ] description = "Microsoft Corporation Azure Storage Queue Client Library for Python" license = "MIT" @@ -34,11 +34,17 @@ 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" From 7473c90434360c3509619f464085207556d3b523 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 13:44:49 -0700 Subject: [PATCH 033/102] fix [] --- .../azure-storage-queue/azure/storage/queue/_queue_client.py | 2 +- .../azure/storage/queue/aio/_queue_client_async.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 31595548369c..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 @@ -501,7 +501,7 @@ def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An if s.access_policy else AccessPolicy() ) - for s in identifiers.items_property + for s in (identifiers.items_property or []) } if identifiers else {} 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 78b84869d577..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 @@ -516,7 +516,7 @@ async def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwar if s.access_policy else AccessPolicy() ) - for s in identifiers.items_property + for s in (identifiers.items_property or []) } if identifiers else {} From 9e70eb6ce9379428f80dc161e2a0cc36d919b478 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 13 Apr 2026 12:56:54 -0700 Subject: [PATCH 034/102] remove --- .../storage/queue/_generated/_metadata.json | 6 - .../queue/_generated/_utils/model_base.py | 219 +++++++++++++----- .../queue/_generated/apiview-properties.json | 64 ----- 3 files changed, 155 insertions(+), 134 deletions(-) delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_metadata.json delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/apiview-properties.json diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_metadata.json b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_metadata.json deleted file mode 100644 index 722c39b95657..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_metadata.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "apiVersion": "2026-04-06", - "apiVersions": { - "Storage.Queues": "2026-04-06" - } -} \ No newline at end of file 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 index a75a22adbb97..eef4e52ed1a0 100644 --- 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 @@ -600,57 +600,9 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: for rest_field in self._attr_to_rest_field.values() if rest_field._default is not _UNSET } - if args: # pylint: disable=too-many-nested-blocks + if args: if isinstance(args[0], ET.Element): - existed_attr_keys = [] - model_meta = getattr(self, "_xml", {}) - - 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 = prop_meta.get("ns", model_meta.get("ns", None)) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - if prop_meta.get("itemsName"): - xml_name = prop_meta.get("itemsName") - xml_ns = prop_meta.get("itemNs") - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = args[0].findall(xml_name) # pyright: ignore - if len(items) > 0: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if args[0].text is not None: - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = args[0].find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) - - # rest thing is additional properties - for e in args[0]: - if e.tag not in existed_attr_keys: - dict_to_pass[e.tag] = _convert_element(e) + 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()} @@ -669,6 +621,69 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> 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__) @@ -735,7 +750,7 @@ def _deserialize(cls, data, exist_discriminators): model_meta = getattr(cls, "_xml", {}) prop_meta = getattr(discriminator, "_xml", {}) xml_name = prop_meta.get("name", discriminator._rest_name) - xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) if xml_ns: xml_name = "{" + xml_ns + "}" + xml_name @@ -1208,6 +1223,56 @@ def serialize_xml(model: Model, exclude_readonly: bool = False) -> 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, @@ -1219,10 +1284,16 @@ def _get_element( # 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( - model_meta.get("name", o.__class__.__name__), + element_name, model_meta.get("prefix"), - model_meta.get("ns"), + _model_ns, ) readonly_props = [] @@ -1244,7 +1315,9 @@ def _get_element( # additional properties will not have rest field, use the wire name as xml name prop_meta = {"name": k} - # if no ns for prop, use model's + # 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") @@ -1256,12 +1329,7 @@ def _get_element( # text could only set on primitive type wrapped_element.text = _get_primitive_type_value(v) elif prop_meta.get("attribute", False): - xml_name = prop_meta.get("name", k) - if prop_meta.get("ns"): - ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore - xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore - # attribute should be primitive type - wrapped_element.set(xml_name, _get_primitive_type_value(v)) + _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)) @@ -1270,6 +1338,7 @@ def _get_element( 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( @@ -1277,7 +1346,7 @@ def _get_element( exclude_readonly, { "name": k, - "ns": parent_meta.get("ns") if parent_meta else None, + "ns": _dict_ns, "prefix": parent_meta.get("prefix") if parent_meta else None, }, ) @@ -1286,13 +1355,16 @@ def _get_element( # 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": parent_meta.get("itemsNs", parent_meta.get("ns")), + "ns": _items_ns, }, ) @@ -1304,8 +1376,9 @@ def _get_wrapped_element( 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.get("ns") if meta else None + 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)) @@ -1326,11 +1399,29 @@ def _get_primitive_type_value(v) -> str: 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: - ET.register_namespace(prefix, ns) + _safe_register_namespace(prefix, ns) if ns: return ET.Element("{" + ns + "}" + tag) return ET.Element(tag) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/apiview-properties.json b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/apiview-properties.json deleted file mode 100644 index 15d94ba57ec4..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/apiview-properties.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "CrossLanguagePackageId": "Storage.Queues", - "CrossLanguageDefinitionId": { - "azure.storage.queues.models.AccessPolicy": "Storage.Queues.AccessPolicy", - "azure.storage.queues.models.CorsRule": "Storage.Queues.CorsRule", - "azure.storage.queues.models.Error": "Storage.Queues.Error", - "azure.storage.queues.models.GeoReplication": "Storage.Queues.GeoReplication", - "azure.storage.queues.models.KeyInfo": "Storage.Queues.KeyInfo", - "azure.storage.queues.models.ListOfPeekedMessage": "Storage.Queues.ListOfPeekedMessage", - "azure.storage.queues.models.ListOfReceivedMessage": "Storage.Queues.ListOfReceivedMessage", - "azure.storage.queues.models.ListOfSentMessage": "Storage.Queues.ListOfSentMessage", - "azure.storage.queues.models.ListQueuesResponse": "Storage.Queues.ListQueuesResponse", - "azure.storage.queues.models.Logging": "Storage.Queues.Logging", - "azure.storage.queues.models.Metrics": "Storage.Queues.Metrics", - "azure.storage.queues.models.PeekedMessage": "Storage.Queues.PeekedMessage", - "azure.storage.queues.models.QueueItem": "Storage.Queues.QueueItem", - "azure.storage.queues.models.QueueMessage": "Storage.Queues.QueueMessage", - "azure.storage.queues.models.QueueServiceProperties": "Storage.Queues.QueueServiceProperties", - "azure.storage.queues.models.QueueServiceStats": "Storage.Queues.QueueServiceStats", - "azure.storage.queues.models.ReceivedMessage": "Storage.Queues.ReceivedMessage", - "azure.storage.queues.models.RetentionPolicy": "Storage.Queues.RetentionPolicy", - "azure.storage.queues.models.SentMessage": "Storage.Queues.SentMessage", - "azure.storage.queues.models.SignedIdentifier": "Storage.Queues.SignedIdentifier", - "azure.storage.queues.models.SignedIdentifiers": "Storage.Queues.SignedIdentifiers", - "azure.storage.queues.models.UserDelegationKey": "Storage.Queues.UserDelegationKey", - "azure.storage.queues.models.StorageErrorCode": "Storage.Queues.StorageErrorCode", - "azure.storage.queues.models.GeoReplicationStatusType": "Storage.Queues.GeoReplicationStatusType", - "azure.storage.queues.models.ListQueuesIncludeType": "Storage.Queues.ListQueuesIncludeType", - "azure.storage.queues.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", - "azure.storage.queues.aio.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", - "azure.storage.queues.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", - "azure.storage.queues.aio.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", - "azure.storage.queues.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", - "azure.storage.queues.aio.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", - "azure.storage.queues.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", - "azure.storage.queues.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", - "azure.storage.queues.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", - "azure.storage.queues.aio.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", - "azure.storage.queues.operations.QueueOperations.create": "Storage.Queues.Queue.create", - "azure.storage.queues.aio.operations.QueueOperations.create": "Storage.Queues.Queue.create", - "azure.storage.queues.operations.QueueOperations.get_metadata": "Storage.Queues.Queue.getMetadata", - "azure.storage.queues.aio.operations.QueueOperations.get_metadata": "Storage.Queues.Queue.getMetadata", - "azure.storage.queues.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", - "azure.storage.queues.aio.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", - "azure.storage.queues.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", - "azure.storage.queues.aio.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", - "azure.storage.queues.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", - "azure.storage.queues.aio.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", - "azure.storage.queues.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", - "azure.storage.queues.aio.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", - "azure.storage.queues.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", - "azure.storage.queues.aio.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", - "azure.storage.queues.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", - "azure.storage.queues.aio.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", - "azure.storage.queues.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", - "azure.storage.queues.aio.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", - "azure.storage.queues.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", - "azure.storage.queues.aio.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", - "azure.storage.queues.operations.QueueOperations.update": "Storage.Queues.Queue.update", - "azure.storage.queues.aio.operations.QueueOperations.update": "Storage.Queues.Queue.update", - "azure.storage.queues.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage", - "azure.storage.queues.aio.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage" - } -} \ No newline at end of file From 3541133dd33f6059e797bf6f6c4a76fff213257e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 14 Apr 2026 09:58:09 -0700 Subject: [PATCH 035/102] regen with new config --- sdk/storage/azure-storage-queue/MANIFEST.in | 3 +- .../apiview-properties.json | 118 +++++++++--------- .../azure/storage/queue/_generated/_client.py | 4 +- .../storage/queue/_generated/aio/_client.py | 4 +- .../_generated/aio/operations/_operations.py | 6 +- .../queue/_generated/models/_models.py | 4 +- .../_generated/operations/_operations.py | 6 +- .../azure/storage/queue/_version.py | 8 +- .../azure/storage/queue/py.typed | 1 + 9 files changed, 78 insertions(+), 76 deletions(-) diff --git a/sdk/storage/azure-storage-queue/MANIFEST.in b/sdk/storage/azure-storage-queue/MANIFEST.in index bae0431342c4..8e7ae2ff16fb 100644 --- a/sdk/storage/azure-storage-queue/MANIFEST.in +++ b/sdk/storage/azure-storage-queue/MANIFEST.in @@ -1,8 +1,7 @@ include *.md include LICENSE -include azure/storage/queue/_generated/py.typed +include azure/storage/queue/py.typed recursive-include tests *.py recursive-include samples *.py *.md include azure/__init__.py include azure/storage/__init__.py -include azure/storage/queue/__init__.py diff --git a/sdk/storage/azure-storage-queue/apiview-properties.json b/sdk/storage/azure-storage-queue/apiview-properties.json index 46775c913b7d..056dcf5fc299 100644 --- a/sdk/storage/azure-storage-queue/apiview-properties.json +++ b/sdk/storage/azure-storage-queue/apiview-properties.json @@ -1,64 +1,64 @@ { "CrossLanguagePackageId": "Storage.Queues", "CrossLanguageDefinitionId": { - "azure.storage.queue._generated.models.AccessPolicy": "Storage.Queues.AccessPolicy", - "azure.storage.queue._generated.models.CorsRule": "Storage.Queues.CorsRule", - "azure.storage.queue._generated.models.Error": "Storage.Queues.Error", - "azure.storage.queue._generated.models.GeoReplication": "Storage.Queues.GeoReplication", - "azure.storage.queue._generated.models.KeyInfo": "Storage.Queues.KeyInfo", - "azure.storage.queue._generated.models.ListOfSentMessage": "Storage.Queues.ListOfSentMessage", - "azure.storage.queue._generated.models.ListQueuesResponse": "Storage.Queues.ListQueuesResponse", - "azure.storage.queue._generated.models.Logging": "Storage.Queues.Logging", - "azure.storage.queue._generated.models.Metrics": "Storage.Queues.Metrics", - "azure.storage.queue._generated.models.PeekedMessage": "Storage.Queues.PeekedMessage", - "azure.storage.queue._generated.models.PeekedMessages": "Storage.Queues.PeekedMessages", - "azure.storage.queue._generated.models.QueueItem": "Storage.Queues.QueueItem", - "azure.storage.queue._generated.models.QueueMessage": "Storage.Queues.QueueMessage", - "azure.storage.queue._generated.models.QueueServiceProperties": "Storage.Queues.QueueServiceProperties", - "azure.storage.queue._generated.models.QueueServiceStats": "Storage.Queues.QueueServiceStats", - "azure.storage.queue._generated.models.ReceivedMessage": "Storage.Queues.ReceivedMessage", - "azure.storage.queue._generated.models.ReceivedMessages": "Storage.Queues.ReceivedMessages", - "azure.storage.queue._generated.models.RetentionPolicy": "Storage.Queues.RetentionPolicy", - "azure.storage.queue._generated.models.SentMessage": "Storage.Queues.SentMessage", - "azure.storage.queue._generated.models.SignedIdentifier": "Storage.Queues.SignedIdentifier", - "azure.storage.queue._generated.models.SignedIdentifiers": "Storage.Queues.SignedIdentifiers", - "azure.storage.queue._generated.models.UserDelegationKey": "Storage.Queues.UserDelegationKey", - "azure.storage.queue._generated.models.StorageErrorCode": "Storage.Queues.StorageErrorCode", - "azure.storage.queue._generated.models.GeoReplicationStatus": "Storage.Queues.GeoReplicationStatus", - "azure.storage.queue._generated.models.ListQueuesIncludeType": "Storage.Queues.ListQueuesIncludeType", - "azure.storage.queue._generated.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", - "azure.storage.queue._generated.aio.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", - "azure.storage.queue._generated.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", - "azure.storage.queue._generated.aio.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", - "azure.storage.queue._generated.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", - "azure.storage.queue._generated.aio.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", - "azure.storage.queue._generated.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", - "azure.storage.queue._generated.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", - "azure.storage.queue._generated.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", - "azure.storage.queue._generated.aio.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", - "azure.storage.queue._generated.operations.QueueOperations.create": "Storage.Queues.Queue.create", - "azure.storage.queue._generated.aio.operations.QueueOperations.create": "Storage.Queues.Queue.create", - "azure.storage.queue._generated.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", - "azure.storage.queue._generated.aio.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", - "azure.storage.queue._generated.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", - "azure.storage.queue._generated.aio.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", - "azure.storage.queue._generated.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", - "azure.storage.queue._generated.aio.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", - "azure.storage.queue._generated.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", - "azure.storage.queue._generated.aio.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", - "azure.storage.queue._generated.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", - "azure.storage.queue._generated.aio.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", - "azure.storage.queue._generated.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", - "azure.storage.queue._generated.aio.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", - "azure.storage.queue._generated.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", - "azure.storage.queue._generated.aio.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", - "azure.storage.queue._generated.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", - "azure.storage.queue._generated.aio.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", - "azure.storage.queue._generated.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", - "azure.storage.queue._generated.aio.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", - "azure.storage.queue._generated.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", - "azure.storage.queue._generated.aio.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", - "azure.storage.queue._generated.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage", - "azure.storage.queue._generated.aio.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage" + "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/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py index 07be44526bb6..2335c04700ae 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py @@ -26,9 +26,9 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword """QueuesClient. :ivar service: ServiceOperations operations - :vartype service: azure.storage.queue._generated.operations.ServiceOperations + :vartype service: azure.storage.queue.operations.ServiceOperations :ivar queue: QueueOperations operations - :vartype queue: azure.storage.queue._generated.operations.QueueOperations + :vartype queue: azure.storage.queue.operations.QueueOperations :param url: The host name of the queue storage account, e.g. accountName.queue.core.windows.net. Required. :type url: str diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py index f049fcf84d9e..5ed74d3735ac 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py @@ -26,9 +26,9 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword """QueuesClient. :ivar service: ServiceOperations operations - :vartype service: azure.storage.queue._generated.aio.operations.ServiceOperations + :vartype service: azure.storage.queue.aio.operations.ServiceOperations :ivar queue: QueueOperations operations - :vartype queue: azure.storage.queue._generated.aio.operations.QueueOperations + :vartype queue: azure.storage.queue.aio.operations.QueueOperations :param url: The host name of the queue storage account, e.g. accountName.queue.core.windows.net. Required. :type url: str diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py index e13258c997cc..92e70415b9c1 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py @@ -59,7 +59,7 @@ class ServiceOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queue._generated.aio.QueuesClient`'s + :class:`~azure.storage.queue.aio.QueuesClient`'s :attr:`service` attribute. """ @@ -416,7 +416,7 @@ async def get_queues( :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._generated.models.ListQueuesIncludeType] + :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: @@ -496,7 +496,7 @@ class QueueOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queue._generated.aio.QueuesClient`'s + :class:`~azure.storage.queue.aio.QueuesClient`'s :attr:`queue` attribute. """ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 615153e30084..6299dcda18a7 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -160,7 +160,7 @@ class Error(_Model): "AuthorizationProtocolMismatch", "AuthorizationPermissionMismatch", "AuthorizationServiceMismatch", "AuthorizationResourceTypeMismatch", and "FeatureVersionMismatch". - :vartype code: str or ~azure.storage.queue._generated.models.StorageErrorCode + :vartype code: str or ~azure.storage.queue.models.StorageErrorCode :ivar message: The error message. :vartype message: str """ @@ -220,7 +220,7 @@ class GeoReplication(_Model): :ivar status: The status of the secondary location. Required. Known values are: "live", "bootstrap", and "unavailable". - :vartype status: str or ~azure.storage.queue._generated.models.GeoReplicationStatus + :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. diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py index 3cac2fcbf9cd..da60650623ab 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py @@ -452,7 +452,7 @@ class ServiceOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queue._generated.QueuesClient`'s + :class:`~azure.storage.queue.QueuesClient`'s :attr:`service` attribute. """ @@ -809,7 +809,7 @@ def get_queues( :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._generated.models.ListQueuesIncludeType] + :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: @@ -889,7 +889,7 @@ class QueueOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.queue._generated.QueuesClient`'s + :class:`~azure.storage.queue.QueuesClient`'s :attr:`queue` attribute. """ 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..be71c81bd282 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" +VERSION = "1.0.0b1" 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 From eaa221542171efc72d6228852185ef0647143031 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 14 Apr 2026 10:27:33 -0700 Subject: [PATCH 036/102] version --- sdk/storage/azure-storage-queue/azure/storage/queue/_version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 be71c81bd282..195162b92aac 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b1" +VERSION = "12.18.0b1" From 3a18e327c901230a4657accfc41b247e84e745ed Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 16 Apr 2026 10:03:26 -0700 Subject: [PATCH 037/102] update models patch --- .../storage/queue/_generated/models/_patch.py | 90 +----------------- .../azure/storage/queue/_models.py | 94 ++++++------------- 2 files changed, 28 insertions(+), 156 deletions(-) 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 607f97c89a47..fa89e3a07c9a 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 @@ -8,95 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import datetime -from typing import List, Optional - -from .._utils.model_base import Model as _Model, rest_field, _MyMutableMapping, _RestField - - -def _patched_getattr(self, name): - """Lazily initialize _data for subclasses that skip super().__init__().""" - if name == "_data": - object.__setattr__(self, "_data", {}) - return self._data - raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") - - -def _patched_setattr(self, name, value): - """Route attribute writes through _RestField descriptors even when shadowed.""" - if not name.startswith("_"): - try: - rf = type(self)._attr_to_rest_field.get(name) - except AttributeError: - pass - else: - if rf is not None: - rf.__set__(self, value) - return - object.__setattr__(self, name, value) - - -def _patched_getattribute(self, name): - """Route attribute reads through _RestField descriptors even when shadowed.""" - if not name.startswith("_"): - try: - rest_fields = type(self)._attr_to_rest_field - except AttributeError: - pass - else: - rf = rest_fields.get(name) - if rf is not None: - return rf.__get__(self, type(self)) - return object.__getattribute__(self, name) - - -# The original ``Model.__new__`` does ``rf._module = cls.__module__`` which -# lets an external subclass (e.g. from azure-storage-file-datalake) overwrite -# ``_module`` on the *shared* descriptor, corrupting type resolution for -# every class that shares it. This replacement resolves forward references -# against the module that *defined* the rest_field and uses that class's own -# annotations (not merged subclass annotations) to avoid resolving to a type -# whose ``__init__`` can't handle XML elements. - - -def _patched_new(cls, *args, **kwargs): - if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: - # Walk only user-defined classes (base-first), stopping before the - # framework base. Each _RestField is configured with the module of - # the class that defined it so forward references resolve correctly. - user_classes = [] - for c in cls.__mro__: - if c is _Model: - break - user_classes.append(c) - - attr_to_rest_field: dict[str, _RestField] = {} - for mro_class in reversed(user_classes): - annotations = getattr(mro_class, "__annotations__", {}) - for k, v in mro_class.__dict__.items(): - if not k.startswith("_") and isinstance(v, _RestField): - attr_to_rest_field[k] = v - v._module = mro_class.__module__ - if not v._type: - v._type = v._get_deserialize_callable_from_annotation(annotations.get(k, None)) - if not v._rest_name_input: - v._rest_name_input = k - - cls._attr_to_rest_field = attr_to_rest_field - cls._backcompat_attr_to_rest_field = { - _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 object.__new__(cls) - - -_MyMutableMapping.__getattr__ = _patched_getattr -_MyMutableMapping.__setattr__ = _patched_setattr -_MyMutableMapping.__getattribute__ = _patched_getattribute -_Model.__new__ = _patched_new - +from typing import List __all__: List[str] = [] 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 9e669af46c6e..e9aeec99b1f7 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,23 +306,17 @@ 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.""" - def __init__( self, permission: Optional[Union[QueueSasPermissions, str]] = None, 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): From 8afa3a599789ad12d2bffacab92791ccbdc5854a Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 16 Apr 2026 10:38:18 -0700 Subject: [PATCH 038/102] updating client patches --- .../azure/storage/queue/_generated/_patch.py | 51 ++++++++++++++----- .../storage/queue/_generated/aio/_patch.py | 49 ++++++++++++++---- 2 files changed, 76 insertions(+), 24 deletions(-) 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 428f6d049aec..c6d02d38e03e 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 @@ -7,33 +7,58 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING from azure.core import PipelineClient -from ._configuration import QueuesClientConfiguration +from ._configuration import QueuesClientConfiguration as QueuesClientConfigurationInternal from ._utils.serialization import Deserializer, Serializer from .operations import QueueOperations, ServiceOperations -from ._client import QueuesClient as _QueuesClient +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. -class QueuesClient(_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: "TokenCredential" = None, **kwargs: Any) -> None: + def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **kwargs: Any) -> None: _pipeline = kwargs.pop("pipeline", None) if _pipeline is not None: - # When a pre-built pipeline is provided, skip the generated credential/policy setup. - _endpoint = "{url}" - self._config = QueuesClientConfiguration.__new__(QueuesClientConfiguration) - version = kwargs.pop("version", "2026-06-06") - self._config.url = url - self._config.credential = credential - self._config.version = version - self._client: PipelineClient = PipelineClient(base_url=_endpoint, pipeline=_pipeline) + 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 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 bfd8573716c5..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 @@ -7,11 +7,12 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING from azure.core import AsyncPipelineClient -from .._configuration import QueuesClientConfiguration +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 @@ -20,20 +21,46 @@ 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: "AsyncTokenCredential" = None, **kwargs: Any) -> None: + def __init__(self, url: str, credential: Optional["AsyncTokenCredential"] = None, **kwargs: Any) -> None: _pipeline = kwargs.pop("pipeline", None) if _pipeline is not None: - # When a pre-built pipeline is provided, skip the generated credential/policy setup. - _endpoint = "{url}" - self._config = QueuesClientConfiguration.__new__(QueuesClientConfiguration) - version = kwargs.pop("version", "2026-06-06") - self._config.url = url - self._config.credential = credential - self._config.version = version - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, pipeline=_pipeline) + 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 From 9bfdf7427b5594999f506db57d977a49668d9754 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 16 Apr 2026 13:14:21 -0700 Subject: [PATCH 039/102] blob shared folder spread --- .../storage/queue/_shared/authentication.py | 15 +--- .../storage/queue/_shared/base_client.py | 83 +++---------------- .../queue/_shared/base_client_async.py | 68 ++------------- .../azure/storage/queue/_shared/constants.py | 5 +- .../azure/storage/queue/_shared/models.py | 11 +-- .../azure/storage/queue/_shared/parser.py | 5 +- .../azure/storage/queue/_shared/policies.py | 40 ++------- .../storage/queue/_shared/policies_async.py | 28 ++----- .../storage/queue/_shared/request_handlers.py | 1 + .../queue/_shared/response_handlers.py | 26 ++---- .../queue/_shared/shared_access_signature.py | 31 +++---- .../azure/storage/queue/_shared/uploads.py | 33 +++----- .../storage/queue/_shared/uploads_async.py | 29 +++---- 13 files changed, 81 insertions(+), 294 deletions(-) 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 54446f7fc5b4..400f7d6f6dff 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 @@ -41,18 +41,12 @@ StorageHosts, StorageRequestHook, ) -from .policies_async import ( - AsyncStorageBearerTokenCredentialPolicy, - AsyncStorageResponseHook, -) +from .policies_async import AsyncStorageBearerTokenCredentialPolicy, AsyncStorageResponseHook from .response_handlers import PartialBatchErrorException, process_storage_error 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 +63,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 +89,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 +198,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 +217,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..23786baef24b 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 @@ -316,7 +313,7 @@ def from_string(cls, string): :param str string: Specify service, container, or object in in the string with the first letter of the word. :return: A ResourceTypes object - :rtype: ~azure.storage.queue.ResourceTypes + :rtype: ~azure.storage.blob.ResourceTypes """ res_service = "s" in string res_container = "c" in string @@ -440,7 +437,7 @@ def from_string(cls, permission): :param str permission: Specify permissions in the string with the first letter of the word. :return: An AccountSasPermissions object - :rtype: ~azure.storage.queue.AccountSasPermissions + :rtype: ~azure.storage.blob.AccountSasPermissions """ p_read = "r" in permission p_write = "w" in permission @@ -505,7 +502,7 @@ def from_string(cls, string): :param str string: Specify blob, queue, or file in in the string with the first letter of the word. :return: A Services object - :rtype: ~azure.storage.queue.Services + :rtype: ~azure.storage.blob.Services """ res_blob = "b" in string res_queue = "q" in string 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 0127d571f003..abb8c8ff9e7d 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 @@ -55,12 +55,7 @@ def encode_base64(data): # 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 @@ -126,12 +121,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) @@ -233,16 +222,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:") @@ -586,16 +566,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 @@ -605,12 +580,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 f4d235c082d8..4cb32f23248b 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,19 +11,11 @@ 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 -from .policies import ( - encode_base64, - is_retry, - StorageContentValidation, - StorageRetryPolicy, -) +from .policies import encode_base64, is_retry, StorageContentValidation, StorageRetryPolicy if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential @@ -133,16 +125,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 @@ -152,12 +139,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 11d8a2cc391b..1d271a20a66b 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 @@ -22,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__) @@ -80,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 @@ -99,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") @@ -126,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)} @@ -144,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, 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 From 19e13ba13a5b9ba46f767c3a2c37614daa96858e Mon Sep 17 00:00:00 2001 From: l0lawrence Date: Thu, 16 Apr 2026 13:24:57 -0700 Subject: [PATCH 040/102] Fix azure.storage.blob rtype references to azure.storage.queue in queue _shared/models.py Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/storage/queue/_shared/models.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 23786baef24b..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 @@ -313,7 +313,7 @@ def from_string(cls, string): :param str string: Specify service, container, or object in in the string with the first letter of the word. :return: A ResourceTypes object - :rtype: ~azure.storage.blob.ResourceTypes + :rtype: ~azure.storage.queue.ResourceTypes """ res_service = "s" in string res_container = "c" in string @@ -437,7 +437,7 @@ def from_string(cls, permission): :param str permission: Specify permissions in the string with the first letter of the word. :return: An AccountSasPermissions object - :rtype: ~azure.storage.blob.AccountSasPermissions + :rtype: ~azure.storage.queue.AccountSasPermissions """ p_read = "r" in permission p_write = "w" in permission @@ -502,7 +502,7 @@ def from_string(cls, string): :param str string: Specify blob, queue, or file in in the string with the first letter of the word. :return: A Services object - :rtype: ~azure.storage.blob.Services + :rtype: ~azure.storage.queue.Services """ res_blob = "b" in string res_queue = "q" in string From b16013dc59b33cd99a9dc2598fff8e63d125c30e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 16 Apr 2026 14:24:29 -0700 Subject: [PATCH 041/102] model update --- .../azure-storage-queue/azure/storage/queue/_models.py | 4 ++++ 1 file changed, 4 insertions(+) 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 e9aeec99b1f7..acb38ebc8caf 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -306,6 +306,10 @@ class AccessPolicy(GenAccessPolicy): be interpreted as UTC. """ + 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, permission: Optional[Union[QueueSasPermissions, str]] = None, From 238c30fb0314172e3e41de351dbaf758fd896686 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 16 Apr 2026 14:56:32 -0700 Subject: [PATCH 042/102] black --- .../azure/storage/queue/_generated/_patch.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 c6d02d38e03e..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 @@ -20,6 +20,7 @@ if TYPE_CHECKING: from azure.core.credentials import TokenCredential + class QueuesClientConfiguration(QueuesClientConfigurationInternal): """Configuration for QueuesClient. @@ -42,7 +43,7 @@ def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **k if url is None: raise ValueError("Parameter 'url' must not be None.") - + self.url = url self.credential = credential self.version = version @@ -51,6 +52,7 @@ def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **k self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) + class QueuesClient(QueuesClientInternal): """QueuesClient that supports being instantiated with a pre-built pipeline.""" From b8fdfdd280205a2b35edfc1e95e5df034d554a7a Mon Sep 17 00:00:00 2001 From: l0lawrence Date: Fri, 1 May 2026 11:19:43 -0700 Subject: [PATCH 043/102] wip changes from running against azure cli Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../storage/queue/_generated/models/_patch.py | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) 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 fa89e3a07c9a..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 @@ -8,11 +8,56 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +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 + + +_Model._asdict = _patched_namedtuple_asdict + + def patch_sdk(): """Do not remove from this file. From 06ba19afcdc4d93075b8fba6c87329a3bcbbb653 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 5 May 2026 12:51:11 -0700 Subject: [PATCH 044/102] regen --- .../storage/queue/_generated/_version.py | 2 +- .../_generated/aio/operations/_operations.py | 171 ++++++++++-------- .../storage/queue/_generated/models/_enums.py | 6 +- .../queue/_generated/models/_models.py | 143 ++++++++------- .../_generated/operations/_operations.py | 171 ++++++++++-------- 5 files changed, 258 insertions(+), 235 deletions(-) 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 index be71c81bd282..195162b92aac 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b1" +VERSION = "12.18.0b1" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py index 92e70415b9c1..38ad71ea05bd 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_operations.py @@ -79,7 +79,8 @@ async def set_properties( :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 @@ -147,7 +148,8 @@ async def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) """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 @@ -225,7 +227,8 @@ async def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) 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 @@ -306,7 +309,8 @@ async def get_user_delegation_key( :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 @@ -394,28 +398,29 @@ async def get_queues( include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, **kwargs: Any ) -> _models.ListQueuesResponse: - """returns a list of the queues under the specified account. + """Returns a list of queues. :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. + :keyword marker: Identifies the portion of the list of queues to be returned with the next + listing operation. The operation + returns the marker value if the listing operation did not return all queues remaining. The + marker 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. + 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. + :keyword include: Specify to include additional, optional information. 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 @@ -509,11 +514,11 @@ def __init__(self, *args, **kwargs) -> None: @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. + """Creates a new queue. If a queue with the same name already exists, the operation succeeds when + the metadata is identical. If the metadata differs, the operation fails. - :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 @@ -576,9 +581,10 @@ async def create(self, *, timeout: Optional[int] = None, metadata: Optional[str] @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. + """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 @@ -642,9 +648,10 @@ async def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) @distributed_trace_async async def delete(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: - """operation permanently deletes the specified queue. + """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 @@ -706,9 +713,10 @@ async def delete(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: 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. + """Sets user-defined metadata 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 @@ -771,10 +779,10 @@ async def set_metadata( @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. + """Gets the access policy 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 @@ -850,11 +858,12 @@ async def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An 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. + """Sets the permissions for the specified queue. - :param queue_acl: The access control list for the queue. Default value is None. + :param queue_acl: The access control list. 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 @@ -930,21 +939,21 @@ async def receive_messages( timeout: Optional[int] = None, **kwargs: Any ) -> _models.ReceivedMessages: - """The Dequeue operation retrieves one or more messages from the front of the queue. + """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 + :keyword number_of_messages: 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. + to server time. A specified value must be + larger than or equal to 1 second, and cannot be larger than 7 days. 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 @@ -1020,9 +1029,10 @@ async def receive_messages( @distributed_trace_async async def clear(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: - """The Clear operation deletes all messages from the specified queue. + """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 @@ -1090,28 +1100,27 @@ async def send_message( 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. + """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. - :param queue_message: A Message object which can be stored in a Queue. Required. + :param queue_message: The queue message. The 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. 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. + to server time. A specified value must be + larger than or equal to 1 second, and cannot be larger than 7 days. 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. + :keyword message_time_to_live: 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 @@ -1194,16 +1203,16 @@ async def send_message( 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. + """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 + :keyword number_of_messages: 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 @@ -1287,26 +1296,28 @@ async def update_message( 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. + """Updates the visibility timeout of a message. This operation can also be used to update the + contents of a message. - :param message_id: The id of the queue message. Required. + :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. + :param queue_message: The queue message. The 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. 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. + :keyword pop_receipt: An opaque value 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 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. + to server time. A specified value must be + larger than or equal to 1 second, and cannot be larger than 7 days. 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 @@ -1384,14 +1395,16 @@ async def update_message( 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. + """Deletes the specified message. - :param message_id: The id of the queue message. Required. + :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. + :keyword pop_receipt: An opaque value 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 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 diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py index 59eeda9aed3e..05daf42fe207 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_enums.py @@ -22,12 +22,10 @@ class GeoReplicationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): class ListQueuesIncludeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Include this parameter to specify that the queue's metadata be returned as part of the response - body. - """ + """Specify to include additional, optional information.""" METADATA = "metadata" - """Include metadata.""" + """Include queue metadata.""" class StorageErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 6299dcda18a7..21f2e26e9769 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -18,13 +18,13 @@ class AccessPolicy(_Model): - """Represents an access policy. + """The 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 acl the policy. + :ivar permission: The permissions for the policy. :vartype permission: str """ @@ -42,7 +42,7 @@ class AccessPolicy(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Permission", "text": False, "unwrapped": False}, ) - """The permissions for acl the policy.""" + """The permissions for the policy.""" _xml = {"attribute": False, "name": "AccessPolicy", "text": False, "unwrapped": False} @@ -67,10 +67,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: 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. + """The CORS rules. :ivar allowed_origins: The allowed origins. Required. :vartype allowed_origins: str @@ -216,7 +213,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class GeoReplication(_Model): - """Geo-Replication information for the Secondary Storage Service. + """Geo replication information for the secondary storage location. :ivar status: The status of the secondary location. Required. Known values are: "live", "bootstrap", and "unavailable". @@ -271,7 +268,7 @@ class KeyInfo(_Model): :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. + :ivar delegated_user_tid: The delegated user tenant ID in Entra ID. :vartype delegated_user_tid: str """ @@ -290,7 +287,7 @@ class KeyInfo(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "DelegatedUserTid", "text": False, "unwrapped": False}, ) - """The delegated user tenant id in Azure AD.""" + """The delegated user tenant ID in Entra ID.""" _xml = {"attribute": False, "name": "KeyInfo", "text": False, "unwrapped": False} @@ -315,9 +312,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class ListOfSentMessage(_Model): - """List wrapper for EnqueuedMessage array. + """The response of send message. - :ivar items_property: The list of enqueued messages. Required. + :ivar items_property: The list of sent messages. Required. :vartype items_property: ~azure.storage.queue._generated.models.SentMessage """ @@ -327,7 +324,7 @@ class ListOfSentMessage(_Model): xml={"attribute": False, "itemsName": "QueueMessage", "name": "QueueMessage", "text": False, "unwrapped": True}, original_tsp_name="items", ) - """The list of enqueued messages. Required.""" + """The list of sent messages. Required.""" _xml = {"attribute": False, "name": "QueueMessagesList", "text": False, "unwrapped": False} @@ -350,19 +347,20 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class ListQueuesResponse(_Model): - """The list queue segment response. + """The list queues 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. + :ivar marker: Identifies the current position in the list queues operation. :vartype marker: str - :ivar max_results: The max results of the queues. Required. + :ivar max_results: The max results. Required. :vartype max_results: int - :ivar queue_items: The queue segment. + :ivar queue_items: The list of queues. :vartype queue_items: ~azure.storage.queue._generated.models.QueueItem - :ivar next_marker: The next marker of the queues. Required. + :ivar next_marker: Identifies the portion of the list of queues to be returned with the next + listing operation. Required. :vartype next_marker: str """ @@ -381,25 +379,26 @@ class ListQueuesResponse(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Marker", "text": False, "unwrapped": False}, ) - """The marker of the queues.""" + """Identifies the current position in the list queues operation.""" 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.""" + """The max results. 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.""" + """The list of queues.""" 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.""" + """Identifies the portion of the list of queues to be returned with the next listing operation. + Required.""" _xml = {"attribute": False, "name": "EnumerationResults", "text": False, "unwrapped": False} @@ -552,18 +551,18 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class PeekedMessage(_Model): - """The object returned in the QueueMessageList array when calling Peek Messages on a Queue. + """The peeked queue message. - :ivar message_id: The Id of the Message. Required. + :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. + :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. + :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. + :ivar message_text: The content of the message. Required. :vartype message_text: str """ @@ -572,21 +571,21 @@ class PeekedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, ) - """The Id of the Message. Required.""" + """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.""" + """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.""" + """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"], @@ -598,7 +597,7 @@ class PeekedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageText", "text": False, "unwrapped": False}, ) - """The content of the Message. Required.""" + """The content of the message. Required.""" _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} @@ -625,7 +624,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class PeekedMessages(_Model): - """List wrapper for PeekedMessageItem array. + """The response of peek messages. :ivar items_property: The list of peeked messages. Required. :vartype items_property: ~azure.storage.queue._generated.models.PeekedMessage @@ -664,7 +663,7 @@ class QueueItem(_Model): :ivar name: The name of the queue. Required. :vartype name: str - :ivar metadata: The metadata of the container. + :ivar metadata: The metadata of the queue. :vartype metadata: dict[str, str] """ @@ -677,7 +676,7 @@ class QueueItem(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Metadata", "text": False, "unwrapped": False}, ) - """The metadata of the container.""" + """The metadata of the queue.""" _xml = {"attribute": False, "name": "Queue", "text": False, "unwrapped": False} @@ -701,7 +700,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class QueueMessage(_Model): - """A Message object which can be stored in a Queue. + """The queue message. :ivar message_text: The content of the message. Required. :vartype message_text: str @@ -794,7 +793,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class QueueServiceStats(_Model): - """Stats for the storage service. + """Statistics for the storage queue service. :ivar geo_replication: The geo replication stats. :vartype geo_replication: ~azure.storage.queue._generated.models.GeoReplication @@ -828,19 +827,19 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class ReceivedMessage(_Model): - """The object returned in the QueueMessageList array when calling Get Messages on a Queue. + """The received queue message. - :ivar message_id: The Id of the Message. Required. + :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. + :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. + :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 + :ivar pop_receipt: An opaque value 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. + :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. @@ -854,35 +853,35 @@ class ReceivedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, ) - """The Id of the Message. Required.""" + """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.""" + """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.""" + """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.""" + """An opaque value 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.""" + """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"], @@ -923,9 +922,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class ReceivedMessages(_Model): - """List wrapper for DequeuedMessageItem array. + """The response of receive messages. - :ivar items_property: The list of dequeued messages. Required. + :ivar items_property: The list of received messages. Required. :vartype items_property: ~azure.storage.queue._generated.models.ReceivedMessage """ @@ -935,7 +934,7 @@ class ReceivedMessages(_Model): xml={"attribute": False, "itemsName": "QueueMessage", "name": "QueueMessage", "text": False, "unwrapped": True}, original_tsp_name="items", ) - """The list of dequeued messages. Required.""" + """The list of received messages. Required.""" _xml = {"attribute": False, "name": "QueueMessagesList", "text": False, "unwrapped": False} @@ -999,19 +998,19 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class SentMessage(_Model): - """The object returned in the QueueMessageList array when calling Put Message on a Queue. + """The sent queue message. - :ivar message_id: The Id of the Message. Required. + :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. + :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. + :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 + :ivar pop_receipt: An opaque value 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. + :ivar time_next_visible: The time that the message will again become visible in the queue. Required. :vartype time_next_visible: ~datetime.datetime """ @@ -1021,35 +1020,35 @@ class SentMessage(_Model): visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, ) - """The Id of the Message. Required.""" + """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.""" + """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.""" + """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.""" + """An opaque value 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.""" + """The time that the message will again become visible in the queue. Required.""" _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} @@ -1118,7 +1117,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class SignedIdentifiers(_Model): - """Represents an array of signed identifiers. + """An array of signed identifiers. :ivar items_property: The list of signed identifiers. Required. :vartype items_property: ~azure.storage.queue._generated.models.SignedIdentifier @@ -1161,9 +1160,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class UserDelegationKey(_Model): """A user delegation key. - :ivar signed_oid: The Azure Active Directory object ID in GUID format. Required. + :ivar signed_oid: The Entra ID object ID in GUID format. Required. :vartype signed_oid: str - :ivar signed_tid: The Azure Active Directory tenant ID in GUID format. Required. + :ivar signed_tid: The Entra ID 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 @@ -1171,9 +1170,9 @@ class UserDelegationKey(_Model): :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. + :ivar signed_version: The service version used when creating the key. Required. :vartype signed_version: str - :ivar signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if + :ivar signed_delegated_user_tid: The delegated user tenant ID in Entra ID. Return if DelegatedUserTid is specified. :vartype signed_delegated_user_tid: str :ivar value: The key as a base64 string. Required. @@ -1185,13 +1184,13 @@ class UserDelegationKey(_Model): 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.""" + """The Entra ID 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.""" + """The Entra ID tenant ID in GUID format. Required.""" signed_start: str = rest_field( name="signedStart", visibility=["read", "create", "update", "delete", "query"], @@ -1215,13 +1214,13 @@ class UserDelegationKey(_Model): 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.""" + """The service version used when creating 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.""" + """The delegated user tenant ID in Entra ID. Return if DelegatedUserTid is specified.""" value: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Value", "text": False, "unwrapped": False}, diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py index da60650623ab..31d7f854cd9f 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_operations.py @@ -472,7 +472,8 @@ def set_properties( # pylint: disable=inconsistent-return-statements :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 @@ -540,7 +541,8 @@ def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _mo """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 @@ -618,7 +620,8 @@ def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _mo 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 @@ -699,7 +702,8 @@ def get_user_delegation_key( :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 @@ -787,28 +791,29 @@ def get_queues( include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, **kwargs: Any ) -> _models.ListQueuesResponse: - """returns a list of the queues under the specified account. + """Returns a list of queues. :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. + :keyword marker: Identifies the portion of the list of queues to be returned with the next + listing operation. The operation + returns the marker value if the listing operation did not return all queues remaining. The + marker 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. + 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. + :keyword include: Specify to include additional, optional information. 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 @@ -904,11 +909,11 @@ def __init__(self, *args, **kwargs) -> None: 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. + """Creates a new queue. If a queue with the same name already exists, the operation succeeds when + the metadata is identical. If the metadata differs, the operation fails. - :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 @@ -973,9 +978,10 @@ def create( # pylint: disable=inconsistent-return-statements 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. + """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 @@ -1041,9 +1047,10 @@ def get_properties( # pylint: disable=inconsistent-return-statements def delete( # pylint: disable=inconsistent-return-statements self, *, timeout: Optional[int] = None, **kwargs: Any ) -> None: - """operation permanently deletes the specified queue. + """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 @@ -1105,9 +1112,10 @@ def delete( # pylint: disable=inconsistent-return-statements 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. + """Sets user-defined metadata 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 @@ -1170,10 +1178,10 @@ def set_metadata( # pylint: disable=inconsistent-return-statements @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. + """Gets the access policy 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 @@ -1249,11 +1257,12 @@ def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: Any) -> 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. + """Sets the permissions for the specified queue. - :param queue_acl: The access control list for the queue. Default value is None. + :param queue_acl: The access control list. 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 @@ -1329,21 +1338,21 @@ def receive_messages( timeout: Optional[int] = None, **kwargs: Any ) -> _models.ReceivedMessages: - """The Dequeue operation retrieves one or more messages from the front of the queue. + """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 + :keyword number_of_messages: 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. + to server time. A specified value must be + larger than or equal to 1 second, and cannot be larger than 7 days. 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 @@ -1421,9 +1430,10 @@ def receive_messages( 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. + """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 @@ -1491,28 +1501,27 @@ def send_message( 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. + """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. - :param queue_message: A Message object which can be stored in a Queue. Required. + :param queue_message: The queue message. The 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. 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. + to server time. A specified value must be + larger than or equal to 1 second, and cannot be larger than 7 days. 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. + :keyword message_time_to_live: 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 @@ -1595,16 +1604,16 @@ def send_message( 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. + """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 + :keyword number_of_messages: 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 @@ -1688,26 +1697,28 @@ def update_message( # pylint: disable=inconsistent-return-statements 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. + """Updates the visibility timeout of a message. This operation can also be used to update the + contents of a message. - :param message_id: The id of the queue message. Required. + :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. + :param queue_message: The queue message. The 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. 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. + :keyword pop_receipt: An opaque value 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 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. + to server time. A specified value must be + larger than or equal to 1 second, and cannot be larger than 7 days. 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 @@ -1785,14 +1796,16 @@ def update_message( # pylint: disable=inconsistent-return-statements 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. + """Deletes the specified message. - :param message_id: The id of the queue message. Required. + :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. + :keyword pop_receipt: An opaque value 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 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 From d2264739116277dc74260db12293fd9d53b66eef Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 6 May 2026 09:31:00 -0700 Subject: [PATCH 045/102] backcompat patch all model attr from autorest* --- .../storage/queue/_generated/models/_patch.py | 222 +++++++++++++++++- .../azure/storage/queue/_models.py | 77 ++++-- 2 files changed, 273 insertions(+), 26 deletions(-) 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 c414d071566a..c4fb4ca7742e 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 @@ -8,11 +8,222 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, List +import xml.etree.ElementTree as ET +from typing import Any, Callable, List, Optional -from .._utils.model_base import Model as _Model, _MyMutableMapping +from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize -__all__: List[str] = [] + +def _patched_getattr(self, name): + """Lazily initialize _data for subclasses that skip super().__init__().""" + if name == "_data": + object.__setattr__(self, "_data", {}) + return self._data + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + +def _patched_setattr(self, name, value): + """Route attribute writes through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + try: + rf = type(self)._attr_to_rest_field.get(name) + except AttributeError: + pass + else: + if rf is not None: + rf.__set__(self, value) + return + object.__setattr__(self, name, value) + + +def _patched_getattribute(self, name): + """Route attribute reads through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + try: + rest_fields = type(self)._attr_to_rest_field + except AttributeError: + pass + else: + rf = rest_fields.get(name) + if rf is not None: + return rf.__get__(self, type(self)) + return object.__getattribute__(self, name) + + +# The original ``Model.__new__`` does ``rf._module = cls.__module__`` which +# lets an external subclass (e.g. from azure-storage-file-datalake) overwrite +# ``_module`` on the *shared* descriptor, corrupting type resolution for +# every class that shares it. This replacement resolves forward references +# against the module that *defined* the rest_field and uses that class's own +# annotations (not merged subclass annotations) to avoid resolving to a type +# whose ``__init__`` can't handle XML elements. + + +def _patched_new(cls, *args, **kwargs): + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # Walk only user-defined classes (base-first), stopping before the + # framework base. Each _RestField is configured with the module of + # the class that defined it so forward references resolve correctly. + user_classes = [] + for c in cls.__mro__: + if c is _Model: + break + user_classes.append(c) + + attr_to_rest_field: dict[str, _RestField] = {} + for mro_class in reversed(user_classes): + annotations = getattr(mro_class, "__annotations__", {}) + for k, v in mro_class.__dict__.items(): + if not k.startswith("_") and isinstance(v, _RestField): + attr_to_rest_field[k] = v + v._module = mro_class.__module__ + if not v._type: + v._type = v._get_deserialize_callable_from_annotation(annotations.get(k, None)) + if not v._rest_name_input: + v._rest_name_input = k + + cls._attr_to_rest_field = attr_to_rest_field + cls._backcompat_attr_to_rest_field = { + _Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + + # Reverse mapping: REST wire name → Python attribute name + cls._rest_name_to_attr = {rf._rest_name: attr for attr, rf in attr_to_rest_field.items()} + + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return object.__new__(cls) + + +_MyMutableMapping.__getattr__ = _patched_getattr +_MyMutableMapping.__setattr__ = _patched_setattr +_MyMutableMapping.__getattribute__ = _patched_getattribute +_Model.__new__ = _patched_new + + +# --------------------------------------------------------------------------- +# Backcompat shims for public methods that existed on the old autorest +# ``msrest.serialization.Model`` base class. The TypeSpec-generated models +# inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not +# expose ``serialize``/``deserialize``/``from_dict``/``validate``/ +# ``is_xml_model``/``enable_additional_properties_sending``. Re-adding them +# here preserves backward compatibility for users (e.g. azure-storage-file- +# datalake) that still call these methods on models re-exported from +# azure-storage-blob. +# --------------------------------------------------------------------------- + + +_original_as_dict = _Model.as_dict + + +def _remap_keys(d, rest_name_to_attr): + """Recursively remap REST wire-name keys to Python attribute names.""" + if isinstance(d, dict): + return {rest_name_to_attr.get(k, k): _remap_keys(v, rest_name_to_attr) for k, v in d.items()} + if isinstance(d, list): + return [_remap_keys(item, rest_name_to_attr) for item in d] + return d + + +def _patched_as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + *, + exclude_readonly: bool = False, + **kwargs: Any, +) -> dict: + """Backcompat wrapper that returns Python attribute names (snake_case). + + Accepts both the old autorest signature (``keep_readonly``, + ``key_transformer``) and the new TypeSpec keyword-only + ``exclude_readonly`` parameter. ``key_transformer`` is accepted for + signature compatibility but ignored; keys are always remapped to + Python attribute names. + """ + kwargs.pop("is_xml", None) + effective_exclude = exclude_readonly or not keep_readonly + result = _original_as_dict(self, exclude_readonly=effective_exclude) + rest_name_to_attr = getattr(type(self), "_rest_name_to_attr", {}) + return _remap_keys(result, rest_name_to_attr) + + +def _patched_serialize(self, keep_readonly: bool = False, **kwargs: Any) -> dict: + """Backcompat alias for the old autorest ``Model.serialize``. + + Equivalent to ``as_dict(keep_readonly=keep_readonly)`` with REST wire + names (camelCase) as keys — matching what the old autorest serializer + sent to the server. + """ + kwargs.pop("is_xml", None) + return _original_as_dict(self, exclude_readonly=not keep_readonly) + + +def _patched_validate(self) -> list: # pylint: disable=unused-argument + """Backcompat no-op for the old autorest ``Model.validate``. + + TypeSpec models do not perform client-side validation; return an empty + list to match the old "no errors" return value. + """ + return [] + + +def _patched_deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: + """Backcompat classmethod for the old autorest ``Model.deserialize``. + + Accepts either a JSON-compatible dict/str or (when ``content_type`` is + XML) an XML string or ``ElementTree.Element``. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return _deserialize(cls, data) + + +def _patched_from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + content_type: Optional[str] = None, +) -> Any: + """Backcompat classmethod for the old autorest ``Model.from_dict``. + + ``key_extractors`` is accepted for signature compatibility but ignored; + the TypeSpec deserializer always uses REST-key mapping. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return _deserialize(cls, data) + + +def _patched_enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument + """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. + + TypeSpec models already round-trip unknown properties through ``_data``. + """ + return None + + +def _patched_is_xml_model(cls) -> bool: + """Backcompat classmethod for the old autorest ``Model.is_xml_model``. + + Returns True when the model has an ``_xml`` class attribute (set by the + generator for models that serialize to/from XML). + """ + return bool(getattr(cls, "_xml", None)) + + +_Model.as_dict = _patched_as_dict +_Model.serialize = _patched_serialize +_Model.validate = _patched_validate +_Model.deserialize = classmethod(_patched_deserialize) +_Model.from_dict = classmethod(_patched_from_dict) +_Model.enable_additional_properties_sending = classmethod(_patched_enable_additional_properties_sending) +_Model.is_xml_model = classmethod(_patched_is_xml_model) # --------------------------------------------------------------------------- @@ -58,10 +269,13 @@ def _patched_namedtuple_asdict(self) -> dict: _Model._asdict = _patched_namedtuple_asdict +__all__: List[str] = [] + + def patch_sdk(): """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 - """ + """ \ No newline at end of file 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 acb38ebc8caf..ccbde6ac6616 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -42,10 +42,16 @@ 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: - if enabled and days is None: + self.enabled = enabled + self.days = days + if self.enabled and (self.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: @@ -69,14 +75,23 @@ 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: - 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(), - ) + 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() @classmethod def _from_generated(cls, generated: Any) -> Self: @@ -105,13 +120,20 @@ 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] = None + """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: - 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(), - ) + 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() @classmethod def _from_generated(cls, generated: Any) -> Self: @@ -157,14 +179,25 @@ 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 of HTTP methods that are allowed to be executed + by the origin.""" + allowed_headers: str + """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" + exposed_headers: str + """The comma-delimited string representation of the list of response headers to expose to CORS clients.""" + max_age_in_seconds: int + """The number of seconds that the client/browser should cache a pre-flight response.""" + def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: - 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), - ) + 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) @staticmethod def _to_generated( From 7a7accf4ee4ec2bd2ba8af16b1276dbfaaa822fd Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 6 May 2026 09:33:30 -0700 Subject: [PATCH 046/102] fix diff --- .../azure/storage/queue/_models.py | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) 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 ccbde6ac6616..c7aed74fce21 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -124,7 +124,7 @@ class Metrics(GeneratedMetrics): """The version of Storage Analytics to configure.""" enabled: bool = False """Indicates whether metrics are enabled for the service.""" - include_apis: Optional[bool] = None + 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.""" @@ -339,9 +339,13 @@ class AccessPolicy(GenAccessPolicy): be interpreted as UTC. """ - start: Optional[Union["datetime", str]] # type: ignore[assignment] - expiry: Optional[Union["datetime", str]] # type: ignore[assignment] - permission: Optional[Union[QueueSasPermissions, str]] # type: ignore[assignment] + 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.""" def __init__( self, @@ -349,11 +353,9 @@ def __init__( expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - super().__init__( - start=start, # type: ignore[arg-type] - expiry=expiry, # type: ignore[arg-type] - permission=permission, # type: ignore[arg-type] - ) + self.start = start + self.expiry = expiry + self.permission = permission class QueueMessage(DictMixin): From 2249000698bcb355ffe8a4126e0649824b1c8c2a Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 13 May 2026 15:27:49 -0700 Subject: [PATCH 047/102] Fix analyze: trailing newline in _patch.py and wrap long line in _models.py Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/storage/queue/_generated/models/_patch.py | 2 +- sdk/storage/azure-storage-queue/azure/storage/queue/_models.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) 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 c4fb4ca7742e..257980819201 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 @@ -278,4 +278,4 @@ def patch_sdk(): `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 - """ \ No newline at end of file + """ 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 c7aed74fce21..e1b24fe46375 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -186,7 +186,8 @@ class CorsRule(GeneratedCorsRule): """The comma-delimited string representation of the list of HTTP methods that are allowed to be executed by the origin.""" allowed_headers: str - """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" + """The comma-delimited string representation of the list of headers allowed to be part of + the cross-origin request.""" exposed_headers: str """The comma-delimited string representation of the list of response headers to expose to CORS clients.""" max_age_in_seconds: int From 9ca877fe512b4202490eefcf9285e4029a6593c7 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 08:40:06 -0700 Subject: [PATCH 048/102] use commit from main branch --- sdk/storage/azure-storage-queue/tsp-location.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/storage/azure-storage-queue/tsp-location.yaml b/sdk/storage/azure-storage-queue/tsp-location.yaml index b785991fc1da..487ac7889ffb 100644 --- a/sdk/storage/azure-storage-queue/tsp-location.yaml +++ b/sdk/storage/azure-storage-queue/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/storage/Microsoft.QueueStorage -commit: -repo: +commit: 62b449d4f801b4db64038829f51fa546fe89ee5d +repo: Azure/azure-rest-api-specs additionalDirectories: From ee81c642d8009281e05571fcd6bb329282b5fa9c Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 08:50:27 -0700 Subject: [PATCH 049/102] update doc on clients --- .../azure/storage/queue/_generated/_patch.py | 21 ++++++++++++++++--- .../storage/queue/_generated/aio/_patch.py | 21 ++++++++++++++++--- 2 files changed, 36 insertions(+), 6 deletions(-) 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 c079cad7a525..3891e6290098 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 @@ -30,8 +30,8 @@ class QueuesClientConfiguration(QueuesClientConfigurationInternal): :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 + :param credential: Credential used to authenticate requests to the service. + :type credential: ~azure.core.credentials.TokenCredential or None :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. @@ -54,7 +54,22 @@ def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **k class QueuesClient(QueuesClientInternal): - """QueuesClient that supports being instantiated with a pre-built pipeline.""" + """QueuesClient. + + :ivar service: ServiceOperations operations + :vartype service: azure.storage.queue.operations.ServiceOperations + :ivar queue: QueueOperations operations + :vartype queue: azure.storage.queue.operations.QueueOperations + :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. + :type credential: ~azure.core.credentials.TokenCredential or None + :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: _pipeline = kwargs.pop("pipeline", None) 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 039588791200..9e470fc4f1b9 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 @@ -30,8 +30,8 @@ class QueuesClientConfiguration(QueuesClientConfigurationInternal): :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 + :param credential: Credential used to authenticate requests to the service. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential or None :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. @@ -54,7 +54,22 @@ def __init__(self, url: str, credential: Optional["AsyncTokenCredential"] = None class QueuesClient(_QueuesClient): - """QueuesClient that supports being instantiated with a pre-built pipeline.""" + """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 + :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. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential or None + :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: _pipeline = kwargs.pop("pipeline", None) From ce0aba3cf5eb89805b4d9f6a67386f76cbd4bfa9 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 09:20:31 -0700 Subject: [PATCH 050/102] add todo and fixing up _shared for alignment --- .../storage/queue/_generated/models/_patch.py | 1 + .../azure/storage/queue/_shared/policies.py | 6 ++++ .../queue/_shared/shared_access_signature.py | 31 ++++++++++++------- 3 files changed, 27 insertions(+), 11 deletions(-) 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 257980819201..6824902b547d 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 @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +# TODO: Waiting on Emitter Perf updates before updating these methods import xml.etree.ElementTree as ET from typing import Any, Callable, List, Optional 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 cec4acf285ab..b5b33ede2f92 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 @@ -121,6 +121,12 @@ 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) 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 0f7016f11d96..60d2a3475f94 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,7 +117,15 @@ 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, **kwargs + self, + services, + resource_types, + permission, + expiry, + start=None, + ip=None, + protocol=None, + sts_hook=None, ) -> str: """ Generates a shared access signature for the account. @@ -159,9 +167,6 @@ 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. @@ -172,7 +177,6 @@ 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: @@ -194,9 +198,6 @@ 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) @@ -225,7 +226,12 @@ 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) @@ -271,10 +277,13 @@ 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) - + get_value_to_append(QueryStringConstants.SIGNED_ENCRYPTION_SCOPE) + + "\n" # Signed Encryption Scope - always empty for queue ) - 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: From 5b12162fd8443fe7771683160c8d230f5c0d3327 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 09:30:00 -0700 Subject: [PATCH 051/102] Apply suggestion from @l0lawrence --- sdk/storage/azure-storage-queue/azure/storage/queue/_models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e1b24fe46375..1304834c8a2b 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -183,7 +183,7 @@ class CorsRule(GeneratedCorsRule): """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 of HTTP methods that are allowed to be executed + """The comma-delimited string representation of the list HTTP methods that are allowed to be executed by the origin.""" allowed_headers: str """The comma-delimited string representation of the list of headers allowed to be part of From 7a653286ecc1335383d4262ba37c3e82f847cd4e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 09:31:40 -0700 Subject: [PATCH 052/102] ordering nit --- .../azure/storage/queue/_models.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) 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 e1b24fe46375..c0bb2a7ae4d7 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -166,17 +166,17 @@ class CorsRule(GeneratedCorsRule): A list of HTTP methods that are allowed to be executed by the origin. The list must contain at least one entry. For Azure Storage, permitted methods are DELETE, GET, HEAD, MERGE, POST, OPTIONS or PUT. - :keyword int max_age_in_seconds: - The number of seconds that the client/browser should cache a - pre-flight response. + :keyword List[str] allowed_headers: + Defaults to an empty list. A list of headers allowed to be part of + the cross-origin request. Limited to 64 defined headers and 2 prefixed + headers. Each header can be up to 256 characters. :keyword List[str] exposed_headers: Defaults to an empty list. A list of response headers to expose to CORS clients. Limited to 64 defined headers and two prefixed headers. Each header can be up to 256 characters. - :keyword List[str] allowed_headers: - Defaults to an empty list. A list of headers allowed to be part of - the cross-origin request. Limited to 64 defined headers and 2 prefixed - headers. Each header can be up to 256 characters. + :keyword int max_age_in_seconds: + The number of seconds that the client/browser should cache a + pre-flight response. """ allowed_origins: str From 827775e62ca8423298a1fd59d0688e89e588f529 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 09:33:28 -0700 Subject: [PATCH 053/102] this order --- .../azure/storage/queue/_models.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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 69c128b68f5c..e1b24fe46375 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -166,24 +166,24 @@ class CorsRule(GeneratedCorsRule): A list of HTTP methods that are allowed to be executed by the origin. The list must contain at least one entry. For Azure Storage, permitted methods are DELETE, GET, HEAD, MERGE, POST, OPTIONS or PUT. - :keyword List[str] allowed_headers: - Defaults to an empty list. A list of headers allowed to be part of - the cross-origin request. Limited to 64 defined headers and 2 prefixed - headers. Each header can be up to 256 characters. + :keyword int max_age_in_seconds: + The number of seconds that the client/browser should cache a + pre-flight response. :keyword List[str] exposed_headers: Defaults to an empty list. A list of response headers to expose to CORS clients. Limited to 64 defined headers and two prefixed headers. Each header can be up to 256 characters. - :keyword int max_age_in_seconds: - The number of seconds that the client/browser should cache a - pre-flight response. + :keyword List[str] allowed_headers: + Defaults to an empty list. A list of headers allowed to be part of + the cross-origin request. Limited to 64 defined headers and 2 prefixed + 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 + """The comma-delimited string representation of the list of HTTP methods that are allowed to be executed by the origin.""" allowed_headers: str """The comma-delimited string representation of the list of headers allowed to be part of From 9f26f13fb4e4a8ddd5a7e25928dcf0e1189d0ee0 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 09:35:09 -0700 Subject: [PATCH 054/102] order --- .../azure-storage-queue/azure/storage/queue/_models.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 e1b24fe46375..aee076484796 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -183,15 +183,15 @@ class CorsRule(GeneratedCorsRule): """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 of HTTP methods that are allowed to be executed + """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.""" - exposed_headers: str - """The comma-delimited string representation of the list of response headers to expose to CORS clients.""" - max_age_in_seconds: int - """The number of seconds that the client/browser should cache a pre-flight response.""" def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: self.allowed_origins = ",".join(allowed_origins) From f3587931c1c9211ed456c90ee835169b432958b9 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 18 May 2026 18:11:51 -0700 Subject: [PATCH 055/102] added a todo --- .../storage/queue/_generated/models/_patch.py | 108 +++--------------- .../azure/storage/queue/_models.py | 45 ++++---- 2 files changed, 40 insertions(+), 113 deletions(-) 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 6824902b547d..b193df345ff6 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 @@ -15,103 +15,14 @@ from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize -def _patched_getattr(self, name): - """Lazily initialize _data for subclasses that skip super().__init__().""" - if name == "_data": - object.__setattr__(self, "_data", {}) - return self._data - raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") - - -def _patched_setattr(self, name, value): - """Route attribute writes through _RestField descriptors even when shadowed.""" - if not name.startswith("_"): - try: - rf = type(self)._attr_to_rest_field.get(name) - except AttributeError: - pass - else: - if rf is not None: - rf.__set__(self, value) - return - object.__setattr__(self, name, value) - - -def _patched_getattribute(self, name): - """Route attribute reads through _RestField descriptors even when shadowed.""" - if not name.startswith("_"): - try: - rest_fields = type(self)._attr_to_rest_field - except AttributeError: - pass - else: - rf = rest_fields.get(name) - if rf is not None: - return rf.__get__(self, type(self)) - return object.__getattribute__(self, name) - - -# The original ``Model.__new__`` does ``rf._module = cls.__module__`` which -# lets an external subclass (e.g. from azure-storage-file-datalake) overwrite -# ``_module`` on the *shared* descriptor, corrupting type resolution for -# every class that shares it. This replacement resolves forward references -# against the module that *defined* the rest_field and uses that class's own -# annotations (not merged subclass annotations) to avoid resolving to a type -# whose ``__init__`` can't handle XML elements. - - -def _patched_new(cls, *args, **kwargs): - if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: - # Walk only user-defined classes (base-first), stopping before the - # framework base. Each _RestField is configured with the module of - # the class that defined it so forward references resolve correctly. - user_classes = [] - for c in cls.__mro__: - if c is _Model: - break - user_classes.append(c) - - attr_to_rest_field: dict[str, _RestField] = {} - for mro_class in reversed(user_classes): - annotations = getattr(mro_class, "__annotations__", {}) - for k, v in mro_class.__dict__.items(): - if not k.startswith("_") and isinstance(v, _RestField): - attr_to_rest_field[k] = v - v._module = mro_class.__module__ - if not v._type: - v._type = v._get_deserialize_callable_from_annotation(annotations.get(k, None)) - if not v._rest_name_input: - v._rest_name_input = k - - cls._attr_to_rest_field = attr_to_rest_field - cls._backcompat_attr_to_rest_field = { - _Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf - for attr, rf in cls._attr_to_rest_field.items() - } - - # Reverse mapping: REST wire name → Python attribute name - cls._rest_name_to_attr = {rf._rest_name: attr for attr, rf in attr_to_rest_field.items()} - - cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") - - return object.__new__(cls) - - -_MyMutableMapping.__getattr__ = _patched_getattr -_MyMutableMapping.__setattr__ = _patched_setattr -_MyMutableMapping.__getattribute__ = _patched_getattribute -_Model.__new__ = _patched_new - - # --------------------------------------------------------------------------- # Backcompat shims for public methods that existed on the old autorest # ``msrest.serialization.Model`` base class. The TypeSpec-generated models # inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not # expose ``serialize``/``deserialize``/``from_dict``/``validate``/ -# ``is_xml_model``/``enable_additional_properties_sending``. Re-adding them -# here preserves backward compatibility for users (e.g. azure-storage-file- -# datalake) that still call these methods on models re-exported from -# azure-storage-blob. +# ``is_xml_model``/``enable_additional_properties_sending``/ +# ``__eq__``/``__ne__``/``__str__``. Re-adding them +# here preserves backward compatibility for users. # --------------------------------------------------------------------------- @@ -218,15 +129,28 @@ def _patched_is_xml_model(cls) -> bool: return bool(getattr(cls, "_xml", None)) +def _patched_str(self) -> str: + """Backcompat for the old autorest ``Model.__str__``. + Current Mutable Mapping returns __repr__. + + The old implementation returned ``str(self.__dict__)``. We approximate + that by returning the string form of the internal ``_data`` dict which + holds all model fields. + """ + return str(self._data) + + _Model.as_dict = _patched_as_dict _Model.serialize = _patched_serialize _Model.validate = _patched_validate +_Model.__str__ = _patched_str _Model.deserialize = classmethod(_patched_deserialize) _Model.from_dict = classmethod(_patched_from_dict) _Model.enable_additional_properties_sending = classmethod(_patched_enable_additional_properties_sending) _Model.is_xml_model = classmethod(_patched_is_xml_model) +# TODO: Can we eliminate the need for this by changing the CLI's ``todict``? # --------------------------------------------------------------------------- # Backcompat shim for legacy ``knack.util.todict`` consumers (e.g. Azure CLI). # knack checks ``hasattr(obj, '_asdict')`` (namedtuple convention) BEFORE 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 aee076484796..6a09e24dc07d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -3,7 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -# pylint: disable=too-few-public-methods, super-init-not-called +# pylint: disable=too-few-public-methods import sys from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING, Union @@ -48,10 +48,9 @@ class RetentionPolicy(GeneratedRetentionPolicy): """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: @@ -87,11 +86,13 @@ class QueueAnalyticsLogging(GeneratedLogging): """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: @@ -130,10 +131,12 @@ class Metrics(GeneratedMetrics): """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: @@ -194,11 +197,13 @@ class CorsRule(GeneratedCorsRule): 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( @@ -354,9 +359,7 @@ 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, expiry=expiry, permission=permission) class QueueMessage(DictMixin): From 557c2176914edf1d8d7fe9071d74579b45d67ffc Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 18 May 2026 18:28:53 -0700 Subject: [PATCH 056/102] updating models --- .../storage/queue/_generated/models/_patch.py | 13 -------- .../azure/storage/queue/_models.py | 32 +++++++++---------- 2 files changed, 16 insertions(+), 29 deletions(-) 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 b193df345ff6..820c492de6a0 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 @@ -128,22 +128,9 @@ def _patched_is_xml_model(cls) -> bool: """ return bool(getattr(cls, "_xml", None)) - -def _patched_str(self) -> str: - """Backcompat for the old autorest ``Model.__str__``. - Current Mutable Mapping returns __repr__. - - The old implementation returned ``str(self.__dict__)``. We approximate - that by returning the string form of the internal ``_data`` dict which - holds all model fields. - """ - return str(self._data) - - _Model.as_dict = _patched_as_dict _Model.serialize = _patched_serialize _Model.validate = _patched_validate -_Model.__str__ = _patched_str _Model.deserialize = classmethod(_patched_deserialize) _Model.from_dict = classmethod(_patched_from_dict) _Model.enable_additional_properties_sending = classmethod(_patched_enable_additional_properties_sending) 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 6a09e24dc07d..0543a4544bb2 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -42,9 +42,9 @@ class RetentionPolicy(GeneratedRetentionPolicy): be deleted. """ - enabled: bool = False + enabled: bool """Indicates whether a retention policy is enabled for the storage service.""" - days: Optional[int] = None + days: Optional[int] """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: @@ -74,15 +74,15 @@ class QueueAnalyticsLogging(GeneratedLogging): :keyword ~azure.storage.queue.RetentionPolicy retention_policy: The retention policy for the metrics. """ - version: str = "1.0" + version: str """The version of Storage Analytics to configure.""" - delete: bool = False + delete: bool """Indicates whether all delete requests should be logged.""" - read: bool = False + read: bool """Indicates whether all read requests should be logged.""" - write: bool = False + write: bool """Indicates whether all write requests should be logged.""" - retention_policy: RetentionPolicy = RetentionPolicy() + retention_policy: RetentionPolicy """The retention policy for the metrics.""" def __init__(self, **kwargs: Any) -> None: @@ -121,13 +121,13 @@ class Metrics(GeneratedMetrics): :keyword ~azure.storage.queue.RetentionPolicy retention_policy: The retention policy for the metrics. """ - version: str = "1.0" + version: str """The version of Storage Analytics to configure.""" - enabled: bool = False + enabled: bool """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() + retention_policy: RetentionPolicy """The retention policy for the metrics.""" def __init__(self, **kwargs: Any) -> None: @@ -182,17 +182,17 @@ class CorsRule(GeneratedCorsRule): headers. Each header can be up to 256 characters. """ - allowed_origins: str + allowed_origins: str # type: ignore[assignment] """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 + CORS, or \"*\" to allow all domains.""" + allowed_methods: str # type: ignore[assignment] """The comma-delimited string representation of the list HTTP methods that are allowed to be executed by the origin.""" - max_age_in_seconds: int + max_age_in_seconds: int # type: ignore[assignment] """The number of seconds that the client/browser should cache a pre-flight response.""" - exposed_headers: str + exposed_headers: str # type: ignore[assignment] """The comma-delimited string representation of the list of response headers to expose to CORS clients.""" - allowed_headers: str + allowed_headers: str # type: ignore[assignment] """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" From 28dae8e26d4447060aafdc80416dd7fd7bc9c0bd Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 18 May 2026 20:53:03 -0700 Subject: [PATCH 057/102] Revert "added a todo" This reverts commit f3587931c1c9211ed456c90ee835169b432958b9. --- .../storage/queue/_generated/models/_patch.py | 92 ++++++++++++++++++- 1 file changed, 89 insertions(+), 3 deletions(-) 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 820c492de6a0..fe302c531b16 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 @@ -15,13 +15,100 @@ from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize +def _patched_getattr(self, name): + """Lazily initialize _data for subclasses that skip super().__init__().""" + if name == "_data": + object.__setattr__(self, "_data", {}) + return self._data + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + +def _patched_setattr(self, name, value): + """Route attribute writes through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + try: + rf = type(self)._attr_to_rest_field.get(name) + except AttributeError: + pass + else: + if rf is not None: + rf.__set__(self, value) + return + object.__setattr__(self, name, value) + + +def _patched_getattribute(self, name): + """Route attribute reads through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + try: + rest_fields = type(self)._attr_to_rest_field + except AttributeError: + pass + else: + rf = rest_fields.get(name) + if rf is not None: + return rf.__get__(self, type(self)) + return object.__getattribute__(self, name) + + +# The original ``Model.__new__`` does ``rf._module = cls.__module__`` which +# lets an external subclass (e.g. from azure-storage-file-datalake) overwrite +# ``_module`` on the *shared* descriptor, corrupting type resolution for +# every class that shares it. This replacement resolves forward references +# against the module that *defined* the rest_field and uses that class's own +# annotations (not merged subclass annotations) to avoid resolving to a type +# whose ``__init__`` can't handle XML elements. + + +def _patched_new(cls, *args, **kwargs): + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # Walk only user-defined classes (base-first), stopping before the + # framework base. Each _RestField is configured with the module of + # the class that defined it so forward references resolve correctly. + user_classes = [] + for c in cls.__mro__: + if c is _Model: + break + user_classes.append(c) + + attr_to_rest_field: dict[str, _RestField] = {} + for mro_class in reversed(user_classes): + annotations = getattr(mro_class, "__annotations__", {}) + for k, v in mro_class.__dict__.items(): + if not k.startswith("_") and isinstance(v, _RestField): + attr_to_rest_field[k] = v + v._module = mro_class.__module__ + if not v._type: + v._type = v._get_deserialize_callable_from_annotation(annotations.get(k, None)) + if not v._rest_name_input: + v._rest_name_input = k + + cls._attr_to_rest_field = attr_to_rest_field + cls._backcompat_attr_to_rest_field = { + _Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + + # Reverse mapping: REST wire name → Python attribute name + cls._rest_name_to_attr = {rf._rest_name: attr for attr, rf in attr_to_rest_field.items()} + + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return object.__new__(cls) + + +_MyMutableMapping.__getattr__ = _patched_getattr +_MyMutableMapping.__setattr__ = _patched_setattr +_MyMutableMapping.__getattribute__ = _patched_getattribute +_Model.__new__ = _patched_new + + # --------------------------------------------------------------------------- # Backcompat shims for public methods that existed on the old autorest # ``msrest.serialization.Model`` base class. The TypeSpec-generated models # inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not # expose ``serialize``/``deserialize``/``from_dict``/``validate``/ -# ``is_xml_model``/``enable_additional_properties_sending``/ -# ``__eq__``/``__ne__``/``__str__``. Re-adding them +# ``is_xml_model``/``enable_additional_properties_sending``. Re-adding them # here preserves backward compatibility for users. # --------------------------------------------------------------------------- @@ -137,7 +224,6 @@ def _patched_is_xml_model(cls) -> bool: _Model.is_xml_model = classmethod(_patched_is_xml_model) -# TODO: Can we eliminate the need for this by changing the CLI's ``todict``? # --------------------------------------------------------------------------- # Backcompat shim for legacy ``knack.util.todict`` consumers (e.g. Azure CLI). # knack checks ``hasattr(obj, '_asdict')`` (namedtuple convention) BEFORE From 5dda7a72bca775074c2a817565393a3887759316 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 18 May 2026 21:00:04 -0700 Subject: [PATCH 058/102] todo --- .../storage/queue/_generated/models/_patch.py | 107 ++++++------------ 1 file changed, 33 insertions(+), 74 deletions(-) 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 fe302c531b16..1097ecdd5267 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 @@ -15,91 +15,50 @@ from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize -def _patched_getattr(self, name): - """Lazily initialize _data for subclasses that skip super().__init__().""" - if name == "_data": - object.__setattr__(self, "_data", {}) - return self._data - raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") - - -def _patched_setattr(self, name, value): - """Route attribute writes through _RestField descriptors even when shadowed.""" - if not name.startswith("_"): - try: - rf = type(self)._attr_to_rest_field.get(name) - except AttributeError: - pass - else: - if rf is not None: - rf.__set__(self, value) - return - object.__setattr__(self, name, value) - - -def _patched_getattribute(self, name): - """Route attribute reads through _RestField descriptors even when shadowed.""" - if not name.startswith("_"): - try: - rest_fields = type(self)._attr_to_rest_field - except AttributeError: - pass - else: - rf = rest_fields.get(name) - if rf is not None: - return rf.__get__(self, type(self)) - return object.__getattribute__(self, name) - - # The original ``Model.__new__`` does ``rf._module = cls.__module__`` which -# lets an external subclass (e.g. from azure-storage-file-datalake) overwrite +# lets an external subclass overwrite # ``_module`` on the *shared* descriptor, corrupting type resolution for # every class that shares it. This replacement resolves forward references # against the module that *defined* the rest_field and uses that class's own # annotations (not merged subclass annotations) to avoid resolving to a type # whose ``__init__`` can't handle XML elements. - +# TODO: ask the emitter folks def _patched_new(cls, *args, **kwargs): - if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: - # Walk only user-defined classes (base-first), stopping before the - # framework base. Each _RestField is configured with the module of - # the class that defined it so forward references resolve correctly. - user_classes = [] - for c in cls.__mro__: - if c is _Model: - break - user_classes.append(c) - - attr_to_rest_field: dict[str, _RestField] = {} - for mro_class in reversed(user_classes): - annotations = getattr(mro_class, "__annotations__", {}) - for k, v in mro_class.__dict__.items(): - if not k.startswith("_") and isinstance(v, _RestField): - attr_to_rest_field[k] = v - v._module = mro_class.__module__ - if not v._type: - v._type = v._get_deserialize_callable_from_annotation(annotations.get(k, None)) - if not v._rest_name_input: - v._rest_name_input = k - - cls._attr_to_rest_field = attr_to_rest_field - cls._backcompat_attr_to_rest_field = { - _Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf - for attr, rf in cls._attr_to_rest_field.items() - } - - # Reverse mapping: REST wire name → Python attribute name - cls._rest_name_to_attr = {rf._rest_name: attr for attr, rf in attr_to_rest_field.items()} - - cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + cache_key = f"{cls.__module__}.{cls.__qualname__}" + if cache_key in cls._calculated: + return object.__new__(cls) + + # Walk only user-defined classes (base-first), stopping before the + # framework base. Each _RestField is configured with the module of + # the class that defined it so forward references resolve correctly. + model_index = cls.__mro__.index(_Model) + attr_to_rest_field: dict[str, _RestField] = {} + for mro_class in reversed(cls.__mro__[:model_index]): + annotations = getattr(mro_class, "__annotations__", {}) + for attr, rest_field in mro_class.__dict__.items(): + if attr.startswith("_") or not isinstance(rest_field, _RestField): + continue + + attr_to_rest_field[attr] = rest_field + rest_field._module = mro_class.__module__ + if not rest_field._type: + rest_field._type = rest_field._get_deserialize_callable_from_annotation(annotations.get(attr)) + if not rest_field._rest_name_input: + rest_field._rest_name_input = attr + + cls._attr_to_rest_field = attr_to_rest_field + cls._backcompat_attr_to_rest_field = { + _Model._get_backcompat_attribute_name(attr_to_rest_field, attr): rest_field + for attr, rest_field in attr_to_rest_field.items() + } + + # Reverse mapping: REST wire name → Python attribute name + cls._rest_name_to_attr = {rest_field._rest_name: attr for attr, rest_field in attr_to_rest_field.items()} + cls._calculated.add(cache_key) return object.__new__(cls) - -_MyMutableMapping.__getattr__ = _patched_getattr -_MyMutableMapping.__setattr__ = _patched_setattr -_MyMutableMapping.__getattribute__ = _patched_getattribute _Model.__new__ = _patched_new From 0d54c8df7e1a40b96ed9d1b39f0bbbf46bfdcd70 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 18 May 2026 21:04:46 -0700 Subject: [PATCH 059/102] black --- .../azure/storage/queue/_generated/models/_patch.py | 3 +++ 1 file changed, 3 insertions(+) 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 1097ecdd5267..af2111d03ff5 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 @@ -23,6 +23,7 @@ # annotations (not merged subclass annotations) to avoid resolving to a type # whose ``__init__`` can't handle XML elements. + # TODO: ask the emitter folks def _patched_new(cls, *args, **kwargs): cache_key = f"{cls.__module__}.{cls.__qualname__}" @@ -59,6 +60,7 @@ def _patched_new(cls, *args, **kwargs): return object.__new__(cls) + _Model.__new__ = _patched_new @@ -174,6 +176,7 @@ def _patched_is_xml_model(cls) -> bool: """ return bool(getattr(cls, "_xml", None)) + _Model.as_dict = _patched_as_dict _Model.serialize = _patched_serialize _Model.validate = _patched_validate From ed746726ee4e509c6b552f1913d170cc7321af05 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 19 May 2026 09:14:31 -0700 Subject: [PATCH 060/102] fixing models --- .../storage/queue/_generated/models/_patch.py | 49 ------------------- .../azure/storage/queue/_models.py | 14 +++++- 2 files changed, 12 insertions(+), 51 deletions(-) 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 af2111d03ff5..665c2febd424 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 @@ -15,55 +15,6 @@ from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize -# The original ``Model.__new__`` does ``rf._module = cls.__module__`` which -# lets an external subclass overwrite -# ``_module`` on the *shared* descriptor, corrupting type resolution for -# every class that shares it. This replacement resolves forward references -# against the module that *defined* the rest_field and uses that class's own -# annotations (not merged subclass annotations) to avoid resolving to a type -# whose ``__init__`` can't handle XML elements. - - -# TODO: ask the emitter folks -def _patched_new(cls, *args, **kwargs): - cache_key = f"{cls.__module__}.{cls.__qualname__}" - if cache_key in cls._calculated: - return object.__new__(cls) - - # Walk only user-defined classes (base-first), stopping before the - # framework base. Each _RestField is configured with the module of - # the class that defined it so forward references resolve correctly. - model_index = cls.__mro__.index(_Model) - attr_to_rest_field: dict[str, _RestField] = {} - for mro_class in reversed(cls.__mro__[:model_index]): - annotations = getattr(mro_class, "__annotations__", {}) - for attr, rest_field in mro_class.__dict__.items(): - if attr.startswith("_") or not isinstance(rest_field, _RestField): - continue - - attr_to_rest_field[attr] = rest_field - rest_field._module = mro_class.__module__ - if not rest_field._type: - rest_field._type = rest_field._get_deserialize_callable_from_annotation(annotations.get(attr)) - if not rest_field._rest_name_input: - rest_field._rest_name_input = attr - - cls._attr_to_rest_field = attr_to_rest_field - cls._backcompat_attr_to_rest_field = { - _Model._get_backcompat_attribute_name(attr_to_rest_field, attr): rest_field - for attr, rest_field in attr_to_rest_field.items() - } - - # Reverse mapping: REST wire name → Python attribute name - cls._rest_name_to_attr = {rest_field._rest_name: attr for attr, rest_field in attr_to_rest_field.items()} - cls._calculated.add(cache_key) - - return object.__new__(cls) - - -_Model.__new__ = _patched_new - - # --------------------------------------------------------------------------- # Backcompat shims for public methods that existed on the old autorest # ``msrest.serialization.Model`` base class. The TypeSpec-generated models 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 0543a4544bb2..e152d06f2cd9 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -6,6 +6,7 @@ # pylint: disable=too-few-public-methods import sys +import xml.etree.ElementTree as ET from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING, Union from azure.core.exceptions import HttpResponseError from azure.core.paging import PageIterator @@ -98,6 +99,9 @@ def __init__(self, **kwargs: Any) -> None: def _from_generated(cls, generated: Any) -> Self: if not generated: return cls() + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedLogging(generated) # type: ignore[assignment] return cls( version=generated.version, delete=generated.delete, @@ -108,7 +112,6 @@ def _from_generated(cls, generated: Any) -> Self: ), ) - class Metrics(GeneratedMetrics): """A summary of request statistics grouped by API in hour or minute aggregates. @@ -142,6 +145,9 @@ def __init__(self, **kwargs: Any) -> None: def _from_generated(cls, generated: Any) -> Self: if not generated: return cls() + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedMetrics(generated) # type: ignore[assignment] return cls( version=generated.version, enabled=generated.enabled, @@ -359,7 +365,11 @@ def __init__( expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - super().__init__(start=start, expiry=expiry, permission=permission) + # TODO: here AccessPolicy never took in a datetime + # but we supported datetime and serialized it when passing the model through. (see set access policy) + if isinstance(permission, QueueSasPermissions): + permission = str(permission) + super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] class QueueMessage(DictMixin): From 97546303555b471baafc747cc7b83090a729aaa3 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 19 May 2026 09:56:18 -0700 Subject: [PATCH 061/102] updating --- .../azure/storage/queue/_models.py | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) 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 e152d06f2cd9..84f73f292172 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -43,9 +43,9 @@ class RetentionPolicy(GeneratedRetentionPolicy): be deleted. """ - enabled: bool + enabled: bool = False """Indicates whether a retention policy is enabled for the storage service.""" - days: Optional[int] + 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: @@ -57,6 +57,9 @@ def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: def _from_generated(cls, generated: Any) -> Self: if not generated: return cls() + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedRetentionPolicy(generated) # type: ignore[assignment,call-overload] return cls( enabled=generated.enabled, days=generated.days, @@ -75,15 +78,15 @@ class QueueAnalyticsLogging(GeneratedLogging): :keyword ~azure.storage.queue.RetentionPolicy retention_policy: The retention policy for the metrics. """ - version: str + version: str = "1.0" """The version of Storage Analytics to configure.""" - delete: bool + delete: bool = False """Indicates whether all delete requests should be logged.""" - read: bool + read: bool = False """Indicates whether all read requests should be logged.""" - write: bool + write: bool = False """Indicates whether all write requests should be logged.""" - retention_policy: RetentionPolicy + retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" def __init__(self, **kwargs: Any) -> None: @@ -101,7 +104,7 @@ def _from_generated(cls, generated: Any) -> Self: return cls() # Handle XML Element by converting to generated model first if isinstance(generated, ET.Element): - generated = GeneratedLogging(generated) # type: ignore[assignment] + generated = GeneratedLogging(generated) # type: ignore[assignment,call-overload] return cls( version=generated.version, delete=generated.delete, @@ -124,13 +127,13 @@ class Metrics(GeneratedMetrics): :keyword ~azure.storage.queue.RetentionPolicy retention_policy: The retention policy for the metrics. """ - version: str + version: str = "1.0" """The version of Storage Analytics to configure.""" - enabled: bool + 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 + retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" def __init__(self, **kwargs: Any) -> None: @@ -147,7 +150,7 @@ def _from_generated(cls, generated: Any) -> Self: return cls() # Handle XML Element by converting to generated model first if isinstance(generated, ET.Element): - generated = GeneratedMetrics(generated) # type: ignore[assignment] + generated = GeneratedMetrics(generated) # type: ignore[assignment,call-overload] return cls( version=generated.version, enabled=generated.enabled, @@ -188,17 +191,17 @@ class CorsRule(GeneratedCorsRule): headers. Each header can be up to 256 characters. """ - allowed_origins: str # type: ignore[assignment] + 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 # type: ignore[assignment] + 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 # type: ignore[assignment] + max_age_in_seconds: int """The number of seconds that the client/browser should cache a pre-flight response.""" - exposed_headers: str # type: ignore[assignment] + exposed_headers: str """The comma-delimited string representation of the list of response headers to expose to CORS clients.""" - allowed_headers: str # type: ignore[assignment] + allowed_headers: str """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" @@ -233,6 +236,9 @@ def _to_generated( @classmethod def _from_generated(cls, generated: Any) -> Self: + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedCorsRule(generated) # type: ignore[assignment,call-overload] return cls( [generated.allowed_origins], [generated.allowed_methods], From de041edbc485047dc336a878d7dfceaf6a20585b Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 19 May 2026 11:09:29 -0700 Subject: [PATCH 062/102] testing backcompat --- .../storage/queue/_generated/models/_patch.py | 250 +++++++----------- .../azure/storage/queue/_models.py | 19 ++ 2 files changed, 114 insertions(+), 155 deletions(-) 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 665c2febd424..db5f027a5879 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 @@ -12,172 +12,112 @@ import xml.etree.ElementTree as ET from typing import Any, Callable, List, Optional -from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize +from .._utils.model_base import Model as _deserialize +from azure.core.serialization import as_attribute_dict +# do an _mixin and have the public models inherit from it + # --------------------------------------------------------------------------- -# Backcompat shims for public methods that existed on the old autorest -# ``msrest.serialization.Model`` base class. The TypeSpec-generated models -# inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not +# Backcompat shims for public methods that existed on the old autorest msrest models. +# The TypeSpec-generated models inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not # expose ``serialize``/``deserialize``/``from_dict``/``validate``/ # ``is_xml_model``/``enable_additional_properties_sending``. Re-adding them # here preserves backward compatibility for users. # --------------------------------------------------------------------------- +class _ModelBackCompatMixin: + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + *, + exclude_readonly: bool = False, + **kwargs: Any, + ) -> dict: + """Backcompat wrapper that returns Python attribute names (snake_case). + + Accepts both the old autorest signature (``keep_readonly``, + ``key_transformer``) and the new TypeSpec keyword-only + ``exclude_readonly`` parameter. ``key_transformer`` is accepted for + signature compatibility but ignored; keys are always remapped to + Python attribute names. + """ + effective_exclude = exclude_readonly or not keep_readonly + result = as_attribute_dict(self, exclude_readonly=effective_exclude) + return result + + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> dict: + """Backcompat alias for the old autorest ``Model.serialize``. + + Equivalent to ``as_dict(keep_readonly=keep_readonly)`` with REST wire + names (camelCase) as keys — matching what the old autorest serializer + sent to the server. + """ + return as_attribute_dict(self, exclude_readonly=not keep_readonly) + + + def validate(self) -> list: # pylint: disable=unused-argument + """Backcompat no-op for the old autorest ``Model.validate``. + + TypeSpec models do not perform client-side validation; return an empty + list to match the old "no errors" return value. + """ + return [] + + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: + """Backcompat classmethod for the old autorest ``Model.deserialize``. + + Accepts either a JSON-compatible dict/str or (when ``content_type`` is + XML) an XML string or ``ElementTree.Element``. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return _deserialize(cls, data) + + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + content_type: Optional[str] = None, + ) -> Any: + """Backcompat classmethod for the old autorest ``Model.from_dict``. + + ``key_extractors`` is accepted for signature compatibility but ignored; + the TypeSpec deserializer always uses REST-key mapping. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return _deserialize(cls, data) + + + @classmethod + def enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument + """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. + + TypeSpec models already round-trip unknown properties through ``_data``. + """ + return None -_original_as_dict = _Model.as_dict - - -def _remap_keys(d, rest_name_to_attr): - """Recursively remap REST wire-name keys to Python attribute names.""" - if isinstance(d, dict): - return {rest_name_to_attr.get(k, k): _remap_keys(v, rest_name_to_attr) for k, v in d.items()} - if isinstance(d, list): - return [_remap_keys(item, rest_name_to_attr) for item in d] - return d - - -def _patched_as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument - *, - exclude_readonly: bool = False, - **kwargs: Any, -) -> dict: - """Backcompat wrapper that returns Python attribute names (snake_case). - - Accepts both the old autorest signature (``keep_readonly``, - ``key_transformer``) and the new TypeSpec keyword-only - ``exclude_readonly`` parameter. ``key_transformer`` is accepted for - signature compatibility but ignored; keys are always remapped to - Python attribute names. - """ - kwargs.pop("is_xml", None) - effective_exclude = exclude_readonly or not keep_readonly - result = _original_as_dict(self, exclude_readonly=effective_exclude) - rest_name_to_attr = getattr(type(self), "_rest_name_to_attr", {}) - return _remap_keys(result, rest_name_to_attr) - - -def _patched_serialize(self, keep_readonly: bool = False, **kwargs: Any) -> dict: - """Backcompat alias for the old autorest ``Model.serialize``. - - Equivalent to ``as_dict(keep_readonly=keep_readonly)`` with REST wire - names (camelCase) as keys — matching what the old autorest serializer - sent to the server. - """ - kwargs.pop("is_xml", None) - return _original_as_dict(self, exclude_readonly=not keep_readonly) - - -def _patched_validate(self) -> list: # pylint: disable=unused-argument - """Backcompat no-op for the old autorest ``Model.validate``. - - TypeSpec models do not perform client-side validation; return an empty - list to match the old "no errors" return value. - """ - return [] - - -def _patched_deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: - """Backcompat classmethod for the old autorest ``Model.deserialize``. - - Accepts either a JSON-compatible dict/str or (when ``content_type`` is - XML) an XML string or ``ElementTree.Element``. - """ - if content_type and "xml" in content_type.lower(): - if isinstance(data, (bytes, str)): - data = ET.fromstring(data) # nosec - return cls(data) - return _deserialize(cls, data) - - -def _patched_from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument - content_type: Optional[str] = None, -) -> Any: - """Backcompat classmethod for the old autorest ``Model.from_dict``. - - ``key_extractors`` is accepted for signature compatibility but ignored; - the TypeSpec deserializer always uses REST-key mapping. - """ - if content_type and "xml" in content_type.lower(): - if isinstance(data, (bytes, str)): - data = ET.fromstring(data) # nosec - return cls(data) - return _deserialize(cls, data) - - -def _patched_enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument - """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. - - TypeSpec models already round-trip unknown properties through ``_data``. - """ - return None - - -def _patched_is_xml_model(cls) -> bool: - """Backcompat classmethod for the old autorest ``Model.is_xml_model``. - - Returns True when the model has an ``_xml`` class attribute (set by the - generator for models that serialize to/from XML). - """ - return bool(getattr(cls, "_xml", None)) - - -_Model.as_dict = _patched_as_dict -_Model.serialize = _patched_serialize -_Model.validate = _patched_validate -_Model.deserialize = classmethod(_patched_deserialize) -_Model.from_dict = classmethod(_patched_from_dict) -_Model.enable_additional_properties_sending = classmethod(_patched_enable_additional_properties_sending) -_Model.is_xml_model = classmethod(_patched_is_xml_model) - - -# --------------------------------------------------------------------------- -# 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. -# --------------------------------------------------------------------------- + @classmethod + def is_xml_model(cls) -> bool: + """Backcompat classmethod for the old autorest ``Model.is_xml_model``. -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 - - -_Model._asdict = _patched_namedtuple_asdict + Returns True when the model has an ``_xml`` class attribute (set by the + generator for models that serialize to/from XML). + """ + return bool(getattr(cls, "_xml", None)) __all__: List[str] = [] 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 84f73f292172..7aa2c314a769 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -15,6 +15,7 @@ return_context_and_deserialized, ) from ._shared.models import DictMixin +from ._generated.models._patch import _ModelBackCompatMixin from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -51,6 +52,12 @@ class RetentionPolicy(GeneratedRetentionPolicy): def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: if enabled and (days is None): raise ValueError("If policy is enabled, 'days' must be specified.") + self.serialize = _ModelBackCompatMixin.serialize + self.deserialize = _ModelBackCompatMixin.deserialize + self.from_dict = _ModelBackCompatMixin.from_dict + self.validate = _ModelBackCompatMixin.validate + self.enable_additional_properties_sending = _ModelBackCompatMixin.enable_additional_properties_sending + self.is_xml_model = _ModelBackCompatMixin.is_xml_model super().__init__(enabled=enabled, days=days) @classmethod @@ -90,6 +97,12 @@ class QueueAnalyticsLogging(GeneratedLogging): """The retention policy for the metrics.""" def __init__(self, **kwargs: Any) -> None: + self.serialize = _ModelBackCompatMixin.serialize + self.deserialize = _ModelBackCompatMixin.deserialize + self.from_dict = _ModelBackCompatMixin.from_dict + self.validate = _ModelBackCompatMixin.validate + self.enable_additional_properties_sending = _ModelBackCompatMixin.enable_additional_properties_sending + self.is_xml_model = _ModelBackCompatMixin.is_xml_model super().__init__( version=kwargs.get("version", "1.0"), delete=kwargs.get("delete", False), @@ -375,6 +388,12 @@ def __init__( # but we supported datetime and serialized it when passing the model through. (see set access policy) if isinstance(permission, QueueSasPermissions): permission = str(permission) + self.serialize = _ModelBackCompatMixin.serialize + self.deserialize = _ModelBackCompatMixin.deserialize + self.from_dict = _ModelBackCompatMixin.from_dict + self.validate = _ModelBackCompatMixin.validate + self.enable_additional_properties_sending = _ModelBackCompatMixin.enable_additional_properties_sending + self.is_xml_model = _ModelBackCompatMixin.is_xml_model super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] From 238147f41970bebb148049a5d904e2b88572f3df Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 19 May 2026 13:14:50 -0700 Subject: [PATCH 063/102] updating patches --- .../storage/queue/_generated/models/_patch.py | 42 +++++++++---------- .../azure/storage/queue/_models.py | 36 ++++++---------- 2 files changed, 32 insertions(+), 46 deletions(-) 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 db5f027a5879..6a607937d50c 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 @@ -16,8 +16,6 @@ from azure.core.serialization import as_attribute_dict -# do an _mixin and have the public models inherit from it - # --------------------------------------------------------------------------- # Backcompat shims for public methods that existed on the old autorest msrest models. # The TypeSpec-generated models inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not @@ -26,27 +24,27 @@ # here preserves backward compatibility for users. # --------------------------------------------------------------------------- -class _ModelBackCompatMixin: +def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + *, + exclude_readonly: bool = False, + **kwargs: Any, +) -> dict: + """Backcompat wrapper that returns Python attribute names (snake_case). + + Accepts both the old autorest signature (``keep_readonly``, + ``key_transformer``) and the new TypeSpec keyword-only + ``exclude_readonly`` parameter. ``key_transformer`` is accepted for + signature compatibility but ignored; keys are always remapped to + Python attribute names. + """ + effective_exclude = exclude_readonly or not keep_readonly + result = as_attribute_dict(self, exclude_readonly=effective_exclude) + return result - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument - *, - exclude_readonly: bool = False, - **kwargs: Any, - ) -> dict: - """Backcompat wrapper that returns Python attribute names (snake_case). - - Accepts both the old autorest signature (``keep_readonly``, - ``key_transformer``) and the new TypeSpec keyword-only - ``exclude_readonly`` parameter. ``key_transformer`` is accepted for - signature compatibility but ignored; keys are always remapped to - Python attribute names. - """ - effective_exclude = exclude_readonly or not keep_readonly - result = as_attribute_dict(self, exclude_readonly=effective_exclude) - return result +class _ModelBackCompatMixin: def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> dict: 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 7aa2c314a769..ebe4d0f1d6d9 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -15,7 +15,7 @@ return_context_and_deserialized, ) from ._shared.models import DictMixin -from ._generated.models._patch import _ModelBackCompatMixin +from ._generated.models._patch import _ModelBackCompatMixin, as_dict as _backcompat_as_dict from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -31,7 +31,7 @@ from datetime import datetime -class RetentionPolicy(GeneratedRetentionPolicy): +class RetentionPolicy(GeneratedRetentionPolicy, _ModelBackCompatMixin): """The retention policy which determines how long the associated data should persist. @@ -48,16 +48,12 @@ class RetentionPolicy(GeneratedRetentionPolicy): """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.""" + as_dict = _backcompat_as_dict + def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: if enabled and (days is None): raise ValueError("If policy is enabled, 'days' must be specified.") - self.serialize = _ModelBackCompatMixin.serialize - self.deserialize = _ModelBackCompatMixin.deserialize - self.from_dict = _ModelBackCompatMixin.from_dict - self.validate = _ModelBackCompatMixin.validate - self.enable_additional_properties_sending = _ModelBackCompatMixin.enable_additional_properties_sending - self.is_xml_model = _ModelBackCompatMixin.is_xml_model super().__init__(enabled=enabled, days=days) @classmethod @@ -73,7 +69,7 @@ def _from_generated(cls, generated: Any) -> Self: ) -class QueueAnalyticsLogging(GeneratedLogging): +class QueueAnalyticsLogging(GeneratedLogging, _ModelBackCompatMixin): """Azure Analytics Logging settings. All required parameters must be populated in order to send to Azure. @@ -95,14 +91,9 @@ class QueueAnalyticsLogging(GeneratedLogging): """Indicates whether all write requests should be logged.""" retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" + as_dict = _backcompat_as_dict def __init__(self, **kwargs: Any) -> None: - self.serialize = _ModelBackCompatMixin.serialize - self.deserialize = _ModelBackCompatMixin.deserialize - self.from_dict = _ModelBackCompatMixin.from_dict - self.validate = _ModelBackCompatMixin.validate - self.enable_additional_properties_sending = _ModelBackCompatMixin.enable_additional_properties_sending - self.is_xml_model = _ModelBackCompatMixin.is_xml_model super().__init__( version=kwargs.get("version", "1.0"), delete=kwargs.get("delete", False), @@ -128,7 +119,7 @@ def _from_generated(cls, generated: Any) -> Self: ), ) -class Metrics(GeneratedMetrics): +class Metrics(GeneratedMetrics, _ModelBackCompatMixin): """A summary of request statistics grouped by API in hour or minute aggregates. All required parameters must be populated in order to send to Azure. @@ -148,6 +139,7 @@ class Metrics(GeneratedMetrics): """Indicates whether metrics should generate summary statistics for called API operations.""" retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" + as_dict = _backcompat_as_dict def __init__(self, **kwargs: Any) -> None: super().__init__( @@ -174,7 +166,7 @@ def _from_generated(cls, generated: Any) -> Self: ) -class CorsRule(GeneratedCorsRule): +class CorsRule(GeneratedCorsRule, _ModelBackCompatMixin): """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 @@ -217,6 +209,7 @@ class CorsRule(GeneratedCorsRule): allowed_headers: str """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" + as_dict = _backcompat_as_dict def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: super().__init__( @@ -330,7 +323,7 @@ def from_string(cls, permission: str) -> Self: return parsed -class AccessPolicy(GenAccessPolicy): +class AccessPolicy(GenAccessPolicy, _ModelBackCompatMixin): """Access Policy class used by the set and get access policy methods. A stored access policy can specify the start time, expiry time, and @@ -377,6 +370,7 @@ class AccessPolicy(GenAccessPolicy): """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.""" + as_dict = _backcompat_as_dict def __init__( self, @@ -388,12 +382,6 @@ def __init__( # but we supported datetime and serialized it when passing the model through. (see set access policy) if isinstance(permission, QueueSasPermissions): permission = str(permission) - self.serialize = _ModelBackCompatMixin.serialize - self.deserialize = _ModelBackCompatMixin.deserialize - self.from_dict = _ModelBackCompatMixin.from_dict - self.validate = _ModelBackCompatMixin.validate - self.enable_additional_properties_sending = _ModelBackCompatMixin.enable_additional_properties_sending - self.is_xml_model = _ModelBackCompatMixin.is_xml_model super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] From 79bdc593b9de27bb508d3efd2a5e8b181aaee089 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 19 May 2026 14:04:40 -0700 Subject: [PATCH 064/102] pylint + black --- .../storage/queue/_generated/models/_patch.py | 16 ++++++---------- .../azure/storage/queue/_models.py | 14 +++++++------- 2 files changed, 13 insertions(+), 17 deletions(-) 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 6a607937d50c..b74e869bb767 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 @@ -10,7 +10,7 @@ """ # TODO: Waiting on Emitter Perf updates before updating these methods import xml.etree.ElementTree as ET -from typing import Any, Callable, List, Optional +from typing import Any, Callable, Dict, List, Optional from .._utils.model_base import Model as _deserialize from azure.core.serialization import as_attribute_dict @@ -24,6 +24,7 @@ # here preserves backward compatibility for users. # --------------------------------------------------------------------------- + def as_dict( self, keep_readonly: bool = True, @@ -31,7 +32,7 @@ def as_dict( *, exclude_readonly: bool = False, **kwargs: Any, -) -> dict: +) -> Dict[str, Any]: """Backcompat wrapper that returns Python attribute names (snake_case). Accepts both the old autorest signature (``keep_readonly``, @@ -44,10 +45,10 @@ def as_dict( result = as_attribute_dict(self, exclude_readonly=effective_exclude) return result -class _ModelBackCompatMixin: +class _ModelBackCompatMixin: - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> dict: + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> Dict[str, Any]: """Backcompat alias for the old autorest ``Model.serialize``. Equivalent to ``as_dict(keep_readonly=keep_readonly)`` with REST wire @@ -56,8 +57,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> dict: """ return as_attribute_dict(self, exclude_readonly=not keep_readonly) - - def validate(self) -> list: # pylint: disable=unused-argument + def validate(self) -> List[Any]: # pylint: disable=unused-argument """Backcompat no-op for the old autorest ``Model.validate``. TypeSpec models do not perform client-side validation; return an empty @@ -65,7 +65,6 @@ def validate(self) -> list: # pylint: disable=unused-argument """ return [] - @classmethod def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: """Backcompat classmethod for the old autorest ``Model.deserialize``. @@ -79,7 +78,6 @@ def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: return cls(data) return _deserialize(cls, data) - @classmethod def from_dict( cls, @@ -98,7 +96,6 @@ def from_dict( return cls(data) return _deserialize(cls, data) - @classmethod def enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. @@ -107,7 +104,6 @@ def enable_additional_properties_sending(cls) -> None: # pylint: disable=unused """ return None - @classmethod def is_xml_model(cls) -> bool: """Backcompat classmethod for the old autorest ``Model.is_xml_model``. 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 ebe4d0f1d6d9..ab49a0138623 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -49,7 +49,6 @@ class RetentionPolicy(GeneratedRetentionPolicy, _ModelBackCompatMixin): days: Optional[int] = None """Indicates the number of days that metrics or logging or soft-deleted data should be retained.""" as_dict = _backcompat_as_dict - def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: if enabled and (days is None): @@ -62,7 +61,7 @@ def _from_generated(cls, generated: Any) -> Self: return cls() # Handle XML Element by converting to generated model first if isinstance(generated, ET.Element): - generated = GeneratedRetentionPolicy(generated) # type: ignore[assignment,call-overload] + generated = GeneratedRetentionPolicy(generated) # type: ignore[assignment,call-overload] return cls( enabled=generated.enabled, days=generated.days, @@ -108,7 +107,7 @@ def _from_generated(cls, generated: Any) -> Self: return cls() # Handle XML Element by converting to generated model first if isinstance(generated, ET.Element): - generated = GeneratedLogging(generated) # type: ignore[assignment,call-overload] + generated = GeneratedLogging(generated) # type: ignore[assignment,call-overload] return cls( version=generated.version, delete=generated.delete, @@ -119,6 +118,7 @@ def _from_generated(cls, generated: Any) -> Self: ), ) + class Metrics(GeneratedMetrics, _ModelBackCompatMixin): """A summary of request statistics grouped by API in hour or minute aggregates. @@ -155,7 +155,7 @@ def _from_generated(cls, generated: Any) -> Self: return cls() # Handle XML Element by converting to generated model first if isinstance(generated, ET.Element): - generated = GeneratedMetrics(generated) # type: ignore[assignment,call-overload] + generated = GeneratedMetrics(generated) # type: ignore[assignment,call-overload] return cls( version=generated.version, enabled=generated.enabled, @@ -244,7 +244,7 @@ def _to_generated( def _from_generated(cls, generated: Any) -> Self: # Handle XML Element by converting to generated model first if isinstance(generated, ET.Element): - generated = GeneratedCorsRule(generated) # type: ignore[assignment,call-overload] + generated = GeneratedCorsRule(generated) # type: ignore[assignment,call-overload] return cls( [generated.allowed_origins], [generated.allowed_methods], @@ -378,11 +378,11 @@ def __init__( expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - # TODO: here AccessPolicy never took in a datetime + # TODO: here AccessPolicy never took in a datetime # but we supported datetime and serialized it when passing the model through. (see set access policy) if isinstance(permission, QueueSasPermissions): permission = str(permission) - super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] + super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] class QueueMessage(DictMixin): From b39ef80447810f0373a8281c0d75cbc7b8a58114 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 19 May 2026 14:10:28 -0700 Subject: [PATCH 065/102] type fix --- .../azure/storage/queue/_generated/models/_patch.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) 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 b74e869bb767..19efe26f5400 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 @@ -57,14 +57,6 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> Dict[str, Any """ return as_attribute_dict(self, exclude_readonly=not keep_readonly) - def validate(self) -> List[Any]: # pylint: disable=unused-argument - """Backcompat no-op for the old autorest ``Model.validate``. - - TypeSpec models do not perform client-side validation; return an empty - list to match the old "no errors" return value. - """ - return [] - @classmethod def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: """Backcompat classmethod for the old autorest ``Model.deserialize``. @@ -82,7 +74,7 @@ def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: def from_dict( cls, data: Any, - key_extractors: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, # pylint: disable=unused-argument content_type: Optional[str] = None, ) -> Any: """Backcompat classmethod for the old autorest ``Model.from_dict``. From b82b71d4ec83c162dc1b929c88981db30199f7c3 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 19 May 2026 15:11:43 -0700 Subject: [PATCH 066/102] verifytypes --- .../azure/storage/queue/_generated/models/_patch.py | 5 +---- .../azure/storage/queue/_models.py | 12 ++++++------ 2 files changed, 7 insertions(+), 10 deletions(-) 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 19efe26f5400..05d97fad5b16 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 @@ -29,8 +29,6 @@ def as_dict( self, keep_readonly: bool = True, key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument - *, - exclude_readonly: bool = False, **kwargs: Any, ) -> Dict[str, Any]: """Backcompat wrapper that returns Python attribute names (snake_case). @@ -41,8 +39,7 @@ def as_dict( signature compatibility but ignored; keys are always remapped to Python attribute names. """ - effective_exclude = exclude_readonly or not keep_readonly - result = as_attribute_dict(self, exclude_readonly=effective_exclude) + result = as_attribute_dict(self, exclude_readonly=not keep_readonly) return result 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 ab49a0138623..2f2d7cda9b38 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -48,7 +48,7 @@ class RetentionPolicy(GeneratedRetentionPolicy, _ModelBackCompatMixin): """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.""" - as_dict = _backcompat_as_dict + as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: if enabled and (days is None): @@ -90,7 +90,7 @@ class QueueAnalyticsLogging(GeneratedLogging, _ModelBackCompatMixin): """Indicates whether all write requests should be logged.""" retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" - as_dict = _backcompat_as_dict + as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] def __init__(self, **kwargs: Any) -> None: super().__init__( @@ -139,7 +139,7 @@ class Metrics(GeneratedMetrics, _ModelBackCompatMixin): """Indicates whether metrics should generate summary statistics for called API operations.""" retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" - as_dict = _backcompat_as_dict + as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] def __init__(self, **kwargs: Any) -> None: super().__init__( @@ -209,7 +209,7 @@ class CorsRule(GeneratedCorsRule, _ModelBackCompatMixin): allowed_headers: str """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" - as_dict = _backcompat_as_dict + as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: super().__init__( @@ -297,7 +297,7 @@ def __init__( + ("p" if self.process else "") ) - def __str__(self): + def __str__(self) -> str: return self._str @classmethod @@ -370,7 +370,7 @@ class AccessPolicy(GenAccessPolicy, _ModelBackCompatMixin): """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.""" - as_dict = _backcompat_as_dict + as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] def __init__( self, From 88f7c100cfb0e5e79a6f977aeccf61fbd6810c37 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 20 May 2026 08:32:29 -0700 Subject: [PATCH 067/102] typing for verifytypes --- .../azure/storage/queue/_models.py | 50 +++++++++++++++++-- 1 file changed, 45 insertions(+), 5 deletions(-) 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 2f2d7cda9b38..b853b7930117 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -48,7 +48,15 @@ class RetentionPolicy(GeneratedRetentionPolicy, _ModelBackCompatMixin): """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.""" - as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model.""" + return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: if enabled and (days is None): @@ -90,7 +98,15 @@ class QueueAnalyticsLogging(GeneratedLogging, _ModelBackCompatMixin): """Indicates whether all write requests should be logged.""" retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" - as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model.""" + return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] def __init__(self, **kwargs: Any) -> None: super().__init__( @@ -139,7 +155,15 @@ class Metrics(GeneratedMetrics, _ModelBackCompatMixin): """Indicates whether metrics should generate summary statistics for called API operations.""" retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" - as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model.""" + return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] def __init__(self, **kwargs: Any) -> None: super().__init__( @@ -209,7 +233,15 @@ class CorsRule(GeneratedCorsRule, _ModelBackCompatMixin): allowed_headers: str """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" - as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model.""" + return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: super().__init__( @@ -370,7 +402,15 @@ class AccessPolicy(GenAccessPolicy, _ModelBackCompatMixin): """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.""" - as_dict = _backcompat_as_dict # pyright: ignore[reportIncompatibleMethodOverride] + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model.""" + return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] def __init__( self, From 32af44c8237be38808ea7d7bab88dab620cb933e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 20 May 2026 09:45:17 -0700 Subject: [PATCH 068/102] pylint --- .../azure/storage/queue/_models.py | 85 ++++++++++++++++--- 1 file changed, 75 insertions(+), 10 deletions(-) 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 b853b7930117..70e1ba4b6590 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -55,8 +55,21 @@ def as_dict( key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, **kwargs: Any, ) -> Dict[str, Any]: - """Return a dict representation of the model.""" - return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: if enabled and (days is None): @@ -105,8 +118,21 @@ def as_dict( key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, **kwargs: Any, ) -> Dict[str, Any]: - """Return a dict representation of the model.""" - return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] def __init__(self, **kwargs: Any) -> None: super().__init__( @@ -162,8 +188,21 @@ def as_dict( key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, **kwargs: Any, ) -> Dict[str, Any]: - """Return a dict representation of the model.""" - return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] def __init__(self, **kwargs: Any) -> None: super().__init__( @@ -240,8 +279,21 @@ def as_dict( key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, **kwargs: Any, ) -> Dict[str, Any]: - """Return a dict representation of the model.""" - return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: super().__init__( @@ -409,8 +461,21 @@ def as_dict( key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, **kwargs: Any, ) -> Dict[str, Any]: - """Return a dict representation of the model.""" - return _backcompat_as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[return-value] + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] def __init__( self, From ccfbe915950c7d09a079a84d76aa30ee8c43f5fb Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 21 May 2026 16:00:54 -0700 Subject: [PATCH 069/102] removing temp to run tests --- sdk/storage/azure-storage-queue/dev_requirements.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/dev_requirements.txt b/sdk/storage/azure-storage-queue/dev_requirements.txt index b8770ca0db3a..c9cf9f09f32d 100644 --- a/sdk/storage/azure-storage-queue/dev_requirements.txt +++ b/sdk/storage/azure-storage-queue/dev_requirements.txt @@ -1,6 +1,5 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core ../../identity/azure-identity -../azure-storage-extensions azure-mgmt-storage==20.1.0 aiohttp>=3.13.5 From f65fe49e14cf40802db92bd3ed81336116463a9e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 22 May 2026 08:52:06 -0700 Subject: [PATCH 070/102] Revert "removing temp to run tests" This reverts commit ccfbe915950c7d09a079a84d76aa30ee8c43f5fb. --- sdk/storage/azure-storage-queue/dev_requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/storage/azure-storage-queue/dev_requirements.txt b/sdk/storage/azure-storage-queue/dev_requirements.txt index c9cf9f09f32d..b8770ca0db3a 100644 --- a/sdk/storage/azure-storage-queue/dev_requirements.txt +++ b/sdk/storage/azure-storage-queue/dev_requirements.txt @@ -1,5 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core ../../identity/azure-identity +../azure-storage-extensions azure-mgmt-storage==20.1.0 aiohttp>=3.13.5 From b77134c1b2872075255ae1ffa23afe68d6db293c Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 22 May 2026 09:02:20 -0700 Subject: [PATCH 071/102] regen with newest emitter --- .../apiview-properties.json | 3 +- .../azure/storage/queue/_generated/_client.py | 12 +- .../queue/_generated/_configuration.py | 5 +- .../azure/storage/queue/_generated/_patch.py | 1 + .../queue/_generated/_utils/model_base.py | 400 +++++++++++++++--- .../queue/_generated/_utils/serialization.py | 29 +- .../storage/queue/_generated/aio/_client.py | 12 +- .../queue/_generated/aio/_configuration.py | 5 +- .../storage/queue/_generated/aio/_patch.py | 1 + .../queue/_generated/aio/operations/_patch.py | 1 - .../queue/_generated/models/_models.py | 69 ++- .../storage/queue/_generated/models/_patch.py | 2 +- .../queue/_generated/operations/_patch.py | 1 - .../azure/storage/queue/_queue_client.py | 12 +- .../azure/storage/queue/_shared/constants.py | 1 - .../storage/queue/_shared/request_handlers.py | 1 - .../queue/_shared/response_handlers.py | 1 - .../azure/storage/queue/_shared/uploads.py | 1 - .../storage/queue/aio/_queue_client_async.py | 12 +- .../azure-storage-queue/pyproject.toml | 5 +- 20 files changed, 482 insertions(+), 92 deletions(-) diff --git a/sdk/storage/azure-storage-queue/apiview-properties.json b/sdk/storage/azure-storage-queue/apiview-properties.json index 056dcf5fc299..7e205caa7b6e 100644 --- a/sdk/storage/azure-storage-queue/apiview-properties.json +++ b/sdk/storage/azure-storage-queue/apiview-properties.json @@ -60,5 +60,6 @@ "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" - } + }, + "CrossLanguageVersion": "52f8059a5768" } \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py index 2335c04700ae..02c93c2b9c4e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, TYPE_CHECKING -from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies @@ -18,6 +18,11 @@ from ._utils.serialization import Deserializer, Serializer from .operations import QueueOperations, ServiceOperations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: from azure.core.credentials import TokenCredential @@ -35,8 +40,9 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword :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. + are "2026-04-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 e53f7601f7a3..f6f1a7911573 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 @@ -28,8 +28,9 @@ class QueuesClientConfiguration: # pylint: disable=too-many-instance-attributes :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. + are "2026-04-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 3891e6290098..7f0a4ff0259d 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 @@ -7,6 +7,7 @@ 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 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 index eef4e52ed1a0..bd5b9caf1022 100644 --- 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 @@ -23,14 +23,19 @@ 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 +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -585,6 +590,239 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return _serialize(value, rf._format) +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + 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 + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated @@ -595,11 +833,7 @@ 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 - } + dict_to_pass: dict[str, typing.Any] = {} if args: if isinstance(args[0], ET.Element): dict_to_pass.update(self._init_from_xml(args[0])) @@ -619,9 +853,19 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if v is not None } ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) - def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + 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. @@ -629,53 +873,89 @@ def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: :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: + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + 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, items) - elif not rf._is_optional: + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _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 + item = element.find(xml_name) + if item is not None: 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) + result[rf._rest_name] = _deserialize(rf._type, item) # rest thing is additional properties for e in element: @@ -712,6 +992,9 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf for attr, rf in cls._attr_to_rest_field.items() } + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -1096,6 +1379,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, original_tsp_name: typing.Optional[str] = None, ): self._type = type @@ -1109,6 +1393,7 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._deserializer = deserializer self._original_tsp_name = original_tsp_name @property @@ -1129,7 +1414,10 @@ 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) + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None if item is None: return item if self._is_model: @@ -1142,7 +1430,11 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # 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) + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + 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 @@ -1188,6 +1480,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( @@ -1198,6 +1491,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + deserializer=deserializer, original_tsp_name=original_tsp_name, ) @@ -1432,6 +1726,8 @@ def _deserialize_xml( value: str, ) -> typing.Any: element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) return _deserialize(deserializer, element) 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 81ec1de5922b..a088671e9c51 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 @@ -39,11 +39,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore -from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") JSON = MutableMapping[str, Any] @@ -1401,7 +1405,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """Call the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. @@ -1411,6 +1415,27 @@ def __call__(self, target_obj, response_data, content_type=None): :return: Deserialized object. :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py index 5ed74d3735ac..6a06b1a9614d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, Awaitable, TYPE_CHECKING -from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies @@ -18,6 +18,11 @@ from ._configuration import QueuesClientConfiguration from .operations import QueueOperations, ServiceOperations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential @@ -35,8 +40,9 @@ class QueuesClient: # pylint: disable=client-accepts-api-version-keyword :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. + are "2026-04-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 bb5eb3fe726d..935c94b212bc 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 @@ -28,8 +28,9 @@ class QueuesClientConfiguration: # pylint: disable=too-many-instance-attributes :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. + are "2026-04-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 9e470fc4f1b9..9ea6d5f939a9 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 @@ -7,6 +7,7 @@ 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 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 87676c65a8f0..ea765788358a 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 @@ -8,7 +8,6 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ - __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py index 21f2e26e9769..39971f3b13ad 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models.py @@ -9,9 +9,19 @@ # pylint: disable=useless-super-delegation import datetime +import functools from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload -from .._utils.model_base import Model as _Model, rest_field +from .._utils.model_base import ( + Model as _Model, + _xml_deser_bool, + _xml_deser_datetime_rfc7231, + _xml_deser_enum_or_str, + _xml_deser_int, + _xml_deser_str, + rest_field, +) +from ._enums import GeoReplicationStatus, StorageErrorCode if TYPE_CHECKING: from .. import models as _models @@ -31,16 +41,19 @@ class AccessPolicy(_Model): start: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The date-time the policy is active.""" expiry: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The date-time the policy expires.""" permission: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Permission", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The permissions for the policy.""" @@ -85,30 +98,35 @@ class CorsRule(_Model): name="allowedOrigins", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "AllowedOrigins", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_int, ) """The maximum age in seconds. Required.""" @@ -165,6 +183,7 @@ class Error(_Model): code: Optional[Union[str, "_models.StorageErrorCode"]] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Code", "text": False, "unwrapped": False}, + deserializer=functools.partial(_xml_deser_enum_or_str, StorageErrorCode), ) """The error code. Known values are: \"AccountAlreadyExists\", \"AccountBeingCreated\", \"AccountIsDisabled\", \"AuthenticationFailed\", \"AuthorizationFailure\", @@ -188,6 +207,7 @@ class Error(_Model): message: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Message", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The error message.""" @@ -227,6 +247,7 @@ class GeoReplication(_Model): status: Union[str, "_models.GeoReplicationStatus"] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Status", "text": False, "unwrapped": False}, + deserializer=functools.partial(_xml_deser_enum_or_str, GeoReplicationStatus), ) """The status of the secondary location. Required. Known values are: \"live\", \"bootstrap\", and \"unavailable\".""" @@ -235,6 +256,7 @@ class GeoReplication(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "LastSyncTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """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 @@ -275,17 +297,20 @@ class KeyInfo(_Model): start: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The delegated user tenant ID in Entra ID.""" @@ -368,22 +393,26 @@ class ListQueuesResponse(_Model): name="serviceEndpoint", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": True, "name": "ServiceEndpoint", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The service endpoint. Required.""" prefix: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Prefix", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """Identifies the current position in the list queues operation.""" max_results: int = rest_field( name="maxResults", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MaxResults", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """The max results. Required.""" queue_items: Optional[list["_models.QueueItem"]] = rest_field( @@ -396,6 +425,7 @@ class ListQueuesResponse(_Model): name="nextMarker", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """Identifies the portion of the list of queues to be returned with the next listing operation. Required.""" @@ -443,21 +473,25 @@ class Logging(_Model): version: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_bool, ) """Whether write operation is logged. Required.""" retention_policy: "_models.RetentionPolicy" = rest_field( @@ -507,17 +541,20 @@ class Metrics(_Model): version: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_bool, ) """Whether to include API in the metrics.""" retention_policy: Optional["_models.RetentionPolicy"] = rest_field( @@ -570,6 +607,7 @@ class PeekedMessage(_Model): name="messageId", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The ID of the message. Required.""" insertion_time: datetime.datetime = rest_field( @@ -577,6 +615,7 @@ class PeekedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "InsertionTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The time the message was inserted into the queue. Required.""" expiration_time: datetime.datetime = rest_field( @@ -584,18 +623,21 @@ class PeekedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "ExpirationTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_str, ) """The content of the message. Required.""" @@ -670,6 +712,7 @@ class QueueItem(_Model): name: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Name", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The name of the queue. Required.""" metadata: Optional[dict[str, str]] = rest_field( @@ -710,6 +753,7 @@ class QueueMessage(_Model): name="messageText", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageText", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The content of the message. Required.""" @@ -852,6 +896,7 @@ class ReceivedMessage(_Model): name="messageId", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The ID of the message. Required.""" insertion_time: datetime.datetime = rest_field( @@ -859,6 +904,7 @@ class ReceivedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "InsertionTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The time the message was inserted into the queue. Required.""" expiration_time: datetime.datetime = rest_field( @@ -866,12 +912,14 @@ class ReceivedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "ExpirationTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """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}, + deserializer=_xml_deser_str, ) """An opaque value required to delete the message. If deletion fails using this PopReceipt then the message has been dequeued by another client. Required.""" @@ -880,18 +928,21 @@ class ReceivedMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "TimeNextVisible", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_str, ) """The content of the message. Required.""" @@ -968,11 +1019,13 @@ class RetentionPolicy(_Model): enabled: bool = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_int, ) """The number of days to retain the logs.""" @@ -1019,6 +1072,7 @@ class SentMessage(_Model): name="messageId", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MessageId", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The ID of the message. Required.""" insertion_time: datetime.datetime = rest_field( @@ -1026,6 +1080,7 @@ class SentMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "InsertionTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The time the message was inserted into the queue. Required.""" expiration_time: datetime.datetime = rest_field( @@ -1033,12 +1088,14 @@ class SentMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "ExpirationTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """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}, + deserializer=_xml_deser_str, ) """An opaque value required to delete the message. If deletion fails using this PopReceipt then the message has been dequeued by another client. Required.""" @@ -1047,6 +1104,7 @@ class SentMessage(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "TimeNextVisible", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The time that the message will again become visible in the queue. Required.""" @@ -1086,6 +1144,7 @@ class SignedIdentifier(_Model): id: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Id", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The unique ID for the signed identifier. Required.""" access_policy: "_models.AccessPolicy" = rest_field( @@ -1183,47 +1242,55 @@ class UserDelegationKey(_Model): name="signedOid", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "SignedOid", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The Entra ID 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}, + deserializer=_xml_deser_str, ) """The Entra ID 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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The service version used when creating 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}, + deserializer=_xml_deser_str, ) """The delegated user tenant ID in Entra ID. Return if DelegatedUserTid is specified.""" value: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Value", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The key as a base64 string. Required.""" 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 05d97fad5b16..22c939a160b7 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 @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + # TODO: Waiting on Emitter Perf updates before updating these methods import xml.etree.ElementTree as ET from typing import Any, Callable, Dict, List, Optional @@ -15,7 +16,6 @@ from .._utils.model_base import Model as _deserialize from azure.core.serialization import as_attribute_dict - # --------------------------------------------------------------------------- # Backcompat shims for public methods that existed on the old autorest msrest models. # The TypeSpec-generated models inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not 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 87676c65a8f0..ea765788358a 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 @@ -8,7 +8,6 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ - __all__: list[str] = [] # Add all objects you want publicly available to users at this package level 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 c3aedc31c8fc..49d8d6d1cf46 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 @@ -638,12 +638,10 @@ def send_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn( - "TypeError when calling message_encode_policy.configure. \ + warnings.warn("TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version." - ) + Retrying without encryption_version.") self._message_encode_policy.configure( require_encryption=self.require_encryption, key_encryption_key=self.key_encryption_key, @@ -939,12 +937,10 @@ def update_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn( - "TypeError when calling message_encode_policy.configure. \ + warnings.warn("TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version." - ) + Retrying without encryption_version.") self._message_encode_policy.configure( self.require_encryption, self.key_encryption_key, 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 bd6ff89771be..c294d80e0687 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,7 +6,6 @@ from .._serialize import _SUPPORTED_API_VERSIONS - X_MS_VERSION = _SUPPORTED_API_VERSIONS[-1] # Connection defaults 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 b23f65859690..699635565b18 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,7 +12,6 @@ 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 19f9d1086c66..24855e202642 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 @@ -22,7 +22,6 @@ 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__) 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 8eacc59d1a27..83d7d730be36 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,7 +16,6 @@ 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." 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 98dc37871edd..9b43ee0f452b 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 @@ -653,12 +653,10 @@ async def send_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn( - "TypeError when calling message_encode_policy.configure. \ + warnings.warn("TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version." - ) + Retrying without encryption_version.") self._message_encode_policy.configure( require_encryption=self.require_encryption, key_encryption_key=self.key_encryption_key, @@ -944,12 +942,10 @@ async def update_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn( - "TypeError when calling message_encode_policy.configure. \ + warnings.warn("TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version." - ) + Retrying without encryption_version.") self._message_encode_policy.configure( self.require_encryption, self.key_encryption_key, diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index 03e25174e0c7..9a20903de639 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -21,13 +21,12 @@ classifiers = [ "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" +requires-python = ">=3.10" keywords = ["azure", "azure sdk"] dependencies = [ @@ -42,7 +41,7 @@ dynamic = [ [project.optional-dependencies] aio = [ - "azure-core[aio]>=1.38.3", + "azure-core[aio]>=1.38.3", ] [project.urls] From b6a3517f27c756f6c2726e6027b50ce09b7a6e6f Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 26 May 2026 13:24:15 -0700 Subject: [PATCH 072/102] reformat pause --- .../storage/queue/_shared/authentication.py | 15 +++- .../storage/queue/_shared/base_client.py | 83 ++++++++++++++++--- .../queue/_shared/base_client_async.py | 63 ++++++++++++-- .../azure/storage/queue/_shared/constants.py | 4 +- .../azure/storage/queue/_shared/models.py | 5 +- .../azure/storage/queue/_shared/parser.py | 5 +- .../azure/storage/queue/_shared/policies.py | 34 ++++++-- .../storage/queue/_shared/policies_async.py | 21 ++++- .../queue/_shared/response_handlers.py | 26 ++++-- .../azure/storage/queue/_shared/uploads.py | 12 ++- .../storage/queue/_shared/uploads_async.py | 11 ++- 11 files changed, 234 insertions(+), 45 deletions(-) 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 f778dc71eec4..cdbeeace2427 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,7 +16,9 @@ pass try: - from azure.core.pipeline.transport import AioHttpTransport # pylint: disable=non-abstract-transport-import + from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import + AioHttpTransport, + ) except ImportError: AioHttpTransport = None @@ -152,9 +154,16 @@ 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(getattr(request.context.transport, "_transport", None), "_transport", None), + getattr(request.context.transport, "_transport", None), + AioHttpTransport, + ) + or isinstance( + 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 fb62552c15b4..86734de7a20b 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,7 +17,11 @@ ) 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 @@ -64,7 +68,10 @@ if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse # pylint: disable=C4756 + from azure.core.pipeline.transport import ( # pylint: disable=C4756 + HttpRequest, + HttpResponse, + ) _LOGGER = logging.getLogger(__name__) _SERVICE_PARAMS = { @@ -167,7 +174,12 @@ def __init__( if not self._hosts: if kwargs.get("secondary_hostname"): secondary_hostname = kwargs["secondary_hostname"] - self._hosts = {LocationMode.PRIMARY: primary_hostname, LocationMode.SECONDARY: 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._sdk_moniker = f"storage-{service}/{VERSION}" self._config, self._pipeline = self._create_pipeline(self.credential, sdk_moniker=self._sdk_moniker, **kwargs) @@ -261,12 +273,27 @@ 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: @@ -288,7 +315,13 @@ 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]: @@ -384,7 +417,9 @@ 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) @@ -421,7 +456,14 @@ 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): @@ -441,12 +483,28 @@ 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(";")] @@ -460,7 +518,10 @@ 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 d3403af8eaae..993c2cfb354f 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,7 +49,10 @@ from .._shared_access_signature import _is_credential_sastoken if TYPE_CHECKING: - from azure.core.pipeline.transport import HttpRequest, HttpResponse # pylint: disable=C4756 + from azure.core.pipeline.transport import ( # pylint: disable=C4756 + HttpRequest, + HttpResponse, + ) _LOGGER = logging.getLogger(__name__) _SERVICE_PARAMS = { @@ -66,12 +69,27 @@ 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: @@ -92,12 +110,22 @@ 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"): @@ -201,12 +229,28 @@ 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(";")] @@ -220,7 +264,10 @@ 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 c294d80e0687..c9c2ba8f74d0 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 @@ -13,9 +13,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 aa900a4f404a..51565b636f6c 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,7 +292,10 @@ 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 7755398d8090..f16230c9d702 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,7 +53,10 @@ 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 7e225a5a362c..f4f602d1c669 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,7 +72,12 @@ 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 @@ -264,7 +269,16 @@ 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:") @@ -660,11 +674,16 @@ 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 @@ -674,7 +693,12 @@ 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 a7891ec66456..e1d13b1a83fa 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,7 +11,10 @@ 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 @@ -167,11 +170,16 @@ 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 @@ -181,7 +189,12 @@ 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/response_handlers.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/response_handlers.py index 24855e202642..4841b32ebda6 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,4 +1,3 @@ -# 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 @@ -80,7 +79,10 @@ 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 @@ -96,7 +98,12 @@ 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") @@ -118,7 +125,8 @@ 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)} @@ -135,9 +143,15 @@ 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, 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 83d7d730be36..4da915577cdc 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 @@ -112,7 +112,12 @@ 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): @@ -165,7 +170,10 @@ 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.") 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 35787ea27ac5..371525bdedc2 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,7 +189,10 @@ 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 @@ -435,7 +438,11 @@ 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 From b3f5d73507c5e0ec3426094051689176fa9625aa Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 26 May 2026 13:46:10 -0700 Subject: [PATCH 073/102] update wrap even though not a queue thing --- .../azure/storage/queue/_shared/policies.py | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) 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..f98fd2a9504f 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 @@ -473,17 +473,25 @@ def _validate_content_response( # Raises exception if missing content_length = int(response.http_response.headers[CONTENT_LENGTH_HEADER]) - # Patch response to return response iterator wrapped in structured message decoder - original_stream_download = response.http_response.stream_download - - def wrapped_stream_download(*args, **kwargs): - iterator = original_stream_download(*args, **kwargs) - decoder = decoder_cls(iterator, content_length, block_size=DATA_BLOCK_SIZE) - decoder.request = iterator.request # type: ignore - decoder.response = iterator.response # type: ignore - return decoder - - response.http_response.stream_download = wrapped_stream_download + def _make_wrapper(original): + def wrapped(*args, **kwargs): + iterator = original(*args, **kwargs) + decoder = decoder_cls(iterator, content_length, block_size=DATA_BLOCK_SIZE) + if hasattr(iterator, "request"): + decoder.request = iterator.request # type: ignore + if hasattr(iterator, "response"): + decoder.response = iterator.response # type: ignore + return decoder + return wrapped + + # Patch response to return response iterator wrapped in structured message decoder. + # TypeSpec-generated code calls iter_bytes()/iter_raw() instead of stream_download(). + if hasattr(response.http_response, "iter_bytes"): + response.http_response.iter_bytes = _make_wrapper(response.http_response.iter_bytes) + if hasattr(response.http_response, "iter_raw"): + response.http_response.iter_raw = _make_wrapper(response.http_response.iter_raw) + if hasattr(response.http_response, "stream_download"): + response.http_response.stream_download = _make_wrapper(response.http_response.stream_download) class StorageContentValidation(SansIOHTTPPolicy): From fd3edaa87d23b576dd3c6c0901af71f4698e3dc2 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 26 May 2026 13:55:48 -0700 Subject: [PATCH 074/102] try to fix format --- .../azure/storage/queue/_queue_client.py | 18 +++++++++++++----- .../storage/queue/_queue_service_client.py | 6 +++++- .../azure/storage/queue/_shared/policies.py | 1 + .../storage/queue/aio/_queue_client_async.py | 18 +++++++++++++----- .../queue/aio/_queue_service_client_async.py | 13 +++++++++++-- 5 files changed, 43 insertions(+), 13 deletions(-) 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 49d8d6d1cf46..b100c4e40323 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 @@ -134,7 +134,11 @@ 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, version=get_api_version(api_version), 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: @@ -638,10 +642,12 @@ def send_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn("TypeError when calling message_encode_policy.configure. \ + warnings.warn( + "TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version.") + Retrying without encryption_version." + ) self._message_encode_policy.configure( require_encryption=self.require_encryption, key_encryption_key=self.key_encryption_key, @@ -937,10 +943,12 @@ def update_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn("TypeError when calling message_encode_policy.configure. \ + warnings.warn( + "TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version.") + Retrying without encryption_version." + ) self._message_encode_policy.configure( self.require_encryption, self.key_encryption_key, 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 00aa98bda6e2..c8cc2f66f797 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 @@ -133,7 +133,11 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), 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: 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 f98fd2a9504f..3755660cc4c6 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 @@ -482,6 +482,7 @@ def wrapped(*args, **kwargs): if hasattr(iterator, "response"): decoder.response = iterator.response # type: ignore return decoder + return wrapped # Patch response to return response iterator wrapped in structured message decoder. 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 9b43ee0f452b..5cd444037436 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 @@ -146,7 +146,11 @@ 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, version=get_api_version(api_version), pipeline=self._pipeline) + self._client = AzureQueueStorage( + self.url, + version=get_api_version(api_version), + pipeline=self._pipeline, + ) self._loop = loop self._configure_encryption(kwargs) @@ -653,10 +657,12 @@ async def send_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn("TypeError when calling message_encode_policy.configure. \ + warnings.warn( + "TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version.") + Retrying without encryption_version." + ) self._message_encode_policy.configure( require_encryption=self.require_encryption, key_encryption_key=self.key_encryption_key, @@ -942,10 +948,12 @@ async def update_message( encryption_version=self.encryption_version, ) except TypeError: - warnings.warn("TypeError when calling message_encode_policy.configure. \ + warnings.warn( + "TypeError when calling message_encode_policy.configure. \ It is likely missing the encryption_version parameter. \ Consider updating your encryption information/implementation. \ - Retrying without encryption_version.") + Retrying without encryption_version." + ) self._message_encode_policy.configure( self.require_encryption, self.key_encryption_key, 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 4340adad3871..c6a80c2e9149 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 @@ -19,7 +19,12 @@ from .._encryption import StorageEncryptionMixin 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 .._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 @@ -128,7 +133,11 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) + self._client = AzureQueueStorage( + self.url, + version=get_api_version(api_version), + pipeline=self._pipeline, + ) self._loop = loop self._configure_encryption(kwargs) From 341c1f73429f30754d74faf54b1fc67170ed7afa Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 26 May 2026 14:34:19 -0700 Subject: [PATCH 075/102] ran black --- .../azure/storage/queue/_queue_service_client.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) 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 c8cc2f66f797..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 @@ -133,11 +133,7 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage( - self.url, - version=get_api_version(api_version), - 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: From b082826ebf999e1828112fcdb0741bc22bc64789 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 27 May 2026 10:58:42 -0700 Subject: [PATCH 076/102] regen with new emitter --- sdk/storage/azure-storage-queue/apiview-properties.json | 2 +- .../azure/storage/queue/_generated/aio/operations/_patch.py | 1 + .../azure/storage/queue/_generated/operations/_patch.py | 1 + .../azure/storage/queue/_generated/py.typed | 1 - .../azure/storage/queue/_shared/response_handlers.py | 1 + sdk/storage/azure-storage-queue/tsp-location.yaml | 4 ++-- 6 files changed, 6 insertions(+), 4 deletions(-) delete mode 100644 sdk/storage/azure-storage-queue/azure/storage/queue/_generated/py.typed diff --git a/sdk/storage/azure-storage-queue/apiview-properties.json b/sdk/storage/azure-storage-queue/apiview-properties.json index 7e205caa7b6e..d46f9ede0085 100644 --- a/sdk/storage/azure-storage-queue/apiview-properties.json +++ b/sdk/storage/azure-storage-queue/apiview-properties.json @@ -61,5 +61,5 @@ "azure.storage.queue.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage", "azure.storage.queue.aio.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage" }, - "CrossLanguageVersion": "52f8059a5768" + "CrossLanguageVersion": "93cf2ffb7d42" } \ No newline at end of file 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 ea765788358a..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 @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level 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 ea765788358a..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 @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + __all__: list[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/py.typed b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file 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 4841b32ebda6..a5039c487fbb 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 diff --git a/sdk/storage/azure-storage-queue/tsp-location.yaml b/sdk/storage/azure-storage-queue/tsp-location.yaml index 487ac7889ffb..f925a9401a4a 100644 --- a/sdk/storage/azure-storage-queue/tsp-location.yaml +++ b/sdk/storage/azure-storage-queue/tsp-location.yaml @@ -1,4 +1,4 @@ -directory: specification/storage/Microsoft.QueueStorage -commit: 62b449d4f801b4db64038829f51fa546fe89ee5d +directory: specification/storage/data-plane/QueueStorage +commit: a0af72e72c4467678f58e404670c18a3f00ce2e1 repo: Azure/azure-rest-api-specs additionalDirectories: From 5a05042deff6120fd8129fa52729f5b6cce0f9d3 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 4 Jun 2026 12:30:17 -0700 Subject: [PATCH 077/102] py3.14 and models from regen --- .../azure/storage/queue/_models.py | 77 +++++++++++++++++-- .../azure-storage-queue/pyproject.toml | 1 + 2 files changed, 72 insertions(+), 6 deletions(-) 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 70e1ba4b6590..957da5e27785 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -7,7 +7,7 @@ import sys import xml.etree.ElementTree as ET -from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING, Union +from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, TYPE_CHECKING, Union, overload from azure.core.exceptions import HttpResponseError from azure.core.paging import PageIterator from ._shared.response_handlers import ( @@ -71,7 +71,16 @@ def as_dict( **kwargs, ) # type: ignore[return-value] - def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: + @overload + def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: ... + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: + if args and isinstance(args[0], (ET.Element, dict)): + super().__init__(*args, **kwargs) + return + enabled = args[0] if args else kwargs.get("enabled", False) + days = args[1] if len(args) > 1 else kwargs.get("days", None) if enabled and (days is None): raise ValueError("If policy is enabled, 'days' must be specified.") super().__init__(enabled=enabled, days=days) @@ -134,7 +143,22 @@ def as_dict( **kwargs, ) # type: ignore[return-value] - def __init__(self, **kwargs: Any) -> None: + @overload + def __init__( + self, + *, + version: str = "1.0", + delete: bool = False, + read: bool = False, + write: bool = False, + retention_policy: Optional[RetentionPolicy] = None, + ) -> None: ... + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: + if args and isinstance(args[0], (ET.Element, dict)): + super().__init__(*args, **kwargs) + return super().__init__( version=kwargs.get("version", "1.0"), delete=kwargs.get("delete", False), @@ -204,7 +228,21 @@ def as_dict( **kwargs, ) # type: ignore[return-value] - def __init__(self, **kwargs: Any) -> None: + @overload + def __init__( + self, + *, + version: str = "1.0", + enabled: bool = False, + include_apis: Optional[bool] = None, + retention_policy: Optional[RetentionPolicy] = None, + ) -> None: ... + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: + if args and isinstance(args[0], (ET.Element, dict)): + super().__init__(*args, **kwargs) + return super().__init__( version=kwargs.get("version", "1.0"), enabled=kwargs.get("enabled", False), @@ -295,7 +333,24 @@ def as_dict( **kwargs, ) # type: ignore[return-value] - def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: + @overload + def __init__( + self, + allowed_origins: List[str], + allowed_methods: List[str], + *, + allowed_headers: Optional[List[str]] = None, + exposed_headers: Optional[List[str]] = None, + max_age_in_seconds: int = 0, + ) -> None: ... + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: + if args and isinstance(args[0], (ET.Element, dict)): + super().__init__(*args, **kwargs) + return + allowed_origins = args[0] if args else kwargs.pop("allowed_origins") + allowed_methods = args[1] if len(args) > 1 else kwargs.pop("allowed_methods") super().__init__( allowed_origins=",".join(allowed_origins), allowed_methods=",".join(allowed_methods), @@ -477,14 +532,24 @@ def as_dict( **kwargs, ) # type: ignore[return-value] + @overload def __init__( self, permission: Optional[Union[QueueSasPermissions, str]] = None, expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, - ) -> None: + ) -> None: ... + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: + if args and isinstance(args[0], (ET.Element, dict)): + super().__init__(*args, **kwargs) + return # TODO: here AccessPolicy never took in a datetime # but we supported datetime and serialized it when passing the model through. (see set access policy) + permission = args[0] if args else kwargs.pop("permission", None) + expiry = args[1] if len(args) > 1 else kwargs.pop("expiry", None) + start = args[2] if len(args) > 2 else kwargs.pop("start", None) if isinstance(permission, QueueSasPermissions): permission = str(permission) super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index 9a20903de639..105505bc1ea5 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] requires-python = ">=3.10" keywords = ["azure", "azure sdk"] From c9552ee670de9b18d2c5f816162dac8bcce0526d Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 8 Jun 2026 10:23:38 -0700 Subject: [PATCH 078/102] pin here for models --- .../storage/queue/_generated/models/_patch.py | 109 +----- .../azure/storage/queue/_models.py | 359 +++++++----------- .../azure/storage/queue/_queue_client.py | 5 +- .../storage/queue/_queue_service_client.py | 6 +- .../storage/queue/aio/_queue_client_async.py | 5 +- .../queue/aio/_queue_service_client_async.py | 6 +- 6 files changed, 149 insertions(+), 341 deletions(-) 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 22c939a160b7..5755fd181b3f 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,109 +1,16 @@ -# 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. -# -------------------------------------------------------------------------- +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import List -# TODO: Waiting on Emitter Perf updates before updating these methods -import xml.etree.ElementTree as ET -from typing import Any, Callable, Dict, List, Optional - -from .._utils.model_base import Model as _deserialize -from azure.core.serialization import as_attribute_dict - -# --------------------------------------------------------------------------- -# Backcompat shims for public methods that existed on the old autorest msrest models. -# The TypeSpec-generated models inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not -# expose ``serialize``/``deserialize``/``from_dict``/``validate``/ -# ``is_xml_model``/``enable_additional_properties_sending``. Re-adding them -# here preserves backward compatibility for users. -# --------------------------------------------------------------------------- - - -def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument - **kwargs: Any, -) -> Dict[str, Any]: - """Backcompat wrapper that returns Python attribute names (snake_case). - - Accepts both the old autorest signature (``keep_readonly``, - ``key_transformer``) and the new TypeSpec keyword-only - ``exclude_readonly`` parameter. ``key_transformer`` is accepted for - signature compatibility but ignored; keys are always remapped to - Python attribute names. - """ - result = as_attribute_dict(self, exclude_readonly=not keep_readonly) - return result - - -class _ModelBackCompatMixin: - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> Dict[str, Any]: - """Backcompat alias for the old autorest ``Model.serialize``. - - Equivalent to ``as_dict(keep_readonly=keep_readonly)`` with REST wire - names (camelCase) as keys — matching what the old autorest serializer - sent to the server. - """ - return as_attribute_dict(self, exclude_readonly=not keep_readonly) - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: - """Backcompat classmethod for the old autorest ``Model.deserialize``. - - Accepts either a JSON-compatible dict/str or (when ``content_type`` is - XML) an XML string or ``ElementTree.Element``. - """ - if content_type and "xml" in content_type.lower(): - if isinstance(data, (bytes, str)): - data = ET.fromstring(data) # nosec - return cls(data) - return _deserialize(cls, data) - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, # pylint: disable=unused-argument - content_type: Optional[str] = None, - ) -> Any: - """Backcompat classmethod for the old autorest ``Model.from_dict``. - - ``key_extractors`` is accepted for signature compatibility but ignored; - the TypeSpec deserializer always uses REST-key mapping. - """ - if content_type and "xml" in content_type.lower(): - if isinstance(data, (bytes, str)): - data = ET.fromstring(data) # nosec - return cls(data) - return _deserialize(cls, data) - - @classmethod - def enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument - """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. - - TypeSpec models already round-trip unknown properties through ``_data``. - """ - return None - - @classmethod - def is_xml_model(cls) -> bool: - """Backcompat classmethod for the old autorest ``Model.is_xml_model``. - - Returns True when the model has an ``_xml`` class attribute (set by the - generator for models that serialize to/from XML). - """ - return bool(getattr(cls, "_xml", None)) - - -__all__: List[str] = [] +__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/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py index 957da5e27785..bd57cf1e8519 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -3,11 +3,10 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -# pylint: disable=too-few-public-methods +# pylint: disable=too-few-public-methods, super-init-not-called import sys -import xml.etree.ElementTree as ET -from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, TYPE_CHECKING, Union, overload +from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING, Union from azure.core.exceptions import HttpResponseError from azure.core.paging import PageIterator from ._shared.response_handlers import ( @@ -15,7 +14,12 @@ return_context_and_deserialized, ) from ._shared.models import DictMixin -from ._generated.models._patch import _ModelBackCompatMixin, as_dict as _backcompat_as_dict +# The msrest-style ``Model`` base from the generated serialization layer is +# kept as the base of the publicly exported models below to preserve the +# exact public API surface (``serialize``/``deserialize``/``as_dict``/ +# ``from_dict``/``is_xml_model``/``enable_additional_properties_sending``) +# that customers depended on prior to the TypeSpec migration. +from ._generated._utils.serialization import Model as _SerializationModel from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -31,7 +35,7 @@ from datetime import datetime -class RetentionPolicy(GeneratedRetentionPolicy, _ModelBackCompatMixin): +class RetentionPolicy(_SerializationModel): """The retention policy which determines how long the associated data should persist. @@ -49,56 +53,36 @@ class RetentionPolicy(GeneratedRetentionPolicy, _ModelBackCompatMixin): days: Optional[int] = None """Indicates the number of days that metrics or logging or soft-deleted data should be retained.""" - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - **kwargs: Any, - ) -> Dict[str, Any]: - """Return a dict representation of the model. - - :param bool keep_readonly: Whether to include readonly fields. - :param key_transformer: A callable to transform each key serialized - from the model. - :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] - :return: A dictionary representation of this model. - :rtype: Dict[str, Any] - """ - return _backcompat_as_dict( - self, - keep_readonly=keep_readonly, - key_transformer=key_transformer, - **kwargs, - ) # type: ignore[return-value] - - @overload - def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: ... - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: ... - def __init__(self, *args: Any, **kwargs: Any) -> None: - if args and isinstance(args[0], (ET.Element, dict)): - super().__init__(*args, **kwargs) - return - enabled = args[0] if args else kwargs.get("enabled", False) - days = args[1] if len(args) > 1 else kwargs.get("days", None) - if enabled and (days is None): + _validation = { + "enabled": {"required": True}, + "days": {"minimum": 1}, + } + + _attribute_map = { + "enabled": {"key": "Enabled", "type": "bool"}, + "days": {"key": "Days", "type": "int"}, + } + + 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): raise ValueError("If policy is enabled, 'days' must be specified.") - super().__init__(enabled=enabled, days=days) @classmethod def _from_generated(cls, generated: Any) -> Self: if not generated: return cls() - # Handle XML Element by converting to generated model first - if isinstance(generated, ET.Element): - generated = GeneratedRetentionPolicy(generated) # type: ignore[assignment,call-overload] return cls( enabled=generated.enabled, days=generated.days, ) + def _to_generated(self) -> GeneratedRetentionPolicy: + return GeneratedRetentionPolicy(enabled=self.enabled, days=self.days) -class QueueAnalyticsLogging(GeneratedLogging, _ModelBackCompatMixin): + +class QueueAnalyticsLogging(_SerializationModel): """Azure Analytics Logging settings. All required parameters must be populated in order to send to Azure. @@ -121,59 +105,33 @@ class QueueAnalyticsLogging(GeneratedLogging, _ModelBackCompatMixin): retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - **kwargs: Any, - ) -> Dict[str, Any]: - """Return a dict representation of the model. - - :param bool keep_readonly: Whether to include readonly fields. - :param key_transformer: A callable to transform each key serialized - from the model. - :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] - :return: A dictionary representation of this model. - :rtype: Dict[str, Any] - """ - return _backcompat_as_dict( - self, - keep_readonly=keep_readonly, - key_transformer=key_transformer, - **kwargs, - ) # type: ignore[return-value] - - @overload - def __init__( - self, - *, - version: str = "1.0", - delete: bool = False, - read: bool = False, - write: bool = False, - retention_policy: Optional[RetentionPolicy] = None, - ) -> None: ... - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: ... - def __init__(self, *args: Any, **kwargs: Any) -> None: - if args and isinstance(args[0], (ET.Element, dict)): - super().__init__(*args, **kwargs) - return - 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(), - ) + _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, **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() @classmethod def _from_generated(cls, generated: Any) -> Self: if not generated: return cls() - # Handle XML Element by converting to generated model first - if isinstance(generated, ET.Element): - generated = GeneratedLogging(generated) # type: ignore[assignment,call-overload] return cls( version=generated.version, delete=generated.delete, @@ -184,8 +142,17 @@ def _from_generated(cls, generated: Any) -> Self: ), ) + def _to_generated(self) -> GeneratedLogging: + return GeneratedLogging( + version=self.version, + delete=self.delete, + read=self.read, + write=self.write, + retention_policy=self.retention_policy._to_generated(), # pylint: disable=protected-access + ) + -class Metrics(GeneratedMetrics, _ModelBackCompatMixin): +class Metrics(_SerializationModel): """A summary of request statistics grouped by API in hour or minute aggregates. All required parameters must be populated in order to send to Azure. @@ -206,57 +173,27 @@ class Metrics(GeneratedMetrics, _ModelBackCompatMixin): retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - **kwargs: Any, - ) -> Dict[str, Any]: - """Return a dict representation of the model. - - :param bool keep_readonly: Whether to include readonly fields. - :param key_transformer: A callable to transform each key serialized - from the model. - :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] - :return: A dictionary representation of this model. - :rtype: Dict[str, Any] - """ - return _backcompat_as_dict( - self, - keep_readonly=keep_readonly, - key_transformer=key_transformer, - **kwargs, - ) # type: ignore[return-value] - - @overload - def __init__( - self, - *, - version: str = "1.0", - enabled: bool = False, - include_apis: Optional[bool] = None, - retention_policy: Optional[RetentionPolicy] = None, - ) -> None: ... - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: ... - def __init__(self, *args: Any, **kwargs: Any) -> None: - if args and isinstance(args[0], (ET.Element, dict)): - super().__init__(*args, **kwargs) - return - 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(), - ) + _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, **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() @classmethod def _from_generated(cls, generated: Any) -> Self: if not generated: return cls() - # Handle XML Element by converting to generated model first - if isinstance(generated, ET.Element): - generated = GeneratedMetrics(generated) # type: ignore[assignment,call-overload] return cls( version=generated.version, enabled=generated.enabled, @@ -266,8 +203,16 @@ def _from_generated(cls, generated: Any) -> Self: ), ) + def _to_generated(self) -> GeneratedMetrics: + return GeneratedMetrics( + version=self.version, + enabled=self.enabled, + include_apis=self.include_apis, + retention_policy=self.retention_policy._to_generated(), # pylint: disable=protected-access + ) + -class CorsRule(GeneratedCorsRule, _ModelBackCompatMixin): +class CorsRule(_SerializationModel): """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 @@ -301,63 +246,38 @@ class CorsRule(GeneratedCorsRule, _ModelBackCompatMixin): """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 + """The comma-delimited string representation of the list of 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.""" + """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin + request.""" + + _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}, + } - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - **kwargs: Any, - ) -> Dict[str, Any]: - """Return a dict representation of the model. - - :param bool keep_readonly: Whether to include readonly fields. - :param key_transformer: A callable to transform each key serialized - from the model. - :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] - :return: A dictionary representation of this model. - :rtype: Dict[str, Any] - """ - return _backcompat_as_dict( - self, - keep_readonly=keep_readonly, - key_transformer=key_transformer, - **kwargs, - ) # type: ignore[return-value] - - @overload - def __init__( - self, - allowed_origins: List[str], - allowed_methods: List[str], - *, - allowed_headers: Optional[List[str]] = None, - exposed_headers: Optional[List[str]] = None, - max_age_in_seconds: int = 0, - ) -> None: ... - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: ... - def __init__(self, *args: Any, **kwargs: Any) -> None: - if args and isinstance(args[0], (ET.Element, dict)): - super().__init__(*args, **kwargs) - return - allowed_origins = args[0] if args else kwargs.pop("allowed_origins") - allowed_methods = args[1] if len(args) > 1 else kwargs.pop("allowed_methods") - 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), - ) + _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: 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) @staticmethod def _to_generated( @@ -381,9 +301,6 @@ def _to_generated( @classmethod def _from_generated(cls, generated: Any) -> Self: - # Handle XML Element by converting to generated model first - if isinstance(generated, ET.Element): - generated = GeneratedCorsRule(generated) # type: ignore[assignment,call-overload] return cls( [generated.allowed_origins], [generated.allowed_methods], @@ -462,7 +379,7 @@ def from_string(cls, permission: str) -> Self: return parsed -class AccessPolicy(GenAccessPolicy, _ModelBackCompatMixin): +class AccessPolicy(_SerializationModel): """Access Policy class used by the set and get access policy methods. A stored access policy can specify the start time, expiry time, and @@ -502,57 +419,35 @@ class AccessPolicy(GenAccessPolicy, _ModelBackCompatMixin): be interpreted as UTC. """ - permission: Optional[Union[QueueSasPermissions, str]] # type: ignore [assignment] + permission: Optional[Union[QueueSasPermissions, str]] """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] + expiry: Optional[Union["datetime", str]] """The time at which the shared access signature becomes invalid.""" - start: Optional[Union["datetime", str]] # type: ignore [assignment] + start: Optional[Union["datetime", str]] """The time at which the shared access signature becomes valid.""" - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - **kwargs: Any, - ) -> Dict[str, Any]: - """Return a dict representation of the model. - - :param bool keep_readonly: Whether to include readonly fields. - :param key_transformer: A callable to transform each key serialized - from the model. - :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] - :return: A dictionary representation of this model. - :rtype: Dict[str, Any] - """ - return _backcompat_as_dict( - self, - keep_readonly=keep_readonly, - key_transformer=key_transformer, - **kwargs, - ) # type: ignore[return-value] - - @overload + _attribute_map = { + "start": {"key": "Start", "type": "str"}, + "expiry": {"key": "Expiry", "type": "str"}, + "permission": {"key": "Permission", "type": "str"}, + } + def __init__( self, permission: Optional[Union[QueueSasPermissions, str]] = None, expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, - ) -> None: ... - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: ... - def __init__(self, *args: Any, **kwargs: Any) -> None: - if args and isinstance(args[0], (ET.Element, dict)): - super().__init__(*args, **kwargs) - return - # TODO: here AccessPolicy never took in a datetime - # but we supported datetime and serialized it when passing the model through. (see set access policy) - permission = args[0] if args else kwargs.pop("permission", None) - expiry = args[1] if len(args) > 1 else kwargs.pop("expiry", None) - start = args[2] if len(args) > 2 else kwargs.pop("start", None) + ) -> None: + self.start = start + self.expiry = expiry + self.permission = permission + + def _to_generated(self) -> GenAccessPolicy: + permission = self.permission if isinstance(permission, QueueSasPermissions): permission = str(permission) - super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore [arg-type] + return GenAccessPolicy(start=self.start, expiry=self.expiry, permission=permission) class QueueMessage(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 b100c4e40323..d19875f2238f 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 @@ -560,7 +560,10 @@ def set_queue_access_policy( if value: value.start = serialize_iso(value.start) value.expiry = serialize_iso(value.expiry) - identifiers.append(SignedIdentifier(id=key, access_policy=value)) + access_policy = value._to_generated() # pylint: disable=protected-access + else: + access_policy = None + identifiers.append(SignedIdentifier(id=key, access_policy=access_policy)) signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) 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 00aa98bda6e2..5012de6b6528 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 @@ -380,9 +380,9 @@ def set_service_properties( :caption: Setting queue service properties. """ props = StorageServiceProperties( - logging=analytics_logging, - hour_metrics=hour_metrics, - minute_metrics=minute_metrics, + logging=analytics_logging._to_generated() if analytics_logging else None, # pylint: disable=protected-access + hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access + minute_metrics=minute_metrics._to_generated() if minute_metrics else None, # pylint: disable=protected-access cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: 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 5cd444037436..e22ad3518ecf 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 @@ -575,7 +575,10 @@ async def set_queue_access_policy( if value: value.start = serialize_iso(value.start) value.expiry = serialize_iso(value.expiry) - identifiers.append(SignedIdentifier(id=key, access_policy=value)) + access_policy = value._to_generated() # pylint: disable=protected-access + else: + access_policy = None + identifiers.append(SignedIdentifier(id=key, access_policy=access_policy)) signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: await self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) 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 c6a80c2e9149..8a5a0bdb3bfc 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 @@ -384,9 +384,9 @@ async def set_service_properties( :caption: Setting queue service properties. """ props = StorageServiceProperties( - logging=analytics_logging, - hour_metrics=hour_metrics, - minute_metrics=minute_metrics, + logging=analytics_logging._to_generated() if analytics_logging else None, # pylint: disable=protected-access + hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access + minute_metrics=minute_metrics._to_generated() if minute_metrics else None, # pylint: disable=protected-access cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: From 975c10515b3bb1ce277d65778cf5528e79121960 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 8 Jun 2026 13:48:47 -0700 Subject: [PATCH 079/102] items_proeprty --- .../azure/storage/queue/_message_encoding.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py index 8e43f3d926fb..266ce955e31c 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py @@ -77,7 +77,7 @@ def __init__(self) -> None: self.resolver = None def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[str, Any]) -> object: - messages = obj.items_property if hasattr(obj, "items_property") else obj + messages = obj.items_property for message in messages or []: if message.message_text in [None, "", b""]: continue From a845bd9dfc5ae80adbdd4f38c13e8e28f6a999b4 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 8 Jun 2026 14:19:06 -0700 Subject: [PATCH 080/102] try this for models, removing inheritance --- .../storage/queue/_generated/models/_patch.py | 166 +++++++++++++++++- .../azure/storage/queue/_models.py | 18 +- 2 files changed, 171 insertions(+), 13 deletions(-) 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 5755fd181b3f..d59ffd6fe1f0 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 @@ -8,7 +8,171 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +import sys +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, List, Optional + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +JSON = MutableMapping[str, Any] + + +class BackCompatMixin: + """A mixin to provide backwards compatibility for models + that used to inherit from msrest models that have now changed to dpg models. + This mixin should not be used for new models. + + Subclasses must define ``_attribute_map`` and optionally ``_validation`` + just like the old msrest ``Model``. + """ + + _attribute_map: Dict[str, Dict[str, Any]] = {} + _validation: Dict[str, Dict[str, Any]] = {} + _xml: Optional[Dict[str, Any]] = None + additional_properties: Optional[Dict[str, Any]] = {} + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @staticmethod + def _serialize_value(value: Any, keep_readonly: bool) -> Any: + """Recursively serialize a value for ``_to_dict``.""" + if isinstance(value, BackCompatMixin): + return value._to_dict(keep_readonly=keep_readonly) # pylint: disable=protected-access + if isinstance(value, list): + return [BackCompatMixin._serialize_value(v, keep_readonly) for v in value] + if isinstance(value, dict): + return {k: BackCompatMixin._serialize_value(v, keep_readonly) for k, v in value.items()} + return value + + def _to_dict(self, keep_readonly: bool) -> Dict[str, Any]: + """Build a dict from ``_attribute_map``, using the REST wire key.""" + result: Dict[str, Any] = {} + for attr, desc in self._attribute_map.items(): + if not keep_readonly and self._validation.get(attr, {}).get("readonly", False): + continue + value = getattr(self, attr, None) + if value is None: + continue + result[desc["key"]] = self._serialize_value(value, keep_readonly) + return result + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to ``as_dict(full_restapi_key_transformer, keep_readonly=False)``. + + :param bool keep_readonly: If you want to serialize the readonly attributes. + :returns: A dict JSON compatible object + :rtype: dict + """ + return self._to_dict(keep_readonly=keep_readonly) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + **kwargs: Any, + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + :param bool keep_readonly: If you want to serialize the readonly attributes. + :param function key_transformer: A key transformer function (accepted for + signature compatibility but ignored). + :returns: A dict JSON compatible object + :rtype: dict + """ + return self._to_dict(keep_readonly=keep_readonly) + + @classmethod + def _from_data(cls, data: Any) -> Self: + """Create an instance from a dict with REST wire keys (e.g. from ``serialize``). + + Uses ``_attribute_map`` to reverse-map REST keys to Python attribute + names, then sets them directly (bypassing ``__init__``). + """ + if isinstance(data, cls): + return data + reverse_map = {desc["key"]: attr for attr, desc in cls._attribute_map.items()} + instance = cls.__new__(cls) + if isinstance(data, dict): + for key, value in data.items(): + attr_name = reverse_map.get(key, key) + setattr(instance, attr_name, value) + return instance + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Backcompat classmethod for the old autorest ``Model.deserialize``. + + Accepts either a JSON-compatible dict/str or (when ``content_type`` is + XML) an XML string or ``ElementTree.Element``. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return cls._from_data(data) + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, # pylint: disable=unused-argument + content_type: Optional[str] = None, + ) -> Self: + """Backcompat classmethod for the old autorest ``Model.from_dict``. + + ``key_extractors`` is accepted for signature compatibility but ignored; + keys are reverse-mapped via ``_attribute_map``. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return cls._from_data(data) + + @classmethod + def enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument + """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. + + TypeSpec models already round-trip unknown properties through ``_data``. + """ + return None + + @classmethod + def is_xml_model(cls) -> bool: + """Backcompat classmethod for the old autorest ``Model.is_xml_model``. + + Returns True when the model has an ``_xml`` class attribute (set by the + generator for models that serialize to/from XML). + """ + return bool(getattr(cls, "_xml", None)) + __all__: List[str] = [] # Add all objects you want publicly available to users at this package level 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 bd57cf1e8519..065bfffdd90f 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -14,12 +14,7 @@ return_context_and_deserialized, ) from ._shared.models import DictMixin -# The msrest-style ``Model`` base from the generated serialization layer is -# kept as the base of the publicly exported models below to preserve the -# exact public API surface (``serialize``/``deserialize``/``as_dict``/ -# ``from_dict``/``is_xml_model``/``enable_additional_properties_sending``) -# that customers depended on prior to the TypeSpec migration. -from ._generated._utils.serialization import Model as _SerializationModel +from ._generated.models._patch import BackCompatMixin as _BackCompatMixin from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -34,8 +29,7 @@ if TYPE_CHECKING: from datetime import datetime - -class RetentionPolicy(_SerializationModel): +class RetentionPolicy(_BackCompatMixin): """The retention policy which determines how long the associated data should persist. @@ -82,7 +76,7 @@ def _to_generated(self) -> GeneratedRetentionPolicy: return GeneratedRetentionPolicy(enabled=self.enabled, days=self.days) -class QueueAnalyticsLogging(_SerializationModel): +class QueueAnalyticsLogging(_BackCompatMixin): """Azure Analytics Logging settings. All required parameters must be populated in order to send to Azure. @@ -152,7 +146,7 @@ def _to_generated(self) -> GeneratedLogging: ) -class Metrics(_SerializationModel): +class Metrics(_BackCompatMixin): """A summary of request statistics grouped by API in hour or minute aggregates. All required parameters must be populated in order to send to Azure. @@ -212,7 +206,7 @@ def _to_generated(self) -> GeneratedMetrics: ) -class CorsRule(_SerializationModel): +class CorsRule(_BackCompatMixin): """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 @@ -379,7 +373,7 @@ def from_string(cls, permission: str) -> Self: return parsed -class AccessPolicy(_SerializationModel): +class AccessPolicy(_BackCompatMixin): """Access Policy class used by the set and get access policy methods. A stored access policy can specify the start time, expiry time, and From 3a8966f13167df1b2f16d75b48e56c63b75ff47f Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 8 Jun 2026 14:56:30 -0700 Subject: [PATCH 081/102] black --- .../storage/queue/_generated/models/_patch.py | 33 ++++++++++++------- .../azure/storage/queue/_models.py | 1 + .../storage/queue/_queue_service_client.py | 8 +++-- .../queue/aio/_queue_service_client_async.py | 8 +++-- 4 files changed, 35 insertions(+), 15 deletions(-) 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 d59ffd6fe1f0..bcb7a3ef6b3f 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 @@ -33,7 +33,6 @@ class BackCompatMixin: _attribute_map: Dict[str, Dict[str, Any]] = {} _validation: Dict[str, Dict[str, Any]] = {} _xml: Optional[Dict[str, Any]] = None - additional_properties: Optional[Dict[str, Any]] = {} def __eq__(self, other: Any) -> bool: """Compare objects by comparing all attributes. @@ -59,18 +58,26 @@ def __str__(self) -> str: return str(self.__dict__) @staticmethod - def _serialize_value(value: Any, keep_readonly: bool) -> Any: + def _serialize_value(value: Any, keep_readonly: bool, use_rest_key: bool) -> Any: """Recursively serialize a value for ``_to_dict``.""" if isinstance(value, BackCompatMixin): - return value._to_dict(keep_readonly=keep_readonly) # pylint: disable=protected-access + return value._to_dict( # pylint: disable=protected-access + keep_readonly=keep_readonly, use_rest_key=use_rest_key + ) if isinstance(value, list): - return [BackCompatMixin._serialize_value(v, keep_readonly) for v in value] + return [BackCompatMixin._serialize_value(v, keep_readonly, use_rest_key) for v in value] if isinstance(value, dict): - return {k: BackCompatMixin._serialize_value(v, keep_readonly) for k, v in value.items()} + return {k: BackCompatMixin._serialize_value(v, keep_readonly, use_rest_key) for k, v in value.items()} return value - def _to_dict(self, keep_readonly: bool) -> Dict[str, Any]: - """Build a dict from ``_attribute_map``, using the REST wire key.""" + def _to_dict(self, keep_readonly: bool, use_rest_key: bool) -> Dict[str, Any]: + """Build a dict from ``_attribute_map``. + + :param bool keep_readonly: If False, skip attributes marked readonly. + :param bool use_rest_key: If True, key the result by the REST wire name + (e.g. ``Enabled``); if False, key by the Python attribute name + (e.g. ``enabled``). + """ result: Dict[str, Any] = {} for attr, desc in self._attribute_map.items(): if not keep_readonly and self._validation.get(attr, {}).get("readonly", False): @@ -78,7 +85,8 @@ def _to_dict(self, keep_readonly: bool) -> Dict[str, Any]: value = getattr(self, attr, None) if value is None: continue - result[desc["key"]] = self._serialize_value(value, keep_readonly) + key = desc["key"] if use_rest_key else attr + result[key] = self._serialize_value(value, keep_readonly, use_rest_key) return result def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: @@ -90,7 +98,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :returns: A dict JSON compatible object :rtype: dict """ - return self._to_dict(keep_readonly=keep_readonly) + return self._to_dict(keep_readonly=keep_readonly, use_rest_key=True) def as_dict( self, @@ -100,13 +108,16 @@ def as_dict( ) -> JSON: """Return a dict that can be serialized using json.dump. + Keys are the Python attribute names (snake_case), matching the old + autorest ``Model.as_dict`` default (``attribute_transformer``). + :param bool keep_readonly: If you want to serialize the readonly attributes. :param function key_transformer: A key transformer function (accepted for signature compatibility but ignored). :returns: A dict JSON compatible object :rtype: dict """ - return self._to_dict(keep_readonly=keep_readonly) + return self._to_dict(keep_readonly=keep_readonly, use_rest_key=False) @classmethod def _from_data(cls, data: Any) -> Self: @@ -172,7 +183,7 @@ def is_xml_model(cls) -> bool: generator for models that serialize to/from XML). """ return bool(getattr(cls, "_xml", None)) - + __all__: List[str] = [] # Add all objects you want publicly available to users at this package level 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 065bfffdd90f..d3664c4efcb4 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -29,6 +29,7 @@ if TYPE_CHECKING: from datetime import datetime + class RetentionPolicy(_BackCompatMixin): """The retention policy which determines how long the associated data should persist. 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 5012de6b6528..c8cf472ff283 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 @@ -380,9 +380,13 @@ def set_service_properties( :caption: Setting queue service properties. """ props = StorageServiceProperties( - logging=analytics_logging._to_generated() if analytics_logging else None, # pylint: disable=protected-access + logging=( + analytics_logging._to_generated() if analytics_logging else None + ), # pylint: disable=protected-access hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access - minute_metrics=minute_metrics._to_generated() if minute_metrics else None, # pylint: disable=protected-access + minute_metrics=( + minute_metrics._to_generated() if minute_metrics else None + ), # pylint: disable=protected-access cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: 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 8a5a0bdb3bfc..175616019b79 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 @@ -384,9 +384,13 @@ async def set_service_properties( :caption: Setting queue service properties. """ props = StorageServiceProperties( - logging=analytics_logging._to_generated() if analytics_logging else None, # pylint: disable=protected-access + logging=( + analytics_logging._to_generated() if analytics_logging else None + ), # pylint: disable=protected-access hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access - minute_metrics=minute_metrics._to_generated() if minute_metrics else None, # pylint: disable=protected-access + minute_metrics=( + minute_metrics._to_generated() if minute_metrics else None + ), # pylint: disable=protected-access cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: From 6246b41d501cdd6fe0d39a9414ff9f1b2951e146 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 8 Jun 2026 15:01:18 -0700 Subject: [PATCH 082/102] mypy --- .../azure/storage/queue/_message_encoding.py | 10 ++++++++-- .../azure/storage/queue/_models.py | 7 ++++++- .../azure/storage/queue/_queue_client.py | 15 +++++++-------- .../storage/queue/aio/_queue_client_async.py | 15 +++++++-------- 4 files changed, 28 insertions(+), 19 deletions(-) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py index 266ce955e31c..f9d8f2b0767d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- from base64 import b64decode, b64encode -from typing import Any, Callable, Dict, Iterable, Optional, TYPE_CHECKING, Union +from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, Union from azure.core.exceptions import DecodeError @@ -18,6 +18,7 @@ if TYPE_CHECKING: from azure.core.pipeline import PipelineResponse + from ._generated.models import PeekedMessages, ReceivedMessages class MessageEncodePolicy(object): @@ -76,7 +77,12 @@ def __init__(self) -> None: self.key_encryption_key = None self.resolver = None - def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[str, Any]) -> object: + def __call__( + self, + response: "PipelineResponse", + obj: Union["PeekedMessages", "ReceivedMessages"], + headers: Dict[str, Any], + ) -> object: messages = obj.items_property for message in messages or []: if message.message_text in [None, "", b""]: 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 d3664c4efcb4..009f2f9a0cd0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -13,6 +13,7 @@ process_storage_error, return_context_and_deserialized, ) +from ._shared.request_handlers import serialize_iso from ._shared.models import DictMixin from ._generated.models._patch import BackCompatMixin as _BackCompatMixin from ._generated.models import AccessPolicy as GenAccessPolicy @@ -442,7 +443,11 @@ def _to_generated(self) -> GenAccessPolicy: permission = self.permission if isinstance(permission, QueueSasPermissions): permission = str(permission) - return GenAccessPolicy(start=self.start, expiry=self.expiry, permission=permission) + return GenAccessPolicy( + start=serialize_iso(self.start), + expiry=serialize_iso(self.expiry), + permission=permission, + ) class QueueMessage(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 d19875f2238f..b9e76e3a2f2e 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 @@ -23,7 +23,7 @@ from ._queue_client_helpers import _format_url, _from_queue_url, _parse_url from ._serialize import get_api_version from ._shared.base_client import parse_connection_str, StorageAccountHostsMixin -from ._shared.request_handlers import add_metadata_headers, serialize_iso +from ._shared.request_handlers import add_metadata_headers from ._shared.response_handlers import ( process_storage_error, return_headers_and_deserialized, @@ -557,13 +557,12 @@ def set_queue_access_policy( ) identifiers = [] for key, value in signed_identifiers.items(): - if value: - value.start = serialize_iso(value.start) - value.expiry = serialize_iso(value.expiry) - access_policy = value._to_generated() # pylint: disable=protected-access - else: - access_policy = None - identifiers.append(SignedIdentifier(id=key, access_policy=access_policy)) + access_policy = value._to_generated() if value else None # pylint: disable=protected-access + # access_policy is optional on the wire (an identifier may reference a stored + # policy by id alone), but the generated model types it as required. + identifiers.append( + SignedIdentifier(id=key, access_policy=access_policy) # type: ignore[arg-type] + ) signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) 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 e22ad3518ecf..67f7184fad11 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 @@ -30,7 +30,7 @@ parse_connection_str, ) from .._shared.policies_async import ExponentialRetry -from .._shared.request_handlers import add_metadata_headers, serialize_iso +from .._shared.request_handlers import add_metadata_headers from .._shared.response_handlers import ( process_storage_error, return_headers_and_deserialized, @@ -572,13 +572,12 @@ async def set_queue_access_policy( ) identifiers = [] for key, value in signed_identifiers.items(): - if value: - value.start = serialize_iso(value.start) - value.expiry = serialize_iso(value.expiry) - access_policy = value._to_generated() # pylint: disable=protected-access - else: - access_policy = None - identifiers.append(SignedIdentifier(id=key, access_policy=access_policy)) + access_policy = value._to_generated() if value else None # pylint: disable=protected-access + # access_policy is optional on the wire (an identifier may reference a stored + # policy by id alone), but the generated model types it as required. + identifiers.append( + SignedIdentifier(id=key, access_policy=access_policy) # type: ignore[arg-type] + ) signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: await self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) From dcd69a7e7dd3f5a9523bc944f25262be5c064930 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 8 Jun 2026 15:44:09 -0700 Subject: [PATCH 083/102] this --- .../storage/queue/_generated/models/_patch.py | 29 +++++++------------ .../azure/storage/queue/_message_encoding.py | 9 +++--- .../azure/storage/queue/_queue_client.py | 4 +-- .../storage/queue/aio/_queue_client_async.py | 4 +-- 4 files changed, 18 insertions(+), 28 deletions(-) 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 bcb7a3ef6b3f..d4b609d9c491 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 @@ -9,7 +9,6 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ import sys -import xml.etree.ElementTree as ET from collections.abc import MutableMapping from typing import Any, Callable, Dict, List, Optional @@ -32,7 +31,6 @@ class BackCompatMixin: _attribute_map: Dict[str, Dict[str, Any]] = {} _validation: Dict[str, Dict[str, Any]] = {} - _xml: Optional[Dict[str, Any]] = None def __eq__(self, other: Any) -> bool: """Compare objects by comparing all attributes. @@ -59,7 +57,7 @@ def __str__(self) -> str: @staticmethod def _serialize_value(value: Any, keep_readonly: bool, use_rest_key: bool) -> Any: - """Recursively serialize a value for ``_to_dict``.""" + """Recursively serialize a value for ``_to_dict``, kept simple for the few backcompat models that need it.""" if isinstance(value, BackCompatMixin): return value._to_dict( # pylint: disable=protected-access keep_readonly=keep_readonly, use_rest_key=use_rest_key @@ -137,16 +135,16 @@ def _from_data(cls, data: Any) -> Self: return instance @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + def deserialize( + cls, + data: Any, + content_type: Optional[str] = None, # pylint: disable=unused-argument + ) -> Self: """Backcompat classmethod for the old autorest ``Model.deserialize``. - Accepts either a JSON-compatible dict/str or (when ``content_type`` is - XML) an XML string or ``ElementTree.Element``. + Accepts a JSON-compatible dict with REST wire keys (e.g. from + ``serialize``). """ - if content_type and "xml" in content_type.lower(): - if isinstance(data, (bytes, str)): - data = ET.fromstring(data) # nosec - return cls(data) return cls._from_data(data) @classmethod @@ -154,17 +152,13 @@ def from_dict( cls, data: Any, key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, # pylint: disable=unused-argument - content_type: Optional[str] = None, + content_type: Optional[str] = None, # pylint: disable=unused-argument ) -> Self: """Backcompat classmethod for the old autorest ``Model.from_dict``. ``key_extractors`` is accepted for signature compatibility but ignored; keys are reverse-mapped via ``_attribute_map``. """ - if content_type and "xml" in content_type.lower(): - if isinstance(data, (bytes, str)): - data = ET.fromstring(data) # nosec - return cls(data) return cls._from_data(data) @classmethod @@ -179,10 +173,9 @@ def enable_additional_properties_sending(cls) -> None: # pylint: disable=unused def is_xml_model(cls) -> bool: """Backcompat classmethod for the old autorest ``Model.is_xml_model``. - Returns True when the model has an ``_xml`` class attribute (set by the - generator for models that serialize to/from XML). + Always ``False``: these backcompat models serialize to/from JSON, not XML. """ - return bool(getattr(cls, "_xml", None)) + return False __all__: List[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py index f9d8f2b0767d..137841be1927 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_message_encoding.py @@ -5,7 +5,7 @@ # -------------------------------------------------------------------------- from base64 import b64decode, b64encode -from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, Union +from typing import Any, Callable, Dict, Iterable, Optional, TYPE_CHECKING, Union from azure.core.exceptions import DecodeError @@ -18,7 +18,6 @@ if TYPE_CHECKING: from azure.core.pipeline import PipelineResponse - from ._generated.models import PeekedMessages, ReceivedMessages class MessageEncodePolicy(object): @@ -80,10 +79,12 @@ def __init__(self) -> None: def __call__( self, response: "PipelineResponse", - obj: Union["PeekedMessages", "ReceivedMessages"], + obj: Iterable, headers: Dict[str, Any], ) -> object: - messages = obj.items_property + # ``obj`` is the deserialized container (PeekedMessages/ReceivedMessages) + # whose messages live on ``items_property``; to make typing happy + messages = getattr(obj, "items_property", obj) for message in messages or []: if message.message_text in [None, "", b""]: continue 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 b9e76e3a2f2e..1dd4fca08549 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 @@ -560,9 +560,7 @@ def set_queue_access_policy( access_policy = value._to_generated() if value else None # pylint: disable=protected-access # access_policy is optional on the wire (an identifier may reference a stored # policy by id alone), but the generated model types it as required. - identifiers.append( - SignedIdentifier(id=key, access_policy=access_policy) # type: ignore[arg-type] - ) + identifiers.append(SignedIdentifier(id=key, access_policy=access_policy)) # type: ignore[arg-type] signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) 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 67f7184fad11..d52acc68fb8a 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 @@ -575,9 +575,7 @@ async def set_queue_access_policy( access_policy = value._to_generated() if value else None # pylint: disable=protected-access # access_policy is optional on the wire (an identifier may reference a stored # policy by id alone), but the generated model types it as required. - identifiers.append( - SignedIdentifier(id=key, access_policy=access_policy) # type: ignore[arg-type] - ) + identifiers.append(SignedIdentifier(id=key, access_policy=access_policy)) # type: ignore[arg-type] signed_identifiers_model = SignedIdentifiers(items_property=identifiers) if identifiers else None try: await self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) From 965e06595a7dcecc8e3d6ba163dc11f0e25b44af Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 9 Jun 2026 08:23:39 -0700 Subject: [PATCH 084/102] pylint --- .../azure/storage/queue/_queue_service_client.py | 8 ++++---- .../storage/queue/aio/_queue_service_client_async.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) 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 c8cf472ff283..b7092feb450c 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 @@ -381,12 +381,12 @@ def set_service_properties( """ props = StorageServiceProperties( logging=( - analytics_logging._to_generated() if analytics_logging else None - ), # pylint: disable=protected-access + analytics_logging._to_generated() if analytics_logging else None # pylint: disable=protected-access + ), hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access minute_metrics=( - minute_metrics._to_generated() if minute_metrics else None - ), # pylint: disable=protected-access + minute_metrics._to_generated() if minute_metrics else None # pylint: disable=protected-access + ), cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: 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 175616019b79..84681af73ade 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 @@ -385,12 +385,12 @@ async def set_service_properties( """ props = StorageServiceProperties( logging=( - analytics_logging._to_generated() if analytics_logging else None - ), # pylint: disable=protected-access + analytics_logging._to_generated() if analytics_logging else None # pylint: disable=protected-access + ), hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access minute_metrics=( - minute_metrics._to_generated() if minute_metrics else None - ), # pylint: disable=protected-access + minute_metrics._to_generated() if minute_metrics else None # pylint: disable=protected-access + ), cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: From 067745d3201923fab893049f966ff416bd2b10b8 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 9 Jun 2026 09:42:09 -0700 Subject: [PATCH 085/102] backcompat loading --- .../storage/queue/_generated/models/_patch.py | 174 +----------------- .../azure/storage/queue/_models.py | 44 ++++- 2 files changed, 40 insertions(+), 178 deletions(-) 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 d4b609d9c491..3bd73d69cd35 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 @@ -2,181 +2,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ - - """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import sys -from collections.abc import MutableMapping -from typing import Any, Callable, Dict, List, Optional - -if sys.version_info >= (3, 11): - from typing import Self -else: - from typing_extensions import Self - -JSON = MutableMapping[str, Any] - - -class BackCompatMixin: - """A mixin to provide backwards compatibility for models - that used to inherit from msrest models that have now changed to dpg models. - This mixin should not be used for new models. - - Subclasses must define ``_attribute_map`` and optionally ``_validation`` - just like the old msrest ``Model``. - """ - - _attribute_map: Dict[str, Dict[str, Any]] = {} - _validation: Dict[str, Dict[str, Any]] = {} - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @staticmethod - def _serialize_value(value: Any, keep_readonly: bool, use_rest_key: bool) -> Any: - """Recursively serialize a value for ``_to_dict``, kept simple for the few backcompat models that need it.""" - if isinstance(value, BackCompatMixin): - return value._to_dict( # pylint: disable=protected-access - keep_readonly=keep_readonly, use_rest_key=use_rest_key - ) - if isinstance(value, list): - return [BackCompatMixin._serialize_value(v, keep_readonly, use_rest_key) for v in value] - if isinstance(value, dict): - return {k: BackCompatMixin._serialize_value(v, keep_readonly, use_rest_key) for k, v in value.items()} - return value - - def _to_dict(self, keep_readonly: bool, use_rest_key: bool) -> Dict[str, Any]: - """Build a dict from ``_attribute_map``. - - :param bool keep_readonly: If False, skip attributes marked readonly. - :param bool use_rest_key: If True, key the result by the REST wire name - (e.g. ``Enabled``); if False, key by the Python attribute name - (e.g. ``enabled``). - """ - result: Dict[str, Any] = {} - for attr, desc in self._attribute_map.items(): - if not keep_readonly and self._validation.get(attr, {}).get("readonly", False): - continue - value = getattr(self, attr, None) - if value is None: - continue - key = desc["key"] if use_rest_key else attr - result[key] = self._serialize_value(value, keep_readonly, use_rest_key) - return result - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to ``as_dict(full_restapi_key_transformer, keep_readonly=False)``. - - :param bool keep_readonly: If you want to serialize the readonly attributes. - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_dict(keep_readonly=keep_readonly, use_rest_key=True) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument - **kwargs: Any, - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Keys are the Python attribute names (snake_case), matching the old - autorest ``Model.as_dict`` default (``attribute_transformer``). - - :param bool keep_readonly: If you want to serialize the readonly attributes. - :param function key_transformer: A key transformer function (accepted for - signature compatibility but ignored). - :returns: A dict JSON compatible object - :rtype: dict - """ - return self._to_dict(keep_readonly=keep_readonly, use_rest_key=False) - - @classmethod - def _from_data(cls, data: Any) -> Self: - """Create an instance from a dict with REST wire keys (e.g. from ``serialize``). - - Uses ``_attribute_map`` to reverse-map REST keys to Python attribute - names, then sets them directly (bypassing ``__init__``). - """ - if isinstance(data, cls): - return data - reverse_map = {desc["key"]: attr for attr, desc in cls._attribute_map.items()} - instance = cls.__new__(cls) - if isinstance(data, dict): - for key, value in data.items(): - attr_name = reverse_map.get(key, key) - setattr(instance, attr_name, value) - return instance - - @classmethod - def deserialize( - cls, - data: Any, - content_type: Optional[str] = None, # pylint: disable=unused-argument - ) -> Self: - """Backcompat classmethod for the old autorest ``Model.deserialize``. - - Accepts a JSON-compatible dict with REST wire keys (e.g. from - ``serialize``). - """ - return cls._from_data(data) - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, # pylint: disable=unused-argument - content_type: Optional[str] = None, # pylint: disable=unused-argument - ) -> Self: - """Backcompat classmethod for the old autorest ``Model.from_dict``. - - ``key_extractors`` is accepted for signature compatibility but ignored; - keys are reverse-mapped via ``_attribute_map``. - """ - return cls._from_data(data) - - @classmethod - def enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument - """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. - - TypeSpec models already round-trip unknown properties through ``_data``. - """ - return None - - @classmethod - def is_xml_model(cls) -> bool: - """Backcompat classmethod for the old autorest ``Model.is_xml_model``. - - Always ``False``: these backcompat models serialize to/from JSON, not XML. - """ - return False - +from typing import List __all__: List[str] = [] # Add all objects you want publicly available to users at this package level @@ -187,4 +17,4 @@ def patch_sdk(): `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 - """ + """ \ No newline at end of file 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 009f2f9a0cd0..4912fabfbb2b 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -15,7 +15,7 @@ ) from ._shared.request_handlers import serialize_iso from ._shared.models import DictMixin -from ._generated.models._patch import BackCompatMixin as _BackCompatMixin +from ._generated._utils import serialization as _serialization from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -31,7 +31,35 @@ from datetime import datetime -class RetentionPolicy(_BackCompatMixin): +# These public models inherited (transitively) from the autorest +# msrest model, which exposed ``serialize``, ``deserialize``, +# ``from_dict``, ``as_dict``, ``is_xml_model``, and +# ``enable_additional_properties_sending``. After the migration the generated models +# use a different base class. To preserve the public method surface, the methods +# are grafted onto each public class at module load time via the +# ``@_attach_msrest_compat`` decorator. +def _attach_msrest_compat(cls: type) -> type: + if not hasattr(cls, "_attribute_map"): + raise TypeError(f"{cls.__name__} must define _attribute_map to use _attach_msrest_compat") + if not hasattr(cls, "_validation"): + cls._validation = {} # type: ignore[attr-defined] + cls.additional_properties = None # type: ignore[attr-defined] + for _name in ( + "serialize", + "deserialize", + "from_dict", + "as_dict", + "is_xml_model", + "enable_additional_properties_sending", + "_infer_class_models", + "_create_xml_node", + ): + setattr(cls, _name, vars(_serialization.Model)[_name]) + return cls + + +@_attach_msrest_compat +class RetentionPolicy: """The retention policy which determines how long the associated data should persist. @@ -78,7 +106,8 @@ def _to_generated(self) -> GeneratedRetentionPolicy: return GeneratedRetentionPolicy(enabled=self.enabled, days=self.days) -class QueueAnalyticsLogging(_BackCompatMixin): +@_attach_msrest_compat +class QueueAnalyticsLogging: """Azure Analytics Logging settings. All required parameters must be populated in order to send to Azure. @@ -148,7 +177,8 @@ def _to_generated(self) -> GeneratedLogging: ) -class Metrics(_BackCompatMixin): +@_attach_msrest_compat +class Metrics: """A summary of request statistics grouped by API in hour or minute aggregates. All required parameters must be populated in order to send to Azure. @@ -208,7 +238,8 @@ def _to_generated(self) -> GeneratedMetrics: ) -class CorsRule(_BackCompatMixin): +@_attach_msrest_compat +class CorsRule: """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 @@ -375,7 +406,8 @@ def from_string(cls, permission: str) -> Self: return parsed -class AccessPolicy(_BackCompatMixin): +@_attach_msrest_compat +class AccessPolicy: """Access Policy class used by the set and get access policy methods. A stored access policy can specify the start time, expiry time, and From b4c6456eb7699aaed72fae6e0bcea69014e6ec3a Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 9 Jun 2026 12:08:07 -0700 Subject: [PATCH 086/102] move to patch --- .../storage/queue/_generated/models/_patch.py | 31 ++++++++++++++++++- .../azure/storage/queue/_models.py | 29 +---------------- 2 files changed, 31 insertions(+), 29 deletions(-) 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 3bd73d69cd35..3d84f8518d2e 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 @@ -7,8 +7,37 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ from typing import List +from .._utils import serialization as _serialization -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +# These public models inherited (transitively) from the autorest +# msrest model, which exposed ``serialize``, ``deserialize``, +# ``from_dict``, ``as_dict``, ``is_xml_model``, and +# ``enable_additional_properties_sending``. After the migration the generated models +# use a different base class. To preserve the public method surface, the methods +# are grafted onto each public class at module load time via the +# ``@_attach_msrest_compat`` decorator. +def _attach_msrest_compat(cls: type) -> type: + if not hasattr(cls, "_attribute_map"): + raise TypeError(f"{cls.__name__} must define _attribute_map to use _attach_msrest_compat") + if not hasattr(cls, "_validation"): + cls._validation = {} # type: ignore[attr-defined] + cls.additional_properties = None # type: ignore[attr-defined] + for _name in ( + "serialize", + "deserialize", + "from_dict", + "as_dict", + "is_xml_model", + "enable_additional_properties_sending", + "_infer_class_models", + "_create_xml_node", + ): + setattr(cls, _name, vars(_serialization.Model)[_name]) + return cls + + + +__all__: List[str] = ["_attach_msrest_compat"] # 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/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py index 4912fabfbb2b..ad64d066e96d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -15,7 +15,7 @@ ) from ._shared.request_handlers import serialize_iso from ._shared.models import DictMixin -from ._generated._utils import serialization as _serialization +from ._generated.models import _attach_msrest_compat from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -31,33 +31,6 @@ from datetime import datetime -# These public models inherited (transitively) from the autorest -# msrest model, which exposed ``serialize``, ``deserialize``, -# ``from_dict``, ``as_dict``, ``is_xml_model``, and -# ``enable_additional_properties_sending``. After the migration the generated models -# use a different base class. To preserve the public method surface, the methods -# are grafted onto each public class at module load time via the -# ``@_attach_msrest_compat`` decorator. -def _attach_msrest_compat(cls: type) -> type: - if not hasattr(cls, "_attribute_map"): - raise TypeError(f"{cls.__name__} must define _attribute_map to use _attach_msrest_compat") - if not hasattr(cls, "_validation"): - cls._validation = {} # type: ignore[attr-defined] - cls.additional_properties = None # type: ignore[attr-defined] - for _name in ( - "serialize", - "deserialize", - "from_dict", - "as_dict", - "is_xml_model", - "enable_additional_properties_sending", - "_infer_class_models", - "_create_xml_node", - ): - setattr(cls, _name, vars(_serialization.Model)[_name]) - return cls - - @_attach_msrest_compat class RetentionPolicy: """The retention policy which determines how long the associated data should From 71692eea5214b93a3a53b9cab57436d43f310d8d Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 9 Jun 2026 12:51:43 -0700 Subject: [PATCH 087/102] pylint fix --- .../azure/storage/queue/_generated/models/_patch.py | 6 +++--- .../azure-storage-queue/azure/storage/queue/_models.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) 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 3d84f8518d2e..ee07e6918a98 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 @@ -9,6 +9,7 @@ from typing import List from .._utils import serialization as _serialization + # These public models inherited (transitively) from the autorest # msrest model, which exposed ``serialize``, ``deserialize``, # ``from_dict``, ``as_dict``, ``is_xml_model``, and @@ -36,8 +37,7 @@ def _attach_msrest_compat(cls: type) -> type: return cls - -__all__: List[str] = ["_attach_msrest_compat"] # 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(): @@ -46,4 +46,4 @@ def patch_sdk(): `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 - """ \ No newline at end of file + """ 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 ad64d066e96d..6c22ee1a8ae5 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -15,7 +15,7 @@ ) from ._shared.request_handlers import serialize_iso from ._shared.models import DictMixin -from ._generated.models import _attach_msrest_compat +from ._generated.models._patch import _attach_msrest_compat from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging From 6c0a6cf6553e46be1d7a69c516dc29821bae2f38 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 9 Jun 2026 12:53:27 -0700 Subject: [PATCH 088/102] missing __str --- .../azure/storage/queue/_generated/models/_patch.py | 3 +++ 1 file changed, 3 insertions(+) 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 ee07e6918a98..0ed6ace04276 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 @@ -32,6 +32,9 @@ def _attach_msrest_compat(cls: type) -> type: "enable_additional_properties_sending", "_infer_class_models", "_create_xml_node", + "__eq__", + "__ne__", + "__str__", ): setattr(cls, _name, vars(_serialization.Model)[_name]) return cls From 6960cdb90d0ddf1857db5d62d528aa049488d6a8 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 10 Jun 2026 11:05:33 -0700 Subject: [PATCH 089/102] change to backcompatMixin of serialization Model --- .../storage/queue/_generated/models/_patch.py | 46 +++++++------------ .../azure/storage/queue/_models.py | 17 +++---- 2 files changed, 23 insertions(+), 40 deletions(-) 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 0ed6ace04276..62b7612fa1ba 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 @@ -6,38 +6,26 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import Any, Dict, List, Optional from .._utils import serialization as _serialization -# These public models inherited (transitively) from the autorest -# msrest model, which exposed ``serialize``, ``deserialize``, -# ``from_dict``, ``as_dict``, ``is_xml_model``, and -# ``enable_additional_properties_sending``. After the migration the generated models -# use a different base class. To preserve the public method surface, the methods -# are grafted onto each public class at module load time via the -# ``@_attach_msrest_compat`` decorator. -def _attach_msrest_compat(cls: type) -> type: - if not hasattr(cls, "_attribute_map"): - raise TypeError(f"{cls.__name__} must define _attribute_map to use _attach_msrest_compat") - if not hasattr(cls, "_validation"): - cls._validation = {} # type: ignore[attr-defined] - cls.additional_properties = None # type: ignore[attr-defined] - for _name in ( - "serialize", - "deserialize", - "from_dict", - "as_dict", - "is_xml_model", - "enable_additional_properties_sending", - "_infer_class_models", - "_create_xml_node", - "__eq__", - "__ne__", - "__str__", - ): - setattr(cls, _name, vars(_serialization.Model)[_name]) - return cls +# These public models inherited (transitively) from the autorest msrest model, +# which exposed ``serialize``, ``deserialize``, ``from_dict``, ``as_dict``, +# ``is_xml_model``, and ``enable_additional_properties_sending``. After the +# migration the generated models use a different base class, so the public +# classes mix this in to preserve the historical method surface. +class _BackCompatMixin(_serialization.Model): + # The hand-written models define their own ``__init__`` and never call the + # base ``Model.__init__``, so expose ``additional_properties`` at the class + # level just as the previous decorator-based approach did. + additional_properties: Optional[Dict[str, Any]] = None + + # ``Model`` defines ``__eq__`` (value equality), which would otherwise set + # ``__hash__`` to ``None``. Keep these models hashable by identity, matching + # their previous behavior. + def __hash__(self) -> int: + return object.__hash__(self) __all__: List[str] = [] # Add all objects you want publicly available to users at this package level 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 6c22ee1a8ae5..d7ab81e36e5c 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -15,7 +15,7 @@ ) from ._shared.request_handlers import serialize_iso from ._shared.models import DictMixin -from ._generated.models._patch import _attach_msrest_compat +from ._generated.models._patch import _BackCompatMixin from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -31,8 +31,7 @@ from datetime import datetime -@_attach_msrest_compat -class RetentionPolicy: +class RetentionPolicy(_BackCompatMixin): """The retention policy which determines how long the associated data should persist. @@ -79,8 +78,7 @@ def _to_generated(self) -> GeneratedRetentionPolicy: return GeneratedRetentionPolicy(enabled=self.enabled, days=self.days) -@_attach_msrest_compat -class QueueAnalyticsLogging: +class QueueAnalyticsLogging(_BackCompatMixin): """Azure Analytics Logging settings. All required parameters must be populated in order to send to Azure. @@ -150,8 +148,7 @@ def _to_generated(self) -> GeneratedLogging: ) -@_attach_msrest_compat -class Metrics: +class Metrics(_BackCompatMixin): """A summary of request statistics grouped by API in hour or minute aggregates. All required parameters must be populated in order to send to Azure. @@ -211,8 +208,7 @@ def _to_generated(self) -> GeneratedMetrics: ) -@_attach_msrest_compat -class CorsRule: +class CorsRule(_BackCompatMixin): """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 @@ -379,8 +375,7 @@ def from_string(cls, permission: str) -> Self: return parsed -@_attach_msrest_compat -class AccessPolicy: +class AccessPolicy(_BackCompatMixin): """Access Policy class used by the set and get access policy methods. A stored access policy can specify the start time, expiry time, and From 7b35e99b42f99384713a404966e1680eef73ae26 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 10 Jun 2026 11:34:33 -0700 Subject: [PATCH 090/102] dont directly inherit from model --- .../storage/queue/_generated/models/_patch.py | 114 +++++++++++++++--- 1 file changed, 99 insertions(+), 15 deletions(-) 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 62b7612fa1ba..46a7f131867d 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 @@ -6,26 +6,110 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Any, Dict, List, Optional -from .._utils import serialization as _serialization +import sys +from typing import Any, Callable, Dict, List, Optional + +from .._utils.serialization import JSON, Model + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # These public models inherited (transitively) from the autorest msrest model, # which exposed ``serialize``, ``deserialize``, ``from_dict``, ``as_dict``, # ``is_xml_model``, and ``enable_additional_properties_sending``. After the -# migration the generated models use a different base class, so the public -# classes mix this in to preserve the historical method surface. -class _BackCompatMixin(_serialization.Model): - # The hand-written models define their own ``__init__`` and never call the - # base ``Model.__init__``, so expose ``additional_properties`` at the class - # level just as the previous decorator-based approach did. - additional_properties: Optional[Dict[str, Any]] = None - - # ``Model`` defines ``__eq__`` (value equality), which would otherwise set - # ``__hash__`` to ``None``. Keep these models hashable by identity, matching - # their previous behavior. - def __hash__(self) -> int: - return object.__hash__(self) +# migration the generated models use a different base class. The public classes mix this in to expose +# exactly the historical methods, each delegating to ``Model``. +class _BackCompatMixin: + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Serialize this model to a dictionary. + + :param bool keep_readonly: If you want to serialize the readonly attributes. + :returns: A dict JSON compatible object. + :rtype: JSON + """ + return Model.serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore[arg-type] + + def as_dict(self, keep_readonly: bool = True, **kwargs: Any) -> JSON: + """Return a dict that can be serialized using json.dump. + + :param bool keep_readonly: If you want to serialize the readonly attributes. + :returns: A dict JSON compatible object. + :rtype: JSON + """ + return Model.as_dict(self, keep_readonly=keep_readonly, **kwargs) # type: ignore[arg-type] + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Deserialize this model from a dictionary. + + :param data: A str using RestAPI structure. JSON by default. + :type data: str + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model. + :rtype: Self + """ + # ``Model.deserialize`` is a classmethod already bound to ``Model``; reach + # through ``__func__`` so it runs with this subclass as ``cls``. + return Model.deserialize.__func__(cls, data, content_type=content_type) + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using a given key extractor and return a model. + + :param dict data: A dict using RestAPI structure. + :param key_extractors: A key extractor function. + :type key_extractors: callable or None + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model. + :rtype: Self + """ + return Model.from_dict.__func__(cls, data, key_extractors=key_extractors, content_type=content_type) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + """Add ``additional_properties`` to the attribute map so they are sent to the service. + + :returns: None + :rtype: None + """ + return Model.enable_additional_properties_sending.__func__(cls) + + @classmethod + def is_xml_model(cls) -> bool: + """Whether this model is serialized as XML. + + :returns: True if this model is serialized as XML, otherwise False. + :rtype: bool + """ + return Model.is_xml_model.__func__(cls) + + @classmethod + def _infer_class_models(cls) -> Dict[str, type]: + # Internal helper used by serialize/as_dict/deserialize/from_dict. + return Model._infer_class_models.__func__(cls) + + @classmethod + def _create_xml_node(cls) -> Any: + # Internal helper used during XML (de)serialization. + return Model._create_xml_node.__func__(cls) + + def __eq__(self, other: Any) -> bool: + return Model.__eq__(self, other) # type: ignore[arg-type] + + def __ne__(self, other: Any) -> bool: + return Model.__ne__(self, other) # type: ignore[arg-type] + + def __str__(self) -> str: + return Model.__str__(self) # type: ignore[arg-type] __all__: List[str] = [] # Add all objects you want publicly available to users at this package level From 29cefcffffbf1307e6258b93abefcdee90d98b24 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 11 Jun 2026 08:42:27 -0700 Subject: [PATCH 091/102] bump missing api diff --- .../azure/storage/queue/_generated/models/_patch.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) 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 46a7f131867d..65da755ea3c6 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 @@ -9,7 +9,7 @@ import sys from typing import Any, Callable, Dict, List, Optional -from .._utils.serialization import JSON, Model +from .._utils.serialization import JSON, Model, attribute_transformer if sys.version_info >= (3, 11): from typing import Self @@ -33,14 +33,15 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: """ return Model.serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore[arg-type] - def as_dict(self, keep_readonly: bool = True, **kwargs: Any) -> JSON: + def as_dict(self, keep_readonly: bool = True, key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any) -> JSON: """Return a dict that can be serialized using json.dump. :param bool keep_readonly: If you want to serialize the readonly attributes. + :param key_transformer: A function that takes an attribute name, the attribute map, and the value, and returns the key to use in the output dict. :returns: A dict JSON compatible object. :rtype: JSON """ - return Model.as_dict(self, keep_readonly=keep_readonly, **kwargs) # type: ignore[arg-type] + return Model.as_dict(self, keep_readonly=keep_readonly, key_transformer=key_transformer, **kwargs) # type: ignore[arg-type] @classmethod def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: @@ -60,7 +61,7 @@ def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: def from_dict( cls, data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, ) -> Self: """Parse a dict using a given key extractor and return a model. From 99d8bd17c52218f27196ea1bec3656f38ea935fe Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 11 Jun 2026 13:16:48 -0700 Subject: [PATCH 092/102] black --- .../azure/storage/queue/_generated/models/_patch.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 65da755ea3c6..59eb5a0c6363 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 @@ -33,7 +33,12 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: """ return Model.serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore[arg-type] - def as_dict(self, keep_readonly: bool = True, key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any) -> JSON: + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: """Return a dict that can be serialized using json.dump. :param bool keep_readonly: If you want to serialize the readonly attributes. From 9ae5e4374e565cbc826e7410d4f8c35cfb4b4ff6 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 12 Jun 2026 11:10:29 -0700 Subject: [PATCH 093/102] backcompat updates --- .../azure/storage/queue/_generated/models/_patch.py | 1 + .../azure-storage-queue/azure/storage/queue/_models.py | 10 ++++++++++ .../azure/storage/queue/_queue_client.py | 10 +--------- .../azure/storage/queue/aio/_queue_client_async.py | 10 +--------- 4 files changed, 13 insertions(+), 18 deletions(-) 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 59eb5a0c6363..71e561394be9 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 @@ -23,6 +23,7 @@ # migration the generated models use a different base class. The public classes mix this in to expose # exactly the historical methods, each delegating to ``Model``. class _BackCompatMixin: + _validation = {} def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: """Serialize this model to a dictionary. 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 d7ab81e36e5c..585f5f68fd09 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -439,6 +439,16 @@ def __init__( self.expiry = expiry self.permission = permission + @classmethod + def _from_generated(cls, generated: Any) -> Self: + if not generated: + return cls() + return cls( + permission=generated.permission, + expiry=generated.expiry, + start=generated.start, + ) + def _to_generated(self) -> GenAccessPolicy: permission = self.permission if isinstance(permission, QueueSasPermissions): 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 1dd4fca08549..a2657e9869fc 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 @@ -496,15 +496,7 @@ def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An process_storage_error(error) 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() - ) + s.id: AccessPolicy._from_generated(s.access_policy) # pylint: disable=protected-access for s in (identifiers.items_property or []) } if identifiers 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 d52acc68fb8a..fc582011b38c 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 @@ -511,15 +511,7 @@ async def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwar process_storage_error(error) 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() - ) + s.id: AccessPolicy._from_generated(s.access_policy) # pylint: disable=protected-access for s in (identifiers.items_property or []) } if identifiers From 2718bd5d9c3301f909f63c477524752813be160c Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 12 Jun 2026 13:31:21 -0700 Subject: [PATCH 094/102] cleaning code --- .../azure/storage/queue/_models.py | 28 +++++++++++-------- .../storage/queue/_queue_service_client.py | 13 ++++----- .../queue/aio/_queue_service_client_async.py | 13 ++++----- 3 files changed, 27 insertions(+), 27 deletions(-) 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 585f5f68fd09..79a9f0664951 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -138,13 +138,16 @@ def _from_generated(cls, generated: Any) -> Self: ), ) - def _to_generated(self) -> GeneratedLogging: + @staticmethod + def _to_generated(logging: Optional["QueueAnalyticsLogging"]) -> Optional[GeneratedLogging]: + if logging is None: + return None return GeneratedLogging( - version=self.version, - delete=self.delete, - read=self.read, - write=self.write, - retention_policy=self.retention_policy._to_generated(), # pylint: disable=protected-access + version=logging.version, + delete=logging.delete, + read=logging.read, + write=logging.write, + retention_policy=logging.retention_policy._to_generated(), # pylint: disable=protected-access ) @@ -199,12 +202,15 @@ def _from_generated(cls, generated: Any) -> Self: ), ) - def _to_generated(self) -> GeneratedMetrics: + @staticmethod + def _to_generated(metrics: Optional["Metrics"]) -> Optional[GeneratedMetrics]: + if metrics is None: + return None return GeneratedMetrics( - version=self.version, - enabled=self.enabled, - include_apis=self.include_apis, - retention_policy=self.retention_policy._to_generated(), # pylint: disable=protected-access + version=metrics.version, + enabled=metrics.enabled, + include_apis=metrics.include_apis, + retention_policy=metrics.retention_policy._to_generated(), # pylint: disable=protected-access ) 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 b7092feb450c..d6e6a07a826e 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 @@ -18,6 +18,8 @@ from ._generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties from ._models import ( CorsRule, + Metrics, + QueueAnalyticsLogging, QueueProperties, QueuePropertiesPaged, service_properties_deserialize, @@ -45,7 +47,6 @@ TokenCredential, ) from datetime import datetime - from ._models import Metrics, QueueAnalyticsLogging from ._shared.models import UserDelegationKey @@ -380,13 +381,9 @@ def set_service_properties( :caption: Setting queue service properties. """ props = StorageServiceProperties( - logging=( - analytics_logging._to_generated() if analytics_logging else None # pylint: disable=protected-access - ), - hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access - minute_metrics=( - minute_metrics._to_generated() if minute_metrics else None # pylint: disable=protected-access - ), + logging=QueueAnalyticsLogging._to_generated(analytics_logging), # pylint: disable=protected-access + hour_metrics=Metrics._to_generated(hour_metrics), # pylint: disable=protected-access + minute_metrics=Metrics._to_generated(minute_metrics), # pylint: disable=protected-access cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: 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 84681af73ade..6be8c8539cb7 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 @@ -21,6 +21,8 @@ from .._generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties from .._models import ( CorsRule, + Metrics, + QueueAnalyticsLogging, QueueProperties, service_properties_deserialize, service_stats_deserialize, @@ -45,7 +47,6 @@ from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential from azure.core.credentials_async import AsyncTokenCredential from datetime import datetime - from .._models import Metrics, QueueAnalyticsLogging from .._shared.models import UserDelegationKey @@ -384,13 +385,9 @@ async def set_service_properties( :caption: Setting queue service properties. """ props = StorageServiceProperties( - logging=( - analytics_logging._to_generated() if analytics_logging else None # pylint: disable=protected-access - ), - hour_metrics=hour_metrics._to_generated() if hour_metrics else None, # pylint: disable=protected-access - minute_metrics=( - minute_metrics._to_generated() if minute_metrics else None # pylint: disable=protected-access - ), + logging=QueueAnalyticsLogging._to_generated(analytics_logging), # pylint: disable=protected-access + hour_metrics=Metrics._to_generated(hour_metrics), # pylint: disable=protected-access + minute_metrics=Metrics._to_generated(minute_metrics), # pylint: disable=protected-access cors=CorsRule._to_generated(cors), # pylint: disable=protected-access ) try: From fff857b4ba49276c3ecd225eb588b01bdde1196e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 12 Jun 2026 13:36:12 -0700 Subject: [PATCH 095/102] clean --- .../azure/storage/queue/_models.py | 17 ----------------- 1 file changed, 17 deletions(-) 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 79a9f0664951..70d6ae3ee27e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -49,11 +49,6 @@ class RetentionPolicy(_BackCompatMixin): days: Optional[int] = None """Indicates the number of days that metrics or logging or soft-deleted data should be retained.""" - _validation = { - "enabled": {"required": True}, - "days": {"minimum": 1}, - } - _attribute_map = { "enabled": {"key": "Enabled", "type": "bool"}, "days": {"key": "Days", "type": "int"}, @@ -172,10 +167,6 @@ class Metrics(_BackCompatMixin): retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" - _validation = { - "enabled": {"required": True}, - } - _attribute_map = { "version": {"key": "Version", "type": "str"}, "enabled": {"key": "Enabled", "type": "bool"}, @@ -258,14 +249,6 @@ class CorsRule(_BackCompatMixin): """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" - _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"}, From 017f8898d1f7a64df2a2a5412e6f985c931f67c4 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 12 Jun 2026 13:54:59 -0700 Subject: [PATCH 096/102] uploads slightly out of sync from blob --- .../azure/storage/queue/_shared/uploads.py | 20 +++++++++---------- .../storage/queue/_shared/uploads_async.py | 19 +++++++++--------- 2 files changed, 20 insertions(+), 19 deletions(-) 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 4da915577cdc..b2dc44770eec 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 @@ -55,6 +55,10 @@ def upload_data_chunks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, @@ -95,6 +99,10 @@ def upload_substream_blocks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, total_size=total_size, @@ -112,12 +120,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 +173,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.") 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 371525bdedc2..c1fa2a428dcc 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 @@ -73,6 +73,10 @@ async def upload_data_chunks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, @@ -119,6 +123,10 @@ async def upload_substream_blocks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, total_size=total_size, @@ -189,10 +197,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 @@ -438,11 +443,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 From ed6db4fde5ebcbeb5ca3e296ae828f8f019fbf00 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 12 Jun 2026 14:11:55 -0700 Subject: [PATCH 097/102] regen --- .../azure/storage/queue/_generated/models/_patch.py | 1 + 1 file changed, 1 insertion(+) 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 71e561394be9..d970ae08a96a 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,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. From 507c975bb82e0b9a2817ec36a6d83926f342e0d7 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 12 Jun 2026 14:53:55 -0700 Subject: [PATCH 098/102] validaiton --- .../azure/storage/queue/_models.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) 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 70d6ae3ee27e..79a9f0664951 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -49,6 +49,11 @@ class RetentionPolicy(_BackCompatMixin): days: Optional[int] = None """Indicates the number of days that metrics or logging or soft-deleted data should be retained.""" + _validation = { + "enabled": {"required": True}, + "days": {"minimum": 1}, + } + _attribute_map = { "enabled": {"key": "Enabled", "type": "bool"}, "days": {"key": "Days", "type": "int"}, @@ -167,6 +172,10 @@ class Metrics(_BackCompatMixin): retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" + _validation = { + "enabled": {"required": True}, + } + _attribute_map = { "version": {"key": "Version", "type": "str"}, "enabled": {"key": "Enabled", "type": "bool"}, @@ -249,6 +258,14 @@ class CorsRule(_BackCompatMixin): """The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.""" + _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"}, From 5ebcfb8ff195cbca82f83e5c66b30e778887e060 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 15 Jun 2026 15:43:17 -0700 Subject: [PATCH 099/102] _shared --- .../azure/storage/queue/_shared/response_handlers.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) 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 a5039c487fbb..c34a43bc7757 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 @@ -96,8 +96,14 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p ) if not storage_error.response or storage_error.response.status_code in [200, 204]: raise storage_error - # If it is one of those three then it has been serialized prior by the generated layer. - if isinstance( + # The generated layer now pre-maps 412 (Precondition Failed) responses to typed + # exceptions based on the request's match condition (e.g. ResourceExistsError for + # IfMissing, ResourceNotFoundError for IfPresent). Historically 412 was not + # pre-mapped and always flowed through the error-code mapping below, surfacing as + # ResourceModifiedError. Skip the "already serialized" shortcut for 412 so it is + # re-mapped from x-ms-error-code (ConditionNotMet -> ResourceModifiedError) and the + # public exception type is preserved for users. + if storage_error.response.status_code != 412 and isinstance( storage_error, ( PartialBatchErrorException, From 33a3fc712cd906c144e3ce9b7693190fe24bb852 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 16 Jun 2026 14:44:29 -0700 Subject: [PATCH 100/102] pass apiconsistency check --- sdk/storage/azure-storage-queue/api.md | 1444 +++++++++++++++++ .../azure-storage-queue/api.metadata.yml | 3 + 2 files changed, 1447 insertions(+) create mode 100644 sdk/storage/azure-storage-queue/api.md create mode 100644 sdk/storage/azure-storage-queue/api.metadata.yml diff --git a/sdk/storage/azure-storage-queue/api.md b/sdk/storage/azure-storage-queue/api.md new file mode 100644 index 000000000000..bced580c3b8b --- /dev/null +++ b/sdk/storage/azure-storage-queue/api.md @@ -0,0 +1,1444 @@ +```py +namespace azure.storage.queue + + def azure.storage.queue.generate_account_sas( + account_name: str, + account_key: str, + resource_types: Union[ResourceTypes, str], + permission: Union[AccountSasPermissions, str], + expiry: Union[datetime, str], + start: Optional[Union[datetime, str]] = None, + ip: Optional[str] = None, + *, + protocol: Optional[str] = ..., + services: Union[Services, str] = Services(queue=True), + sts_hook: Optional[Callable[[str], None]] = ..., + **kwargs: Any + ) -> str: ... + + + def azure.storage.queue.generate_queue_sas( + account_name: str, + queue_name: str, + account_key: Optional[str] = None, + permission: Optional[Union[QueueSasPermissions, str]] = None, + expiry: Optional[Union[datetime, str]] = None, + start: Optional[Union[datetime, str]] = None, + policy_id: Optional[str] = None, + ip: Optional[str] = None, + *, + protocol: Optional[str] = ..., + sts_hook: Optional[Callable[[str], None]] = ..., + user_delegation_key: Optional[UserDelegationKey] = ..., + user_delegation_oid: Optional[str] = ..., + **kwargs: Any + ) -> str: ... + + + class azure.storage.queue.AccessPolicy(_BackCompatMixin): + expiry: Optional[Union[datetime, str]] + permission: Optional[Union[QueueSasPermissions, str]] + start: Optional[Union[datetime, str]] + + def __eq__(self, other: Any) -> bool: ... + + def __init__( + self, + permission: Optional[Union[QueueSasPermissions, str]] = None, + expiry: Optional[Union[datetime, str]] = None, + start: Optional[Union[datetime, str]] = None + ) -> None: ... + + def __ne__(self, other: Any) -> bool: ... + + def __str__(self) -> str: ... + + @classmethod + def deserialize( + cls, + data: Any, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def enable_additional_properties_sending(cls) -> None: ... + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def is_xml_model(cls) -> bool: ... + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: ... + + def serialize( + self, + keep_readonly: bool = False, + **kwargs: Any + ) -> JSON: ... + + + class azure.storage.queue.AccountSasPermissions: + add: bool = False + create: bool = False + delete: bool = False + delete_previous_version: bool = False + filter_by_tags: bool = False + list: bool = False + permanent_delete: bool = False + process: bool = False + read: bool = False + set_immutability_policy: bool = False + tag: bool = False + update: bool = False + write: bool = False + + def __init__( + self, + read: bool = False, + write: bool = False, + delete: bool = False, + list: bool = False, + add: bool = False, + create: bool = False, + update: bool = False, + process: bool = False, + delete_previous_version: bool = False, + *, + filter_by_tags: Optional[bool] = ..., + permanent_delete: Optional[bool] = ..., + set_immutability_policy: Optional[bool] = ..., + tag: Optional[bool] = ..., + **kwargs + ) -> None: ... + + def __str__(self): ... + + @classmethod + def from_string(cls, permission: str) -> AccountSasPermissions: ... + + + class azure.storage.queue.BinaryBase64DecodePolicy(MessageDecodePolicy): + require_encryption = False + + def __call__( + self, + response: PipelineResponse, + obj: Iterable, + headers: Dict[str, Any] + ) -> object: ... + + def __init__(self) -> None: ... + + def configure( + self, + require_encryption: bool, + key_encryption_key: Optional[KeyEncryptionKey], + resolver: Optional[Callable[[str], KeyEncryptionKey]] + ) -> None: ... + + def decode( + self, + content: str, + response: PipelineResponse + ) -> bytes: ... + + + class azure.storage.queue.BinaryBase64EncodePolicy(MessageEncodePolicy): + + def __call__(self, content: Any) -> str: ... + + def __init__(self) -> None: ... + + def configure( + self, + require_encryption: bool, + key_encryption_key: Optional[KeyEncryptionKey], + resolver: Optional[Callable[[str], KeyEncryptionKey]], + encryption_version: str = _ENCRYPTION_PROTOCOL_V1 + ) -> None: ... + + def encode(self, content: bytes) -> str: ... + + + class azure.storage.queue.CorsRule(_BackCompatMixin): + allowed_headers: str + allowed_methods: str + allowed_origins: str + exposed_headers: str + max_age_in_seconds: int + + def __eq__(self, other: Any) -> bool: ... + + def __init__( + self, + allowed_origins: List[str], + allowed_methods: List[str], + *, + allowed_headers: Optional[List[str]] = ..., + exposed_headers: Optional[List[str]] = ..., + max_age_in_seconds: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + def __ne__(self, other: Any) -> bool: ... + + def __str__(self) -> str: ... + + @classmethod + def deserialize( + cls, + data: Any, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def enable_additional_properties_sending(cls) -> None: ... + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def is_xml_model(cls) -> bool: ... + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: ... + + def serialize( + self, + keep_readonly: bool = False, + **kwargs: Any + ) -> JSON: ... + + + class azure.storage.queue.ExponentialRetry(StorageRetryPolicy): + increment_base: int + initial_backoff: int + random_jitter_range: int + + def __init__( + self, + initial_backoff: int = 15, + increment_base: int = 3, + retry_total: int = 3, + retry_to_secondary: bool = False, + random_jitter_range: int = 3, + **kwargs: Any + ) -> None: ... + + def configure_retries(self, request: PipelineRequest) -> Dict[str, Any]: ... + + def get_backoff_time(self, settings: Dict[str, Any]) -> float: ... + + def increment( + self, + settings: Dict[str, Any], + request: PipelineRequest, + response: Optional[PipelineResponse] = None, + error: Optional[AzureError] = None + ) -> bool: ... + + def send(self, request: PipelineRequest) -> PipelineResponse: ... + + def sleep( + self, + settings, + transport: AsyncioBaseTransport or + ): ... + + + class azure.storage.queue.LinearRetry(StorageRetryPolicy): + initial_backoff: int + random_jitter_range: int + + def __init__( + self, + backoff: int = 15, + retry_total: int = 3, + retry_to_secondary: bool = False, + random_jitter_range: int = 3, + **kwargs: Any + ) -> None: ... + + def configure_retries(self, request: PipelineRequest) -> Dict[str, Any]: ... + + def get_backoff_time(self, settings: Dict[str, Any]) -> float: ... + + def increment( + self, + settings: Dict[str, Any], + request: PipelineRequest, + response: Optional[PipelineResponse] = None, + error: Optional[AzureError] = None + ) -> bool: ... + + def send(self, request: PipelineRequest) -> PipelineResponse: ... + + def sleep( + self, + settings, + transport: AsyncioBaseTransport or + ): ... + + + class azure.storage.queue.LocationMode: + PRIMARY = primary + SECONDARY = secondary + + + class azure.storage.queue.Metrics(_BackCompatMixin): + enabled: bool = False + include_apis: Optional[bool] + retention_policy: RetentionPolicy + version: str = "1.0" + + def __eq__(self, other: Any) -> bool: ... + + def __init__( + self, + *, + enabled: Optional[bool] = ..., + include_apis: Optional[bool] = ..., + retention_policy: Optional[RetentionPolicy] = ..., + version: Optional[str] = ..., + **kwargs: Any + ) -> None: ... + + def __ne__(self, other: Any) -> bool: ... + + def __str__(self) -> str: ... + + @classmethod + def deserialize( + cls, + data: Any, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def enable_additional_properties_sending(cls) -> None: ... + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def is_xml_model(cls) -> bool: ... + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: ... + + def serialize( + self, + keep_readonly: bool = False, + **kwargs: Any + ) -> JSON: ... + + + class azure.storage.queue.QueueAnalyticsLogging(_BackCompatMixin): + delete: bool = False + read: bool = False + retention_policy: RetentionPolicy + version: str = "1.0" + write: bool = False + + def __eq__(self, other: Any) -> bool: ... + + def __init__( + self, + *, + delete: Optional[bool] = ..., + read: Optional[bool] = ..., + retention_policy: Optional[RetentionPolicy] = ..., + version: Optional[str] = ..., + write: Optional[bool] = ..., + **kwargs: Any + ) -> None: ... + + def __ne__(self, other: Any) -> bool: ... + + def __str__(self) -> str: ... + + @classmethod + def deserialize( + cls, + data: Any, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def enable_additional_properties_sending(cls) -> None: ... + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def is_xml_model(cls) -> bool: ... + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: ... + + def serialize( + self, + keep_readonly: bool = False, + **kwargs: Any + ) -> JSON: ... + + + class azure.storage.queue.QueueClient(StorageAccountHostsMixin, StorageEncryptionMixin): implements ContextManager + property api_version: str # Read-only + property location_mode: str + property primary_endpoint: str # Read-only + property primary_hostname: str # Read-only + property secondary_endpoint: str # Read-only + property secondary_hostname: Optional[str] # Read-only + property url: str # Read-only + queue_name: str + + def __init__( + self, + account_url: str, + queue_name: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + message_decode_policy: Optional[Union[BinaryBase64DecodePolicy, TextBase64DecodePolicy]] = ..., + message_encode_policy: Optional[Union[BinaryBase64EncodePolicy, TextBase64EncodePolicy]] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> None: ... + + @classmethod + def from_connection_string( + cls, + conn_str: str, + queue_name: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + message_decode_policy: Optional[Union[BinaryBase64DecodePolicy, TextBase64DecodePolicy]] = ..., + message_encode_policy: Optional[Union[BinaryBase64EncodePolicy, TextBase64EncodePolicy]] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> Self: ... + + @classmethod + def from_queue_url( + cls, + queue_url: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + message_decode_policy: Optional[Union[BinaryBase64DecodePolicy, TextBase64DecodePolicy]] = ..., + message_encode_policy: Optional[Union[BinaryBase64EncodePolicy, TextBase64EncodePolicy]] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> Self: ... + + @distributed_trace + def clear_messages( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + def close(self) -> None: ... + + @distributed_trace + def create_queue( + self, + *, + metadata: Optional[Dict[str, str]] = ..., + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def delete_message( + self, + message: Union[str, QueueMessage], + pop_receipt: Optional[str] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def delete_queue( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def get_queue_access_policy( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, AccessPolicy]: ... + + @distributed_trace + def get_queue_properties( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueProperties: ... + + @distributed_trace + def peek_messages( + self, + max_messages: Optional[int] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> List[QueueMessage]: ... + + @distributed_trace + def receive_message( + self, + *, + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> Optional[QueueMessage]: ... + + @distributed_trace + def receive_messages( + self, + *, + max_messages: Optional[int] = ..., + messages_per_page: Optional[int] = ..., + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> ItemPaged[QueueMessage]: ... + + @distributed_trace + def send_message( + self, + content: Optional[object], + *, + time_to_live: Optional[int] = ..., + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueMessage: ... + + @distributed_trace + def set_queue_access_policy( + self, + signed_identifiers: Dict[str, AccessPolicy], + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def set_queue_metadata( + self, + metadata: Optional[Dict[str, str]] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, Any]: ... + + @distributed_trace + def update_message( + self, + message: Union[str, QueueMessage], + pop_receipt: Optional[str] = None, + content: Optional[object] = None, + *, + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueMessage: ... + + + class azure.storage.queue.QueueMessage(DictMixin): + content: Any + dequeue_count: Optional[int] + expires_on: Optional[datetime] + id: str + inserted_on: Optional[datetime] + next_visible_on: Optional[datetime] + pop_receipt: Optional[str] + + def __contains__(self, key): ... + + def __delitem__(self, key): ... + + def __eq__(self, other): ... + + def __getitem__(self, key): ... + + def __init__( + self, + content: Optional[Any] = None, + **kwargs: Any + ) -> None: ... + + def __len__(self): ... + + def __ne__(self, other): ... + + def __repr__(self): ... + + def __setitem__( + self, + key, + item + ): ... + + def __str__(self): ... + + def get( + self, + key, + default = None + ): ... + + def has_key(self, k): ... + + def items(self): ... + + def keys(self): ... + + def update( + self, + *args, + **kwargs + ): ... + + def values(self): ... + + + class azure.storage.queue.QueueProperties(DictMixin): + approximate_message_count: Optional[int] + metadata: Optional[Dict[str, str]] + name: str + + def __contains__(self, key): ... + + def __delitem__(self, key): ... + + def __eq__(self, other): ... + + def __getitem__(self, key): ... + + def __init__( + self, + *, + metadata: Optional[Dict[str, str]] = ..., + **kwargs: Any + ) -> None: ... + + def __len__(self): ... + + def __ne__(self, other): ... + + def __repr__(self): ... + + def __setitem__( + self, + key, + item + ): ... + + def __str__(self): ... + + def get( + self, + key, + default = None + ): ... + + def has_key(self, k): ... + + def items(self): ... + + def keys(self): ... + + def update( + self, + *args, + **kwargs + ): ... + + def values(self): ... + + + class azure.storage.queue.QueueSasPermissions: + add: bool = False + process: bool = False + read: bool = False + update: bool = False + + def __init__( + self, + read: bool = False, + add: bool = False, + update: bool = False, + process: bool = False + ) -> None: ... + + def __str__(self) -> str: ... + + @classmethod + def from_string(cls, permission: str) -> Self: ... + + + class azure.storage.queue.QueueServiceClient(StorageAccountHostsMixin, StorageEncryptionMixin): implements ContextManager + property api_version: str # Read-only + property location_mode: str + property primary_endpoint: str # Read-only + property primary_hostname: str # Read-only + property secondary_endpoint: str # Read-only + property secondary_hostname: Optional[str] # Read-only + property url: str # Read-only + + def __init__( + self, + account_url: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> None: ... + + @classmethod + def from_connection_string( + cls, + conn_str: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> Self: ... + + def close(self) -> None: ... + + @distributed_trace + def create_queue( + self, + name: str, + metadata: Optional[Dict[str, str]] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueClient: ... + + @distributed_trace + def delete_queue( + self, + queue: Union[QueueProperties, str], + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + def get_queue_client( + self, + queue: Union[QueueProperties, str], + **kwargs: Any + ) -> QueueClient: ... + + @distributed_trace + def get_service_properties( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, Any]: ... + + @distributed_trace + def get_service_stats( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, Any]: ... + + @distributed_trace + def get_user_delegation_key( + self, + *, + delegated_user_tid: Optional[str] = ..., + expiry: datetime, + start: Optional[datetime] = ..., + timeout: Optional[int] = ..., + **kwargs: Any + ) -> UserDelegationKey: ... + + @distributed_trace + def list_queues( + self, + name_starts_with: Optional[str] = None, + include_metadata: Optional[bool] = False, + *, + results_per_page: Optional[int] = ..., + timeout: Optional[int] = ..., + **kwargs: Any + ) -> ItemPaged[QueueProperties]: ... + + @distributed_trace + def set_service_properties( + self, + analytics_logging: Optional[QueueAnalyticsLogging] = None, + hour_metrics: Optional[Metrics] = None, + minute_metrics: Optional[Metrics] = None, + cors: Optional[List[CorsRule]] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + + class azure.storage.queue.ResourceTypes: + container: bool = False + object: bool = False + service: bool = False + + def __init__( + self, + service: bool = False, + container: bool = False, + object: bool = False + ) -> None: ... + + def __str__(self): ... + + @classmethod + def from_string(cls, string: str) -> ResourceTypes: ... + + + class azure.storage.queue.RetentionPolicy(_BackCompatMixin): + days: Optional[int] + enabled: bool = False + + def __eq__(self, other: Any) -> bool: ... + + def __init__( + self, + enabled: bool = False, + days: Optional[int] = None + ) -> None: ... + + def __ne__(self, other: Any) -> bool: ... + + def __str__(self) -> str: ... + + @classmethod + def deserialize( + cls, + data: Any, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def enable_additional_properties_sending(cls) -> None: ... + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None + ) -> Self: ... + + @classmethod + def is_xml_model(cls) -> bool: ... + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: ... + + def serialize( + self, + keep_readonly: bool = False, + **kwargs: Any + ) -> JSON: ... + + + class azure.storage.queue.Services: + + def __init__( + self, + *, + blob: bool = False, + fileshare: bool = False, + queue: bool = False + ) -> None: ... + + def __str__(self): ... + + @classmethod + def from_string(cls, string: str) -> Services: ... + + + class azure.storage.queue.StorageErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACCOUNT_ALREADY_EXISTS = "AccountAlreadyExists" + ACCOUNT_BEING_CREATED = "AccountBeingCreated" + ACCOUNT_IS_DISABLED = "AccountIsDisabled" + APPEND_POSITION_CONDITION_NOT_MET = "AppendPositionConditionNotMet" + AUTHENTICATION_FAILED = "AuthenticationFailed" + AUTHORIZATION_FAILURE = "AuthorizationFailure" + BLOB_ACCESS_TIER_NOT_SUPPORTED_FOR_ACCOUNT_TYPE = "BlobAccessTierNotSupportedForAccountType" + BLOB_ALREADY_EXISTS = "BlobAlreadyExists" + BLOB_ARCHIVED = "BlobArchived" + BLOB_BEING_REHYDRATED = "BlobBeingRehydrated" + BLOB_NOT_ARCHIVED = "BlobNotArchived" + BLOB_NOT_FOUND = "BlobNotFound" + BLOB_OVERWRITTEN = "BlobOverwritten" + BLOB_TIER_INADEQUATE_FOR_CONTENT_LENGTH = "BlobTierInadequateForContentLength" + BLOCK_COUNT_EXCEEDS_LIMIT = "BlockCountExceedsLimit" + BLOCK_LIST_TOO_LONG = "BlockListTooLong" + CANNOT_CHANGE_TO_LOWER_TIER = "CannotChangeToLowerTier" + CANNOT_DELETE_FILE_OR_DIRECTORY = "CannotDeleteFileOrDirectory" + CANNOT_VERIFY_COPY_SOURCE = "CannotVerifyCopySource" + CLIENT_CACHE_FLUSH_DELAY = "ClientCacheFlushDelay" + CONDITION_HEADERS_NOT_SUPPORTED = "ConditionHeadersNotSupported" + CONDITION_NOT_MET = "ConditionNotMet" + CONTAINER_ALREADY_EXISTS = "ContainerAlreadyExists" + CONTAINER_BEING_DELETED = "ContainerBeingDeleted" + CONTAINER_DISABLED = "ContainerDisabled" + CONTAINER_NOT_FOUND = "ContainerNotFound" + CONTAINER_QUOTA_DOWNGRADE_NOT_ALLOWED = "ContainerQuotaDowngradeNotAllowed" + CONTENT_LENGTH_LARGER_THAN_TIER_LIMIT = "ContentLengthLargerThanTierLimit" + CONTENT_LENGTH_MUST_BE_ZERO = "ContentLengthMustBeZero" + COPY_ACROSS_ACCOUNTS_NOT_SUPPORTED = "CopyAcrossAccountsNotSupported" + COPY_ID_MISMATCH = "CopyIdMismatch" + DELETE_PENDING = "DeletePending" + DESTINATION_PATH_IS_BEING_DELETED = "DestinationPathIsBeingDeleted" + DIRECTORY_NOT_EMPTY = "DirectoryNotEmpty" + EMPTY_METADATA_KEY = "EmptyMetadataKey" + FEATURE_VERSION_MISMATCH = "FeatureVersionMismatch" + FILE_LOCK_CONFLICT = "FileLockConflict" + FILE_SHARE_PROVISIONED_BANDWIDTH_DOWNGRADE_NOT_ALLOWED = "FileShareProvisionedBandwidthDowngradeNotAllowed" + FILE_SHARE_PROVISIONED_BANDWIDTH_INVALID = "FileShareProvisionedBandwidthInvalid" + FILE_SHARE_PROVISIONED_IOPS_DOWNGRADE_NOT_ALLOWED = "FileShareProvisionedIopsDowngradeNotAllowed" + FILE_SHARE_PROVISIONED_IOPS_INVALID = "FileShareProvisionedIopsInvalid" + FILE_SHARE_PROVISIONED_STORAGE_INVALID = "FileShareProvisionedStorageInvalid" + FILE_SYSTEM_ALREADY_EXISTS = "FilesystemAlreadyExists" + FILE_SYSTEM_BEING_DELETED = "FilesystemBeingDeleted" + FILE_SYSTEM_NOT_FOUND = "FilesystemNotFound" + INCREMENTAL_COPY_BLOB_MISMATCH = "IncrementalCopyBlobMismatch" + INCREMENTAL_COPY_OF_EARLIER_SNAPSHOT_NOT_ALLOWED = "IncrementalCopyOfEarlierSnapshotNotAllowed" + INCREMENTAL_COPY_OF_EARLIER_VERSION_SNAPSHOT_NOT_ALLOWED = "IncrementalCopyOfEarlierVersionSnapshotNotAllowed" + INCREMENTAL_COPY_OF_ERALIER_VERSION_SNAPSHOT_NOT_ALLOWED = "IncrementalCopyOfEarlierVersionSnapshotNotAllowed" + INCREMENTAL_COPY_SOURCE_MUST_BE_SNAPSHOT = "IncrementalCopySourceMustBeSnapshot" + INFINITE_LEASE_DURATION_REQUIRED = "InfiniteLeaseDurationRequired" + INSUFFICIENT_ACCOUNT_PERMISSIONS = "InsufficientAccountPermissions" + INTERNAL_ERROR = "InternalError" + INVALID_AUTHENTICATION_INFO = "InvalidAuthenticationInfo" + INVALID_BLOB_OR_BLOCK = "InvalidBlobOrBlock" + INVALID_BLOB_TIER = "InvalidBlobTier" + INVALID_BLOB_TYPE = "InvalidBlobType" + INVALID_BLOCK_ID = "InvalidBlockId" + INVALID_BLOCK_LIST = "InvalidBlockList" + INVALID_DESTINATION_PATH = "InvalidDestinationPath" + INVALID_FILE_OR_DIRECTORY_PATH_NAME = "InvalidFileOrDirectoryPathName" + INVALID_FLUSH_POSITION = "InvalidFlushPosition" + INVALID_HEADER_VALUE = "InvalidHeaderValue" + INVALID_HTTP_VERB = "InvalidHttpVerb" + INVALID_INPUT = "InvalidInput" + INVALID_MARKER = "InvalidMarker" + INVALID_MD5 = "InvalidMd5" + INVALID_METADATA = "InvalidMetadata" + INVALID_OPERATION = "InvalidOperation" + INVALID_PAGE_RANGE = "InvalidPageRange" + INVALID_PROPERTY_NAME = "InvalidPropertyName" + INVALID_QUERY_PARAMETER_VALUE = "InvalidQueryParameterValue" + INVALID_RANGE = "InvalidRange" + INVALID_RENAME_SOURCE_PATH = "InvalidRenameSourcePath" + INVALID_RESOURCE_NAME = "InvalidResourceName" + INVALID_SOURCE_BLOB_TYPE = "InvalidSourceBlobType" + INVALID_SOURCE_BLOB_URL = "InvalidSourceBlobUrl" + INVALID_SOURCE_OR_DESTINATION_RESOURCE_TYPE = "InvalidSourceOrDestinationResourceType" + INVALID_SOURCE_URI = "InvalidSourceUri" + INVALID_URI = "InvalidUri" + INVALID_VERSION_FOR_PAGE_BLOB_OPERATION = "InvalidVersionForPageBlobOperation" + INVALID_XML_DOCUMENT = "InvalidXmlDocument" + INVALID_XML_NODE_VALUE = "InvalidXmlNodeValue" + LEASE_ALREADY_BROKEN = "LeaseAlreadyBroken" + LEASE_ALREADY_PRESENT = "LeaseAlreadyPresent" + LEASE_ID_MISMATCH_WITH_BLOB_OPERATION = "LeaseIdMismatchWithBlobOperation" + LEASE_ID_MISMATCH_WITH_CONTAINER_OPERATION = "LeaseIdMismatchWithContainerOperation" + LEASE_ID_MISMATCH_WITH_LEASE_OPERATION = "LeaseIdMismatchWithLeaseOperation" + LEASE_ID_MISSING = "LeaseIdMissing" + LEASE_IS_ALREADY_BROKEN = "LeaseIsAlreadyBroken" + LEASE_IS_BREAKING_AND_CANNOT_BE_ACQUIRED = "LeaseIsBreakingAndCannotBeAcquired" + LEASE_IS_BREAKING_AND_CANNOT_BE_CHANGED = "LeaseIsBreakingAndCannotBeChanged" + LEASE_IS_BROKEN_AND_CANNOT_BE_RENEWED = "LeaseIsBrokenAndCannotBeRenewed" + LEASE_LOST = "LeaseLost" + LEASE_NAME_MISMATCH = "LeaseNameMismatch" + LEASE_NOT_PRESENT_WITH_BLOB_OPERATION = "LeaseNotPresentWithBlobOperation" + LEASE_NOT_PRESENT_WITH_CONTAINER_OPERATION = "LeaseNotPresentWithContainerOperation" + LEASE_NOT_PRESENT_WITH_LEASE_OPERATION = "LeaseNotPresentWithLeaseOperation" + MAX_BLOB_SIZE_CONDITION_NOT_MET = "MaxBlobSizeConditionNotMet" + MD5_MISMATCH = "Md5Mismatch" + MESSAGE_NOT_FOUND = "MessageNotFound" + MESSAGE_TOO_LARGE = "MessageTooLarge" + METADATA_TOO_LARGE = "MetadataTooLarge" + MISSING_CONTENT_LENGTH_HEADER = "MissingContentLengthHeader" + MISSING_REQUIRED_HEADER = "MissingRequiredHeader" + MISSING_REQUIRED_QUERY_PARAMETER = "MissingRequiredQueryParameter" + MISSING_REQUIRED_XML_NODE = "MissingRequiredXmlNode" + MULTIPLE_CONDITION_HEADERS_NOT_SUPPORTED = "MultipleConditionHeadersNotSupported" + NO_AUTHENTICATION_INFORMATION = "NoAuthenticationInformation" + NO_PENDING_COPY_OPERATION = "NoPendingCopyOperation" + OPERATION_NOT_ALLOWED_ON_INCREMENTAL_COPY_BLOB = "OperationNotAllowedOnIncrementalCopyBlob" + OPERATION_TIMED_OUT = "OperationTimedOut" + OUT_OF_RANGE_INPUT = "OutOfRangeInput" + OUT_OF_RANGE_QUERY_PARAMETER_VALUE = "OutOfRangeQueryParameterValue" + PARENT_NOT_FOUND = "ParentNotFound" + PATH_ALREADY_EXISTS = "PathAlreadyExists" + PATH_CONFLICT = "PathConflict" + PATH_NOT_FOUND = "PathNotFound" + PENDING_COPY_OPERATION = "PendingCopyOperation" + POP_RECEIPT_MISMATCH = "PopReceiptMismatch" + PREVIOUS_SNAPSHOT_CANNOT_BE_NEWER = "PreviousSnapshotCannotBeNewer" + PREVIOUS_SNAPSHOT_NOT_FOUND = "PreviousSnapshotNotFound" + PREVIOUS_SNAPSHOT_OPERATION_NOT_SUPPORTED = "PreviousSnapshotOperationNotSupported" + QUEUE_ALREADY_EXISTS = "QueueAlreadyExists" + QUEUE_BEING_DELETED = "QueueBeingDeleted" + QUEUE_DISABLED = "QueueDisabled" + QUEUE_NOT_EMPTY = "QueueNotEmpty" + QUEUE_NOT_FOUND = "QueueNotFound" + READ_ONLY_ATTRIBUTE = "ReadOnlyAttribute" + RENAME_DESTINATION_PARENT_PATH_NOT_FOUND = "RenameDestinationParentPathNotFound" + REQUEST_BODY_TOO_LARGE = "RequestBodyTooLarge" + REQUEST_URL_FAILED_TO_PARSE = "RequestUrlFailedToParse" + RESOURCE_ALREADY_EXISTS = "ResourceAlreadyExists" + RESOURCE_NOT_FOUND = "ResourceNotFound" + RESOURCE_TYPE_MISMATCH = "ResourceTypeMismatch" + SEQUENCE_NUMBER_CONDITION_NOT_MET = "SequenceNumberConditionNotMet" + SEQUENCE_NUMBER_INCREMENT_TOO_LARGE = "SequenceNumberIncrementTooLarge" + SERVER_BUSY = "ServerBusy" + SHARE_ALREADY_EXISTS = "ShareAlreadyExists" + SHARE_BEING_DELETED = "ShareBeingDeleted" + SHARE_DISABLED = "ShareDisabled" + SHARE_HAS_SNAPSHOTS = "ShareHasSnapshots" + SHARE_NOT_FOUND = "ShareNotFound" + SHARE_SNAPSHOT_COUNT_EXCEEDED = "ShareSnapshotCountExceeded" + SHARE_SNAPSHOT_IN_PROGRESS = "ShareSnapshotInProgress" + SHARE_SNAPSHOT_NOT_FOUND = "ShareSnapshotNotFound" + SHARE_SNAPSHOT_OPERATION_NOT_SUPPORTED = "ShareSnapshotOperationNotSupported" + SHARING_VIOLATION = "SharingViolation" + SNAPHOT_OPERATION_RATE_EXCEEDED = "SnapshotOperationRateExceeded" + SNAPSHOTS_PRESENT = "SnapshotsPresent" + SNAPSHOT_COUNT_EXCEEDED = "SnapshotCountExceeded" + SNAPSHOT_OPERATION_RATE_EXCEEDED = "SnapshotOperationRateExceeded" + SOURCE_CONDITION_NOT_MET = "SourceConditionNotMet" + SOURCE_PATH_IS_BEING_DELETED = "SourcePathIsBeingDeleted" + SOURCE_PATH_NOT_FOUND = "SourcePathNotFound" + SYSTEM_IN_USE = "SystemInUse" + TARGET_CONDITION_NOT_MET = "TargetConditionNotMet" + TOTAL_SHARES_COUNT_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesCountExceedsAccountLimit" + TOTAL_SHARES_PROVISIONED_BANDWIDTH_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesProvisionedBandwidthExceedsAccountLimit" + TOTAL_SHARES_PROVISIONED_CAPACITY_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesProvisionedCapacityExceedsAccountLimit" + TOTAL_SHARES_PROVISIONED_IOPS_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesProvisionedIopsExceedsAccountLimit" + UNAUTHORIZED_BLOB_OVERWRITE = "UnauthorizedBlobOverwrite" + UNSUPPORTED_HEADER = "UnsupportedHeader" + UNSUPPORTED_HTTP_VERB = "UnsupportedHttpVerb" + UNSUPPORTED_QUERY_PARAMETER = "UnsupportedQueryParameter" + UNSUPPORTED_REST_VERSION = "UnsupportedRestVersion" + UNSUPPORTED_XML_NODE = "UnsupportedXmlNode" + + + class azure.storage.queue.TextBase64DecodePolicy(MessageDecodePolicy): + require_encryption = False + + def __call__( + self, + response: PipelineResponse, + obj: Iterable, + headers: Dict[str, Any] + ) -> object: ... + + def __init__(self) -> None: ... + + def configure( + self, + require_encryption: bool, + key_encryption_key: Optional[KeyEncryptionKey], + resolver: Optional[Callable[[str], KeyEncryptionKey]] + ) -> None: ... + + def decode( + self, + content: str, + response: PipelineResponse + ) -> str: ... + + + class azure.storage.queue.TextBase64EncodePolicy(MessageEncodePolicy): + + def __call__(self, content: Any) -> str: ... + + def __init__(self) -> None: ... + + def configure( + self, + require_encryption: bool, + key_encryption_key: Optional[KeyEncryptionKey], + resolver: Optional[Callable[[str], KeyEncryptionKey]], + encryption_version: str = _ENCRYPTION_PROTOCOL_V1 + ) -> None: ... + + def encode(self, content: str) -> str: ... + + + class azure.storage.queue.UserDelegationKey: + signed_delegated_user_tid: Optional[str] + signed_expiry: Optional[str] + signed_oid: Optional[str] + signed_service: Optional[str] + signed_start: Optional[str] + signed_tid: Optional[str] + signed_version: Optional[str] + value: Optional[str] + + def __init__(self): ... + + +namespace azure.storage.queue.aio + + class azure.storage.queue.aio.QueueClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin, StorageEncryptionMixin): implements AsyncContextManager + property api_version: str # Read-only + property location_mode: str + property primary_endpoint: str # Read-only + property primary_hostname: str # Read-only + property secondary_endpoint: str # Read-only + property secondary_hostname: Optional[str] # Read-only + property url: str # Read-only + queue_name: str + + def __init__( + self, + account_url: str, + queue_name: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + message_decode_policy: Optional[Union[BinaryBase64DecodePolicy, TextBase64DecodePolicy]] = ..., + message_encode_policy: Optional[Union[BinaryBase64EncodePolicy, TextBase64EncodePolicy]] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> None: ... + + @classmethod + def from_connection_string( + cls, + conn_str: str, + queue_name: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + message_decode_policy: Optional[Union[BinaryBase64DecodePolicy, TextBase64DecodePolicy]] = ..., + message_encode_policy: Optional[Union[BinaryBase64EncodePolicy, TextBase64EncodePolicy]] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> Self: ... + + @classmethod + def from_queue_url( + cls, + queue_url: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + message_decode_policy: Optional[Union[BinaryBase64DecodePolicy, TextBase64DecodePolicy]] = ..., + message_encode_policy: Optional[Union[BinaryBase64EncodePolicy, TextBase64EncodePolicy]] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> Self: ... + + @distributed_trace_async + async def clear_messages( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + async def close(self) -> None: ... + + @distributed_trace_async + async def create_queue( + self, + *, + metadata: Optional[Dict[str, str]] = ..., + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def delete_message( + self, + message: Union[str, QueueMessage], + pop_receipt: Optional[str] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def delete_queue( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def get_queue_access_policy( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, AccessPolicy]: ... + + @distributed_trace_async + async def get_queue_properties( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueProperties: ... + + @distributed_trace_async + async def peek_messages( + self, + max_messages: Optional[int] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> List[QueueMessage]: ... + + @distributed_trace_async + async def receive_message( + self, + *, + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> Optional[QueueMessage]: ... + + @distributed_trace + def receive_messages( + self, + *, + max_messages: Optional[int] = ..., + messages_per_page: Optional[int] = ..., + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> AsyncItemPaged[QueueMessage]: ... + + @distributed_trace_async + async def send_message( + self, + content: Optional[object], + *, + time_to_live: Optional[int] = ..., + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueMessage: ... + + @distributed_trace_async + async def set_queue_access_policy( + self, + signed_identifiers: Dict[str, AccessPolicy], + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def set_queue_metadata( + self, + metadata: Optional[Dict[str, str]] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, Any]: ... + + @distributed_trace_async + async def update_message( + self, + message: Union[str, QueueMessage], + pop_receipt: Optional[str] = None, + content: Optional[object] = None, + *, + timeout: Optional[int] = ..., + visibility_timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueMessage: ... + + + class azure.storage.queue.aio.QueueServiceClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin, StorageEncryptionMixin): implements AsyncContextManager + property api_version: str # Read-only + property location_mode: str + property primary_endpoint: str # Read-only + property primary_hostname: str # Read-only + property secondary_endpoint: str # Read-only + property secondary_hostname: Optional[str] # Read-only + property url: str # Read-only + + def __init__( + self, + account_url: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> None: ... + + @classmethod + def from_connection_string( + cls, + conn_str: str, + credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, AsyncTokenCredential]] = None, + *, + api_version: Optional[str] = ..., + audience: Optional[str] = ..., + secondary_hostname: Optional[str] = ..., + **kwargs: Any + ) -> Self: ... + + async def close(self) -> None: ... + + @distributed_trace_async + async def create_queue( + self, + name: str, + metadata: Optional[Dict[str, str]] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> QueueClient: ... + + @distributed_trace_async + async def delete_queue( + self, + queue: Union[QueueProperties, str], + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + def get_queue_client( + self, + queue: Union[QueueProperties, str], + **kwargs: Any + ) -> QueueClient: ... + + @distributed_trace_async + async def get_service_properties( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, Any]: ... + + @distributed_trace_async + async def get_service_stats( + self, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> Dict[str, Any]: ... + + @distributed_trace_async + async def get_user_delegation_key( + self, + *, + delegated_user_tid: Optional[str] = ..., + expiry: datetime, + start: Optional[datetime] = ..., + timeout: Optional[int] = ..., + **kwargs: Any + ) -> UserDelegationKey: ... + + @distributed_trace + def list_queues( + self, + name_starts_with: Optional[str] = None, + include_metadata: Optional[bool] = False, + *, + results_per_page: Optional[int] = ..., + timeout: Optional[int] = ..., + **kwargs: Any + ) -> AsyncItemPaged: ... + + @distributed_trace_async + async def set_service_properties( + self, + analytics_logging: Optional[QueueAnalyticsLogging] = None, + hour_metrics: Optional[Metrics] = None, + minute_metrics: Optional[Metrics] = None, + cors: Optional[List[CorsRule]] = None, + *, + timeout: Optional[int] = ..., + **kwargs: Any + ) -> None: ... + + +``` \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/api.metadata.yml b/sdk/storage/azure-storage-queue/api.metadata.yml new file mode 100644 index 000000000000..4565e0d8f2ff --- /dev/null +++ b/sdk/storage/azure-storage-queue/api.metadata.yml @@ -0,0 +1,3 @@ +apiMdSha256: f44cff7f34be5e007ec8b69b8de79f840f53561af6372a881d4e8c56b712078d +parserVersion: 0.3.28 +pythonVersion: 3.13.9 From b290a753652cdfa93a7cdef6f75a1b88999fb976 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 18 Jun 2026 11:57:02 -0700 Subject: [PATCH 101/102] remove hack --- .../azure/storage/queue/_shared/policies.py | 6 ------ 1 file changed, 6 deletions(-) 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 3755660cc4c6..86d0b3f88c98 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 @@ -147,12 +147,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) From e38f05ec1bb6ffcc89f6d0afe8bc7113b0b58365 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 18 Jun 2026 12:11:36 -0700 Subject: [PATCH 102/102] remove blob/datalake tsp changes --- .../azure/storage/queue/_shared/uploads.py | 40 ++++++++++--------- .../storage/queue/_shared/uploads_async.py | 37 ++++++++--------- 2 files changed, 40 insertions(+), 37 deletions(-) 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 b2dc44770eec..341d034fd07c 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 @@ -55,10 +55,6 @@ def upload_data_chunks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None - if parallel: - # Access conditions do not work with parallelism - kwargs.pop("etag", None) - kwargs.pop("match_condition", None) uploader = uploader_class( service=service, @@ -99,10 +95,6 @@ def upload_substream_blocks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None - if parallel: - # Access conditions do not work with parallelism - kwargs.pop("etag", None) - kwargs.pop("match_condition", None) uploader = uploader_class( service=service, total_size=total_size, @@ -120,7 +112,12 @@ 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): @@ -173,7 +170,10 @@ 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 +269,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=block_id, - content_length=len(chunk_data), - body=chunk_data, + block_id, + len(chunk_data), + chunk_data, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -282,9 +282,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=block_id, - content_length=len(block_stream), - body=block_stream, + block_id, + len(block_stream), + block_stream, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -318,8 +318,8 @@ def _upload_chunk(self, chunk_offset, chunk_data): **self.request_options, ) - if not self.parallel and self.request_options.get("etag"): - self.request_options["etag"] = self.response_headers["etag"] + if not self.parallel and self.request_options.get("modified_access_conditions"): + self.request_options["modified_access_conditions"].if_match = self.response_headers["etag"] def _upload_substream_block(self, index, block_stream): pass @@ -343,7 +343,9 @@ def _upload_chunk(self, chunk_offset, chunk_data): ) self.current_length = int(self.response_headers["blob_append_offset"]) else: - self.request_options["append_position"] = self.current_length + chunk_offset + self.request_options["append_position_access_conditions"].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 c1fa2a428dcc..388429a288a4 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 @@ -73,10 +73,6 @@ async def upload_data_chunks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None - if parallel: - # Access conditions do not work with parallelism - kwargs.pop("etag", None) - kwargs.pop("match_condition", None) uploader = uploader_class( service=service, @@ -123,10 +119,6 @@ async def upload_substream_blocks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None - if parallel: - # Access conditions do not work with parallelism - kwargs.pop("etag", None) - kwargs.pop("match_condition", None) uploader = uploader_class( service=service, total_size=total_size, @@ -197,7 +189,10 @@ 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 @@ -295,8 +290,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=block_id, - content_length=len(chunk_data), + block_id, + len(chunk_data), body=chunk_data, data_stream_total=self.total_size, upload_stream_current=self.progress_total, @@ -308,9 +303,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=block_id, - content_length=len(block_stream), - body=block_stream, + block_id, + len(block_stream), + block_stream, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -347,8 +342,8 @@ async def _upload_chunk(self, chunk_offset, chunk_data): **self.request_options, ) - if not self.parallel and self.request_options.get("etag"): - self.request_options["etag"] = self.response_headers["etag"] + if not self.parallel and self.request_options.get("modified_access_conditions"): + self.request_options["modified_access_conditions"].if_match = self.response_headers["etag"] async def _upload_substream_block(self, index, block_stream): pass @@ -372,7 +367,9 @@ 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"] = self.current_length + chunk_offset + self.request_options["append_position_access_conditions"].append_position = ( + self.current_length + chunk_offset + ) self.response_headers = await self.service.append_block( body=chunk_data, content_length=len(chunk_data), @@ -443,7 +440,11 @@ 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