diff --git a/sdk/storage/azure-storage-queue/MANIFEST.in b/sdk/storage/azure-storage-queue/MANIFEST.in index f2919ebac602..8e7ae2ff16fb 100644 --- a/sdk/storage/azure-storage-queue/MANIFEST.in +++ b/sdk/storage/azure-storage-queue/MANIFEST.in @@ -1,7 +1,7 @@ include *.md -include azure/__init__.py -include azure/storage/__init__.py include LICENSE +include azure/storage/queue/py.typed recursive-include tests *.py recursive-include samples *.py *.md -include azure/storage/queue/py.typed +include azure/__init__.py +include azure/storage/__init__.py diff --git a/sdk/storage/azure-storage-queue/_metadata.json b/sdk/storage/azure-storage-queue/_metadata.json new file mode 100644 index 000000000000..722c39b95657 --- /dev/null +++ b/sdk/storage/azure-storage-queue/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersion": "2026-04-06", + "apiVersions": { + "Storage.Queues": "2026-04-06" + } +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/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 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..d46f9ede0085 --- /dev/null +++ b/sdk/storage/azure-storage-queue/apiview-properties.json @@ -0,0 +1,65 @@ +{ + "CrossLanguagePackageId": "Storage.Queues", + "CrossLanguageDefinitionId": { + "azure.storage.queue.models.AccessPolicy": "Storage.Queues.AccessPolicy", + "azure.storage.queue.models.CorsRule": "Storage.Queues.CorsRule", + "azure.storage.queue.models.Error": "Storage.Queues.Error", + "azure.storage.queue.models.GeoReplication": "Storage.Queues.GeoReplication", + "azure.storage.queue.models.KeyInfo": "Storage.Queues.KeyInfo", + "azure.storage.queue.models.ListOfSentMessage": "Storage.Queues.ListOfSentMessage", + "azure.storage.queue.models.ListQueuesResponse": "Storage.Queues.ListQueuesResponse", + "azure.storage.queue.models.Logging": "Storage.Queues.Logging", + "azure.storage.queue.models.Metrics": "Storage.Queues.Metrics", + "azure.storage.queue.models.PeekedMessage": "Storage.Queues.PeekedMessage", + "azure.storage.queue.models.PeekedMessages": "Storage.Queues.PeekedMessages", + "azure.storage.queue.models.QueueItem": "Storage.Queues.QueueItem", + "azure.storage.queue.models.QueueMessage": "Storage.Queues.QueueMessage", + "azure.storage.queue.models.QueueServiceProperties": "Storage.Queues.QueueServiceProperties", + "azure.storage.queue.models.QueueServiceStats": "Storage.Queues.QueueServiceStats", + "azure.storage.queue.models.ReceivedMessage": "Storage.Queues.ReceivedMessage", + "azure.storage.queue.models.ReceivedMessages": "Storage.Queues.ReceivedMessages", + "azure.storage.queue.models.RetentionPolicy": "Storage.Queues.RetentionPolicy", + "azure.storage.queue.models.SentMessage": "Storage.Queues.SentMessage", + "azure.storage.queue.models.SignedIdentifier": "Storage.Queues.SignedIdentifier", + "azure.storage.queue.models.SignedIdentifiers": "Storage.Queues.SignedIdentifiers", + "azure.storage.queue.models.UserDelegationKey": "Storage.Queues.UserDelegationKey", + "azure.storage.queue.models.StorageErrorCode": "Storage.Queues.StorageErrorCode", + "azure.storage.queue.models.GeoReplicationStatus": "Storage.Queues.GeoReplicationStatus", + "azure.storage.queue.models.ListQueuesIncludeType": "Storage.Queues.ListQueuesIncludeType", + "azure.storage.queue.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", + "azure.storage.queue.aio.operations.ServiceOperations.set_properties": "Storage.Queues.Service.setProperties", + "azure.storage.queue.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", + "azure.storage.queue.aio.operations.ServiceOperations.get_properties": "Storage.Queues.Service.getProperties", + "azure.storage.queue.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", + "azure.storage.queue.aio.operations.ServiceOperations.get_statistics": "Storage.Queues.Service.getStatistics", + "azure.storage.queue.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", + "azure.storage.queue.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.Queues.Service.getUserDelegationKey", + "azure.storage.queue.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", + "azure.storage.queue.aio.operations.ServiceOperations.get_queues": "Storage.Queues.Service.getQueues", + "azure.storage.queue.operations.QueueOperations.create": "Storage.Queues.Queue.create", + "azure.storage.queue.aio.operations.QueueOperations.create": "Storage.Queues.Queue.create", + "azure.storage.queue.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", + "azure.storage.queue.aio.operations.QueueOperations.get_properties": "Storage.Queues.Queue.getProperties", + "azure.storage.queue.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", + "azure.storage.queue.aio.operations.QueueOperations.delete": "Storage.Queues.Queue.delete", + "azure.storage.queue.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", + "azure.storage.queue.aio.operations.QueueOperations.set_metadata": "Storage.Queues.Queue.setMetadata", + "azure.storage.queue.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", + "azure.storage.queue.aio.operations.QueueOperations.get_access_policy": "Storage.Queues.Queue.getAccessPolicy", + "azure.storage.queue.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", + "azure.storage.queue.aio.operations.QueueOperations.set_access_policy": "Storage.Queues.Queue.setAccessPolicy", + "azure.storage.queue.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", + "azure.storage.queue.aio.operations.QueueOperations.receive_messages": "Storage.Queues.Queue.receiveMessages", + "azure.storage.queue.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", + "azure.storage.queue.aio.operations.QueueOperations.clear": "Storage.Queues.Queue.clear", + "azure.storage.queue.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", + "azure.storage.queue.aio.operations.QueueOperations.send_message": "Storage.Queues.Queue.sendMessage", + "azure.storage.queue.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", + "azure.storage.queue.aio.operations.QueueOperations.peek_messages": "Storage.Queues.Queue.peekMessages", + "azure.storage.queue.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", + "azure.storage.queue.aio.operations.QueueOperations.update_message": "Storage.Queues.Queue.updateMessage", + "azure.storage.queue.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage", + "azure.storage.queue.aio.operations.QueueOperations.delete_message": "Storage.Queues.Queue.deleteMessage" + }, + "CrossLanguageVersion": "93cf2ffb7d42" +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py index a743737977f3..0fe6e78452f5 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,10 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._azure_queue_storage import AzureQueueStorage # type: ignore +from ._client import QueuesClient # type: ignore +from ._version import VERSION + +__version__ = VERSION try: from ._patch import __all__ as _patch_all @@ -22,7 +25,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureQueueStorage", + "QueuesClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_azure_queue_storage.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py similarity index 59% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_azure_queue_storage.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py index 688769fac8c3..02c93c2b9c4e 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_azure_queue_storage.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_client.py @@ -2,53 +2,53 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any -from typing_extensions import Self +import sys +from typing import Any, TYPE_CHECKING from azure.core import PipelineClient from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import AzureQueueStorageConfiguration +from ._configuration import QueuesClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import ( - MessageIdOperations, - MessagesOperations, - QueueOperations, - ServiceOperations, -) +from .operations import QueueOperations, ServiceOperations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore -class AzureQueueStorage: # pylint: disable=client-accepts-api-version-keyword - """AzureQueueStorage. +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class QueuesClient: # pylint: disable=client-accepts-api-version-keyword + """QueuesClient. :ivar service: ServiceOperations operations :vartype service: azure.storage.queue.operations.ServiceOperations :ivar queue: QueueOperations operations :vartype queue: azure.storage.queue.operations.QueueOperations - :ivar messages: MessagesOperations operations - :vartype messages: azure.storage.queue.operations.MessagesOperations - :ivar message_id: MessageIdOperations operations - :vartype message_id: azure.storage.queue.operations.MessageIdOperations - :param url: The URL of the service account, queue or message that is the target of the desired - operation. Required. + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. :type url: str - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str - :param base_url: Service URL. Required. Default value is "". - :type base_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06" 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 """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, url: str, version: str, base_url: str = "", **kwargs: Any - ) -> None: - self._config = AzureQueueStorageConfiguration(url=url, version=version, **kwargs) + def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{url}" + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -64,27 +64,24 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._config.custom_hook_policy, self._config.logging_policy, policies.DistributedTracingPolicy(**kwargs), - (policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: PipelineClient = PipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) - self.messages = MessagesOperations(self._client, self._config, self._serialize, self._deserialize) - self.message_id = MessageIdOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -97,7 +94,11 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_configuration.py index 04adef0da253..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 @@ -2,39 +2,51 @@ # -------------------------------------------------------------------------- # 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 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 """ - 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 +60,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_patch.py index 4688ca7f8ac2..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 @@ -1,33 +1,98 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core import PipelineClient + +from ._configuration import QueuesClientConfiguration as QueuesClientConfigurationInternal +from ._utils.serialization import Deserializer, Serializer +from .operations import QueueOperations, ServiceOperations +from ._client import QueuesClient as QueuesClientInternal +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class QueuesClientConfiguration(QueuesClientConfigurationInternal): + """Configuration for QueuesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. + :type url: str + :param credential: Credential used to authenticate requests to the service. + :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: + 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. + + :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) + if _pipeline is not None: + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) + self._client: PipelineClient = PipelineClient(base_url="{url}", pipeline=_pipeline) + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) + else: + super().__init__(url, credential, **kwargs) + + +__all__: list[str] = ["QueuesClient"] def patch_sdk(): - pass + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py index 0af9b28f6607..8026245c2abc 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/__init__.py @@ -1,6 +1,6 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py new file mode 100644 index 000000000000..bd5b9caf1022 --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/model_base.py @@ -0,0 +1,1755 @@ +# 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 +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"] + +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) + + +# ============================================================================ +# 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 + # 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: dict[str, typing.Any] = {} + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + # 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( # 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. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + 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, 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] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + # 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) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + original_tsp_name: typing.Optional[str] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._deserializer = deserializer + 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, _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: + 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) + + # 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 + 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, + deserializer: typing.Optional[typing.Callable] = 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, + deserializer=deserializer, + original_tsp_name=original_tsp_name, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_utils/serialization.py index adacf7b3e18a..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 @@ -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. # -------------------------------------------------------------------------- @@ -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] @@ -235,17 +239,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 +292,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 +453,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 +920,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 +1157,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: @@ -1426,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. @@ -1436,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) @@ -1454,10 +1454,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 +1572,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 +1874,7 @@ def deserialize_enum(data, enum_obj): if enum_value.value.lower() == str(data).lower(): return enum_value # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning( - "Deserializer is not able to find %s as valid enum in %s", - data, - enum_obj, - ) + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) return Deserializer.deserialize_unicode(data) @staticmethod diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py new file mode 100644 index 000000000000..195162b92aac --- /dev/null +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "12.18.0b1" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py index a743737977f3..e6fceae27b60 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._azure_queue_storage import AzureQueueStorage # type: ignore +from ._client import QueuesClient # type: ignore try: from ._patch import __all__ as _patch_all @@ -22,7 +22,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureQueueStorage", + "QueuesClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_azure_queue_storage.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py similarity index 62% rename from sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_azure_queue_storage.py rename to sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py index 5a2ba62e4064..6a06b1a9614d 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_azure_queue_storage.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_client.py @@ -2,53 +2,53 @@ # -------------------------------------------------------------------------- # 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_extensions import Self +import sys +from typing import Any, Awaitable, TYPE_CHECKING 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 sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore -class AzureQueueStorage: # pylint: disable=client-accepts-api-version-keyword - """AzureQueueStorage. +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class QueuesClient: # pylint: disable=client-accepts-api-version-keyword + """QueuesClient. :ivar service: ServiceOperations operations :vartype service: azure.storage.queue.aio.operations.ServiceOperations :ivar queue: QueueOperations operations :vartype queue: azure.storage.queue.aio.operations.QueueOperations - :ivar messages: MessagesOperations operations - :vartype messages: azure.storage.queue.aio.operations.MessagesOperations - :ivar message_id: MessageIdOperations operations - :vartype message_id: azure.storage.queue.aio.operations.MessageIdOperations - :param url: The URL of the service account, queue or message that is the target of the desired - operation. Required. + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. :type url: str - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str - :param base_url: Service URL. Required. Default value is "". - :type base_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-04-06" 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 """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, url: str, version: str, base_url: str = "", **kwargs: Any - ) -> None: - self._config = AzureQueueStorageConfiguration(url=url, version=version, **kwargs) + def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{url}" + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -64,21 +64,18 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._config.custom_hook_policy, self._config.logging_policy, policies.DistributedTracingPolicy(**kwargs), - (policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) - self.messages = MessagesOperations(self._client, self._config, self._serialize, self._deserialize) - self.message_id = MessageIdOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -86,7 +83,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -99,7 +96,11 @@ def _send_request( """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_configuration.py index 1c90497920fe..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 @@ -2,39 +2,51 @@ # -------------------------------------------------------------------------- # 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 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 """ - 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 +60,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/_patch.py index 4688ca7f8ac2..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 @@ -1,33 +1,98 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. -# This file is used for handwritten extensions to the generated code. Example: -# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +from typing import Any, Optional, TYPE_CHECKING + +from azure.core import AsyncPipelineClient + +from .._version import VERSION +from ._configuration import QueuesClientConfiguration as QueuesClientConfigurationInternal +from .._utils.serialization import Deserializer, Serializer +from .operations import QueueOperations, ServiceOperations +from ._client import QueuesClient as _QueuesClient + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class QueuesClientConfiguration(QueuesClientConfigurationInternal): + """Configuration for QueuesClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param url: The host name of the queue storage account, e.g. + accountName.queue.core.windows.net. Required. + :type url: str + :param credential: Credential used to authenticate requests to the service. + :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: + 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. + + :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) + if _pipeline is not None: + self._config = QueuesClientConfiguration(url=url, credential=credential, **kwargs) + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url="{url}", pipeline=_pipeline) + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.queue = QueueOperations(self._client, self._config, self._serialize, self._deserialize) + else: + super().__init__(url, credential, **kwargs) + + +__all__: list[str] = ["QueuesClient"] def patch_sdk(): - pass + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py index e53a2d5483fd..3fb890991836 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,10 +12,8 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._service_operations import ServiceOperations # type: ignore -from ._queue_operations import QueueOperations # type: ignore -from ._messages_operations import MessagesOperations # type: ignore -from ._message_id_operations import MessageIdOperations # type: ignore +from ._operations import ServiceOperations # type: ignore +from ._operations import QueueOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -24,8 +22,6 @@ __all__ = [ "ServiceOperations", "QueueOperations", - "MessagesOperations", - "MessageIdOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py deleted file mode 100644 index bc26d91d2d9d..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_message_id_operations.py +++ /dev/null @@ -1,223 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._message_id_operations import ( - build_delete_request, - build_update_request, -) -from .._configuration import AzureQueueStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class MessageIdOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.aio.AzureQueueStorage`'s - :attr:`message_id` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def update( - self, - pop_receipt: str, - visibilitytimeout: int, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - queue_message: Optional[_models.QueueMessage] = None, - **kwargs: Any - ) -> None: - """The Update operation was introduced with version 2011-08-18 of the Queue service API. The - Update Message operation updates the visibility timeout of a message. You can also use this - operation to update the contents of a message. A message must be in a format that can be - included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in - size. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Required. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Delete operation deletes the specified message. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def dequeue( - self, - number_of_messages: Optional[int] = None, - visibilitytimeout: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> list[_models.DequeuedMessageItem]: - """The Dequeue operation retrieves one or more messages from the front of the queue. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Default value is None. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Clear operation deletes all messages from the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.EnqueuedMessage]: - """The Enqueue operation adds a new message to the back of the message queue. A visibility timeout - can also be specified to make the message invisible until the visibility timeout expires. A - message must be in a format that can be included in an XML request with UTF-8 encoding. The - encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size - for previous versions. - - :param queue_message: A Message object which can be stored in a Queue. Required. - :type queue_message: ~azure.storage.queue.models.QueueMessage - :param visibilitytimeout: Optional. If specified, the request must be made using an - x-ms-version of 2011-08-18 or later. If not specified, the default value is 0. Specifies the - new visibility timeout value, in seconds, relative to server time. The new value must be larger - than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message - cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value - smaller than the time-to-live value. Default value is None. - :type visibilitytimeout: int - :param message_time_to_live: Optional. Specifies the time-to-live interval for the message, in - seconds. Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For version - 2017-07-29 or later, the maximum time-to-live can be any positive number, as well as -1 - indicating that the message does not expire. If this parameter is omitted, the default - time-to-live is 7 days. Default value is None. - :type message_time_to_live: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.PeekedMessageItem]: - """The Peek operation retrieves one or more messages from the front of the queue, but does not - alter the visibility of the message. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def set_properties( + self, queue_service_properties: _models.QueueServiceProperties, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Sets properties for a storage account's Queue service endpoint, including properties for + Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :param queue_service_properties: The storage service properties to set. Required. + :type queue_service_properties: ~azure.storage.queue._generated.models.QueueServiceProperties + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(queue_service_properties) + + _request = build_service_set_properties_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceProperties: + """Retrieves properties of a storage account's Queue service, including properties for Storage + Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceProperties. The QueueServiceProperties is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceProperties] = kwargs.pop("cls", None) + + _request = build_service_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceProperties, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceStats: + """Retrieves statistics related to replication for the Queue service. It is only available on the + secondary location endpoint when read-access geo-redundant replication is enabled for the + storage account. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceStats. The QueueServiceStats is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceStats + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceStats] = kwargs.pop("cls", None) + + _request = build_service_get_statistics_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceStats, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_user_delegation_key( + self, key_info: _models.KeyInfo, *, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.UserDelegationKey: + """Retrieves a user delegation key for the Queue service. This is only a valid operation when + using bearer token authentication. + + :param key_info: Key information. Required. + :type key_info: ~azure.storage.queue._generated.models.KeyInfo + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.UserDelegationKey + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) + + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.UserDelegationKey, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_queues( + self, + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, + **kwargs: Any + ) -> _models.ListQueuesResponse: + """Returns a list of 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: 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. + :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: 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 + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListQueuesResponse] = kwargs.pop("cls", None) + + _request = build_service_get_queues_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, + timeout=timeout, + include=include, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListQueuesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class QueueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.queue.aio.QueuesClient`'s + :attr:`queue` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def create(self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any) -> None: + """Creates a new queue. 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 + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_create_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: + """Returns all user-defined metadata and system properties for the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("str", response.headers.get("x-ms-meta")) + response_headers["x-ms-approximate-messages-count"] = self._deserialize( + "int", response.headers.get("x-ms-approximate-messages-count") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def delete(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: + """Permanently deletes the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def set_metadata( + self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any + ) -> None: + """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 + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_set_metadata_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.SignedIdentifiers: + """Gets the 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 + :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.SignedIdentifiers + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + + _request = build_queue_get_access_policy_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.SignedIdentifiers, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def set_access_policy( + self, queue_acl: Optional[_models.SignedIdentifiers] = None, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Sets the permissions for the specified queue. + + :param queue_acl: The access control list. Default value is None. + :type queue_acl: ~azure.storage.queue._generated.models.SignedIdentifiers + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_acl else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_acl is not None: + _content = _get_element(queue_acl) + else: + _content = None + + _request = build_queue_set_access_policy_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def receive_messages( + self, + *, + number_of_messages: Optional[int] = None, + visibility_timeout: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any + ) -> _models.ReceivedMessages: + """Retrieves one or more messages from the front of the queue. + + :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. 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 + :return: ReceivedMessages. The ReceivedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ReceivedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ReceivedMessages] = kwargs.pop("cls", None) + + _request = build_queue_receive_messages_request( + number_of_messages=number_of_messages, + visibility_timeout=visibility_timeout, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ReceivedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def clear(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: + """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: + """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: 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. 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: Specifies the time-to-live interval for the message, in seconds. + Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For + version 2017-07-29 or later, the maximum time-to-live can be any positive + number, as well as -1 indicating that the message does not expire. If this + parameter is omitted, the default time-to-live is 7 days. Default value is None. + :paramtype message_time_to_live: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: ListOfSentMessage. The ListOfSentMessage is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ListOfSentMessage + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.ListOfSentMessage] = kwargs.pop("cls", None) + + _content = _get_element(queue_message) + + _request = build_queue_send_message_request( + visibility_timeout=visibility_timeout, + message_time_to_live=message_time_to_live, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListOfSentMessage, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def peek_messages( + self, *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.PeekedMessages: + """Retrieves one or more messages from the front of the queue, but does not alter the visibility + of the message. + + :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 + :return: PeekedMessages. The PeekedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.PeekedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PeekedMessages] = kwargs.pop("cls", None) + + _request = build_queue_peek_messages_request( + number_of_messages=number_of_messages, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.PeekedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def update_message( + self, + message_id: str, + queue_message: Optional[_models.QueueMessage] = None, + *, + pop_receipt: str, + visibility_timeout: int, + timeout: Optional[int] = None, + **kwargs: Any + ) -> None: + """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. + :type message_id: str + :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: 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. 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 + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_message else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_message is not None: + _content = _get_element(queue_message) + else: + _content = None + + _request = build_queue_update_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + visibility_timeout=visibility_timeout, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-popreceipt"] = self._deserialize("str", response.headers.get("x-ms-popreceipt")) + response_headers["x-ms-time-next-visible"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-time-next-visible") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def delete_message( + self, message_id: str, *, pop_receipt: str, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Deletes the specified message. + + :param message_id: The ID of the queue message. Required. + :type message_id: str + :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 + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py index 2e25743cab74..87676c65a8f0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_patch.py @@ -1,17 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_queue_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_queue_operations.py deleted file mode 100644 index 252b7d54f4c5..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/aio/operations/_queue_operations.py +++ /dev/null @@ -1,505 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._queue_operations import ( - build_create_request, - build_delete_request, - build_get_access_policy_request, - build_get_properties_request, - build_set_access_policy_request, - build_set_metadata_request, -) -from .._configuration import AzureQueueStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class QueueOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.aio.AzureQueueStorage`'s - :attr:`queue` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def create( - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """creates a new queue under the given account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """operation permanently deletes the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """Retrieves user-defined metadata and queue properties on the specified queue. Metadata is - associated with the queue as name-values pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets user-defined metadata on the specified queue. Metadata is associated with the queue as - name-value pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.SignedIdentifier]: - """returns details about any stored access policies specified on the queue that may be used with - Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets stored access policies for the queue that may be used with Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def set_properties( - self, - storage_service_properties: _models.StorageServiceProperties, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """Sets properties for a storage account's Queue service endpoint, including properties for - Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param storage_service_properties: The StorageService properties. Required. - :type storage_service_properties: ~azure.storage.queue.models.StorageServiceProperties - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceProperties: - """gets the properties of a storage account's Queue service, including properties for Storage - Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceStats: - """Retrieves statistics related to replication for the Queue service. It is only available on the - secondary location endpoint when read-access geo-redundant replication is enabled for the - storage account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.UserDelegationKey: - """Retrieves a user delegation key for the Queue service. This is only a valid operation when - using bearer token authentication. - - :param key_info: Key information. Required. - :type key_info: ~azure.storage.queue.models.KeyInfo - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.ListQueuesSegmentResponse: - """The List Queues Segment operation returns a list of the queues under the specified account. - - :param prefix: Filters the results to return only queues whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param marker: A string value that identifies the portion of the list of queues to be returned - with the next listing operation. The operation returns the NextMarker value within the response - body if the listing operation did not return all queues remaining to be listed with the current - page. The NextMarker value can be used as the value for the marker parameter in a subsequent - call to request the next page of list items. The marker value is opaque to the client. Default - value is None. - :type marker: str - :param maxresults: Specifies the maximum number of queues to return. If the request does not - specify maxresults, or specifies a value greater than 5000, the server will return up to 5000 - items. Note that if the listing operation crosses a partition boundary, then the service will - return a continuation token for retrieving the remainder of the results. For this reason, it is - possible that the service will return fewer results than specified by maxresults, or than the - default of 5000. Default value is None. - :type maxresults: int - :param include: Include this parameter to specify that the queues' metadata be returned as part - of the response body. Default value is None. - :type include: list[str] - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CorsRule(_Model): + """The CORS rules. + + :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}, + 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.""" + + _xml = {"attribute": False, "name": "CorsRule", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + allowed_origins: str, + allowed_methods: str, + allowed_headers: str, + exposed_headers: str, + max_age_in_seconds: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Error(_Model): + """The error response. + + :ivar code: The error code. Known values are: "AccountAlreadyExists", "AccountBeingCreated", + "AccountIsDisabled", "AuthenticationFailed", "AuthorizationFailure", + "ConditionHeadersNotSupported", "ConditionNotMet", "EmptyMetadataKey", + "InsufficientAccountPermissions", "InternalError", "InvalidAuthenticationInfo", + "InvalidHeaderValue", "InvalidHttpVerb", "InvalidInput", "InvalidMd5", "InvalidMetadata", + "InvalidQueryParameterValue", "InvalidRange", "InvalidResourceName", "InvalidUri", + "InvalidXmlDocument", "InvalidXmlNodeValue", "Md5Mismatch", "MetadataTooLarge", + "MissingContentLengthHeader", "MissingRequiredQueryParameter", "MissingRequiredHeader", + "MissingRequiredXmlNode", "MultipleConditionHeadersNotSupported", "OperationTimedOut", + "OutOfRangeInput", "OutOfRangeQueryParameterValue", "RequestBodyTooLarge", + "ResourceTypeMismatch", "RequestUrlFailedToParse", "ResourceAlreadyExists", "ResourceNotFound", + "ServerBusy", "UnsupportedHeader", "UnsupportedXmlNode", "UnsupportedQueryParameter", + "UnsupportedHttpVerb", "InvalidMarker", "MessageNotFound", "MessageTooLarge", + "PopReceiptMismatch", "QueueAlreadyExists", "QueueBeingDeleted", "QueueDisabled", + "QueueNotEmpty", "QueueNotFound", "AuthorizationSourceIPMismatch", + "AuthorizationProtocolMismatch", "AuthorizationPermissionMismatch", + "AuthorizationServiceMismatch", "AuthorizationResourceTypeMismatch", and + "FeatureVersionMismatch". + :vartype code: str or ~azure.storage.queue.models.StorageErrorCode + :ivar message: The error message. + :vartype message: str + """ + + code: Optional[Union[str, "_models.StorageErrorCode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Code", "text": False, "unwrapped": False}, + deserializer=functools.partial(_xml_deser_enum_or_str, StorageErrorCode), + ) + """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}, + deserializer=_xml_deser_str, + ) + """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 location. + + :ivar status: The status of the secondary location. Required. Known values are: "live", + "bootstrap", and "unavailable". + :vartype status: str or ~azure.storage.queue.models.GeoReplicationStatus + :ivar last_sync_time: A GMT date/time value, to the second. All primary writes preceding this + value are guaranteed to be available for read operations at the secondary. Primary writes after + this point in time may or may not be available for reads. Required. + :vartype last_sync_time: ~datetime.datetime + """ + + status: Union[str, "_models.GeoReplicationStatus"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Status", "text": False, "unwrapped": False}, + deserializer=functools.partial(_xml_deser_enum_or_str, GeoReplicationStatus), + ) + """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}, + 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 + or may not be available for reads. Required.""" + + _xml = {"attribute": False, "name": "GeoReplication", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + status: Union[str, "_models.GeoReplicationStatus"], + last_sync_time: datetime.datetime, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KeyInfo(_Model): + """Key information for user delegation key. + + :ivar start: The date-time the key is active in ISO 8601 UTC time. + :vartype start: str + :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. + :vartype expiry: str + :ivar delegated_user_tid: The delegated user tenant ID in Entra ID. + :vartype delegated_user_tid: str + """ + + start: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + 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.""" + + _xml = {"attribute": False, "name": "KeyInfo", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + expiry: str, + start: Optional[str] = None, + delegated_user_tid: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListOfSentMessage(_Model): + """The response of send message. + + :ivar items_property: The list of sent messages. Required. + :vartype items_property: ~azure.storage.queue._generated.models.SentMessage + """ + + items_property: list["_models.SentMessage"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "QueueMessage", "name": "QueueMessage", "text": False, "unwrapped": True}, + original_tsp_name="items", + ) + """The list of sent 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 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: Identifies the current position in the list queues operation. + :vartype marker: str + :ivar max_results: The max results. Required. + :vartype max_results: int + :ivar queue_items: The list of queues. + :vartype queue_items: ~azure.storage.queue._generated.models.QueueItem + :ivar next_marker: Identifies the portion of the list of queues to be returned with the next + listing operation. 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}, + 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( + name="queueItems", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "Queue", "name": "Queues", "text": False, "unwrapped": False}, + ) + """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}, + deserializer=_xml_deser_str, + ) + """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} + + @overload + def __init__( + self, + *, + service_endpoint: str, + prefix: str, + max_results: int, + next_marker: str, + marker: Optional[str] = None, + queue_items: Optional[list["_models.QueueItem"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Logging(_Model): + """Azure Analytics Logging settings. + + :ivar version: The version of the logging properties. Required. + :vartype version: str + :ivar delete: Whether delete operation is logged. Required. + :vartype delete: bool + :ivar read: Whether read operation is logged. Required. + :vartype read: bool + :ivar write: Whether write operation is logged. Required. + :vartype write: bool + :ivar retention_policy: The retention policy of the logs. Required. + :vartype retention_policy: ~azure.storage.queue._generated.models.RetentionPolicy + """ + + version: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + 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( + name="retentionPolicy", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "RetentionPolicy", "text": False, "unwrapped": False}, + ) + """The retention policy of the logs. Required.""" + + _xml = {"attribute": False, "name": "Logging", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + version: str, + delete: bool, + read: bool, + write: bool, + retention_policy: "_models.RetentionPolicy", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Metrics(_Model): + """The metrics properties. + + :ivar version: The version of the metrics properties. + :vartype version: str + :ivar enabled: Whether it is enabled. Required. + :vartype enabled: bool + :ivar include_apis: Whether to include API in the metrics. + :vartype include_apis: bool + :ivar retention_policy: The retention policy of the metrics. + :vartype retention_policy: ~azure.storage.queue._generated.models.RetentionPolicy + """ + + version: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + 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( + 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 peeked queue message. + + :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}, + deserializer=_xml_deser_str, + ) + """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}, + deserializer=_xml_deser_datetime_rfc7231, + ) + """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}, + 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.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_id: str, + insertion_time: datetime.datetime, + expiration_time: datetime.datetime, + dequeue_count: int, + message_text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PeekedMessages(_Model): + """The response of peek messages. + + :ivar items_property: The list of peeked messages. Required. + :vartype items_property: ~azure.storage.queue._generated.models.PeekedMessage + """ + + items_property: list["_models.PeekedMessage"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "QueueMessage", "name": "QueueMessage", "text": False, "unwrapped": True}, + original_tsp_name="items", + ) + """The list of peeked messages. Required.""" + + _xml = {"attribute": False, "name": "QueueMessagesList", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.PeekedMessage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueueItem(_Model): + """An Azure Storage Queue. + + :ivar name: The name of the queue. Required. + :vartype name: str + :ivar metadata: The metadata of the queue. + :vartype metadata: dict[str, str] + """ + + 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( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Metadata", "text": False, "unwrapped": False}, + ) + """The metadata of the queue.""" + + _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): + """The queue message. + + :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}, + deserializer=_xml_deser_str, + ) + """The content of the message. Required.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueueServiceProperties(_Model): + """The service properties. + + :ivar logging: The logging properties. + :vartype logging: ~azure.storage.queue._generated.models.Logging + :ivar hour_metrics: The hour metrics properties. + :vartype hour_metrics: ~azure.storage.queue._generated.models.Metrics + :ivar minute_metrics: The minute metrics properties. + :vartype minute_metrics: ~azure.storage.queue._generated.models.Metrics + :ivar cors: The CORS properties. + :vartype cors: ~azure.storage.queue._generated.models.CorsRule + """ + + logging: Optional["_models.Logging"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Logging", "text": False, "unwrapped": False}, + ) + """The logging properties.""" + hour_metrics: Optional["_models.Metrics"] = rest_field( + name="hourMetrics", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "HourMetrics", "text": False, "unwrapped": False}, + ) + """The hour metrics properties.""" + minute_metrics: Optional["_models.Metrics"] = rest_field( + name="minuteMetrics", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MinuteMetrics", "text": False, "unwrapped": False}, + ) + """The minute metrics properties.""" + cors: Optional[list["_models.CorsRule"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "CorsRule", "name": "Cors", "text": False, "unwrapped": False}, + ) + """The CORS properties.""" + + _xml = {"attribute": False, "name": "StorageServiceProperties", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + logging: Optional["_models.Logging"] = None, + hour_metrics: Optional["_models.Metrics"] = None, + minute_metrics: Optional["_models.Metrics"] = None, + cors: Optional[list["_models.CorsRule"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class QueueServiceStats(_Model): + """Statistics for the storage queue service. + + :ivar geo_replication: The geo replication stats. + :vartype geo_replication: ~azure.storage.queue._generated.models.GeoReplication + """ + + geo_replication: Optional["_models.GeoReplication"] = rest_field( + name="geoReplication", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "GeoReplication", "text": False, "unwrapped": False}, + ) + """The geo replication stats.""" + + _xml = {"attribute": False, "name": "QueueServiceStats", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + geo_replication: Optional["_models.GeoReplication"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ReceivedMessage(_Model): + """The received queue message. + + :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: 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. + 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}, + deserializer=_xml_deser_str, + ) + """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}, + deserializer=_xml_deser_datetime_rfc7231, + ) + """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}, + 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.""" + 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}, + 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.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_id: str, + insertion_time: datetime.datetime, + expiration_time: datetime.datetime, + pop_receipt: str, + time_next_visible: datetime.datetime, + dequeue_count: int, + message_text: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ReceivedMessages(_Model): + """The response of receive messages. + + :ivar items_property: The list of received 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 received messages. Required.""" + + _xml = {"attribute": False, "name": "QueueMessagesList", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.ReceivedMessage"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RetentionPolicy(_Model): + """The retention policy. + + :ivar enabled: Whether to enable the retention policy. Required. + :vartype enabled: bool + :ivar days: The number of days to retain the logs. + :vartype days: int + """ + + enabled: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + 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.""" + + _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 sent queue message. + + :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: 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. + 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}, + deserializer=_xml_deser_str, + ) + """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}, + deserializer=_xml_deser_datetime_rfc7231, + ) + """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}, + 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.""" + 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}, + deserializer=_xml_deser_datetime_rfc7231, + ) + """The time that the message will again become visible in the queue. Required.""" + + _xml = {"attribute": False, "name": "QueueMessage", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + message_id: str, + insertion_time: datetime.datetime, + expiration_time: datetime.datetime, + pop_receipt: str, + time_next_visible: datetime.datetime, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SignedIdentifier(_Model): + """The signed identifier. + + :ivar id: The unique ID for the signed identifier. Required. + :vartype id: str + :ivar access_policy: The access policy for the signed identifier. Required. + :vartype access_policy: ~azure.storage.queue._generated.models.AccessPolicy + """ + + id: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Id", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, + ) + """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): + """An array of signed identifiers. + + :ivar items_property: The list of signed identifiers. Required. + :vartype items_property: ~azure.storage.queue._generated.models.SignedIdentifier + """ + + items_property: list["_models.SignedIdentifier"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={ + "attribute": False, + "itemsName": "SignedIdentifier", + "name": "SignedIdentifier", + "text": False, + "unwrapped": True, + }, + original_tsp_name="items", + ) + """The list of signed identifiers. Required.""" + + _xml = {"attribute": False, "name": "SignedIdentifiers", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.SignedIdentifier"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UserDelegationKey(_Model): + """A user delegation key. + + :ivar signed_oid: The Entra ID object ID in GUID format. Required. + :vartype signed_oid: str + :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 + :ivar signed_expiry: The date-time the key expires. Required. + :vartype signed_expiry: str + :ivar signed_service: The service that created the key. Required. + :vartype signed_service: str + :ivar signed_version: The service version used when creating the key. Required. + :vartype signed_version: str + :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. + :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}, + 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.""" + + _xml = {"attribute": False, "name": "UserDelegationKey", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + signed_oid: str, + signed_tid: str, + signed_start: str, + signed_expiry: str, + signed_service: str, + signed_version: str, + value: str, + signed_delegated_user_tid: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py deleted file mode 100644 index e28743c64d07..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_models_py3.py +++ /dev/null @@ -1,951 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models - - -class AccessPolicy(_serialization.Model): - """An Access policy. - - :ivar start: the date-time the policy is active. - :vartype start: str - :ivar expiry: the date-time the policy expires. - :vartype expiry: str - :ivar permission: the permissions for the acl policy. - :vartype permission: str - """ - - _attribute_map = { - "start": {"key": "Start", "type": "str"}, - "expiry": {"key": "Expiry", "type": "str"}, - "permission": {"key": "Permission", "type": "str"}, - } - - def __init__( - self, - *, - start: Optional[str] = None, - expiry: Optional[str] = None, - permission: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword start: the date-time the policy is active. - :paramtype start: str - :keyword expiry: the date-time the policy expires. - :paramtype expiry: str - :keyword permission: the permissions for the acl policy. - :paramtype permission: str - """ - super().__init__(**kwargs) - self.start = start - self.expiry = expiry - self.permission = permission - - -class CorsRule(_serialization.Model): - """CORS is an HTTP feature that enables a web application running under one domain to access - resources in another domain. Web browsers implement a security restriction known as same-origin - policy that prevents a web page from calling APIs in a different domain; CORS provides a secure - way to allow one domain (the origin domain) to call APIs in another domain. - - All required parameters must be populated in order to send to server. - - :ivar allowed_origins: The origin domains that are permitted to make a request against the - storage service via CORS. The origin domain is the domain from which the request originates. - Note that the origin must be an exact case-sensitive match with the origin that the user age - sends to the service. You can also use the wildcard character '*' to allow all origin domains - to make requests via CORS. Required. - :vartype allowed_origins: str - :ivar allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. (comma separated). Required. - :vartype allowed_methods: str - :ivar allowed_headers: the request headers that the origin domain may specify on the CORS - request. Required. - :vartype allowed_headers: str - :ivar exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. Required. - :vartype exposed_headers: str - :ivar max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. Required. - :vartype max_age_in_seconds: int - """ - - _validation = { - "allowed_origins": {"required": True}, - "allowed_methods": {"required": True}, - "allowed_headers": {"required": True}, - "exposed_headers": {"required": True}, - "max_age_in_seconds": {"required": True, "minimum": 0}, - } - - _attribute_map = { - "allowed_origins": {"key": "AllowedOrigins", "type": "str"}, - "allowed_methods": {"key": "AllowedMethods", "type": "str"}, - "allowed_headers": {"key": "AllowedHeaders", "type": "str"}, - "exposed_headers": {"key": "ExposedHeaders", "type": "str"}, - "max_age_in_seconds": {"key": "MaxAgeInSeconds", "type": "int"}, - } - - def __init__( - self, - *, - allowed_origins: str, - allowed_methods: str, - allowed_headers: str, - exposed_headers: str, - max_age_in_seconds: int, - **kwargs: Any - ) -> None: - """ - :keyword allowed_origins: The origin domains that are permitted to make a request against the - storage service via CORS. The origin domain is the domain from which the request originates. - Note that the origin must be an exact case-sensitive match with the origin that the user age - sends to the service. You can also use the wildcard character '*' to allow all origin domains - to make requests via CORS. Required. - :paramtype allowed_origins: str - :keyword allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. (comma separated). Required. - :paramtype allowed_methods: str - :keyword allowed_headers: the request headers that the origin domain may specify on the CORS - request. Required. - :paramtype allowed_headers: str - :keyword exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. Required. - :paramtype exposed_headers: str - :keyword max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. Required. - :paramtype max_age_in_seconds: int - """ - super().__init__(**kwargs) - self.allowed_origins = allowed_origins - self.allowed_methods = allowed_methods - self.allowed_headers = allowed_headers - self.exposed_headers = exposed_headers - self.max_age_in_seconds = max_age_in_seconds - - -class DequeuedMessageItem(_serialization.Model): - """The object returned in the QueueMessageList array when calling Get Messages on a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_id: The Id of the Message. Required. - :vartype message_id: str - :ivar insertion_time: The time the Message was inserted into the Queue. Required. - :vartype insertion_time: ~datetime.datetime - :ivar expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :vartype expiration_time: ~datetime.datetime - :ivar pop_receipt: This value is required to delete the Message. If deletion fails using this - popreceipt then the message has been dequeued by another client. Required. - :vartype pop_receipt: str - :ivar time_next_visible: The time that the message will again become visible in the Queue. - Required. - :vartype time_next_visible: ~datetime.datetime - :ivar dequeue_count: The number of times the message has been dequeued. Required. - :vartype dequeue_count: int - :ivar message_text: The content of the Message. Required. - :vartype message_text: str - """ - - _validation = { - "message_id": {"required": True}, - "insertion_time": {"required": True}, - "expiration_time": {"required": True}, - "pop_receipt": {"required": True}, - "time_next_visible": {"required": True}, - "dequeue_count": {"required": True}, - "message_text": {"required": True}, - } - - _attribute_map = { - "message_id": {"key": "MessageId", "type": "str"}, - "insertion_time": {"key": "InsertionTime", "type": "rfc-1123"}, - "expiration_time": {"key": "ExpirationTime", "type": "rfc-1123"}, - "pop_receipt": {"key": "PopReceipt", "type": "str"}, - "time_next_visible": {"key": "TimeNextVisible", "type": "rfc-1123"}, - "dequeue_count": {"key": "DequeueCount", "type": "int"}, - "message_text": {"key": "MessageText", "type": "str"}, - } - _xml_map = {"name": "QueueMessage"} - - def __init__( - self, - *, - message_id: str, - insertion_time: datetime.datetime, - expiration_time: datetime.datetime, - pop_receipt: str, - time_next_visible: datetime.datetime, - dequeue_count: int, - message_text: str, - **kwargs: Any - ) -> None: - """ - :keyword message_id: The Id of the Message. Required. - :paramtype message_id: str - :keyword insertion_time: The time the Message was inserted into the Queue. Required. - :paramtype insertion_time: ~datetime.datetime - :keyword expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :paramtype expiration_time: ~datetime.datetime - :keyword pop_receipt: This value is required to delete the Message. If deletion fails using - this popreceipt then the message has been dequeued by another client. Required. - :paramtype pop_receipt: str - :keyword time_next_visible: The time that the message will again become visible in the Queue. - Required. - :paramtype time_next_visible: ~datetime.datetime - :keyword dequeue_count: The number of times the message has been dequeued. Required. - :paramtype dequeue_count: int - :keyword message_text: The content of the Message. Required. - :paramtype message_text: str - """ - super().__init__(**kwargs) - self.message_id = message_id - self.insertion_time = insertion_time - self.expiration_time = expiration_time - self.pop_receipt = pop_receipt - self.time_next_visible = time_next_visible - self.dequeue_count = dequeue_count - self.message_text = message_text - - -class EnqueuedMessage(_serialization.Model): - """The object returned in the QueueMessageList array when calling Put Message on a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_id: The Id of the Message. Required. - :vartype message_id: str - :ivar insertion_time: The time the Message was inserted into the Queue. Required. - :vartype insertion_time: ~datetime.datetime - :ivar expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :vartype expiration_time: ~datetime.datetime - :ivar pop_receipt: This value is required to delete the Message. If deletion fails using this - popreceipt then the message has been dequeued by another client. Required. - :vartype pop_receipt: str - :ivar time_next_visible: The time that the message will again become visible in the Queue. - Required. - :vartype time_next_visible: ~datetime.datetime - """ - - _validation = { - "message_id": {"required": True}, - "insertion_time": {"required": True}, - "expiration_time": {"required": True}, - "pop_receipt": {"required": True}, - "time_next_visible": {"required": True}, - } - - _attribute_map = { - "message_id": {"key": "MessageId", "type": "str"}, - "insertion_time": {"key": "InsertionTime", "type": "rfc-1123"}, - "expiration_time": {"key": "ExpirationTime", "type": "rfc-1123"}, - "pop_receipt": {"key": "PopReceipt", "type": "str"}, - "time_next_visible": {"key": "TimeNextVisible", "type": "rfc-1123"}, - } - _xml_map = {"name": "QueueMessage"} - - def __init__( - self, - *, - message_id: str, - insertion_time: datetime.datetime, - expiration_time: datetime.datetime, - pop_receipt: str, - time_next_visible: datetime.datetime, - **kwargs: Any - ) -> None: - """ - :keyword message_id: The Id of the Message. Required. - :paramtype message_id: str - :keyword insertion_time: The time the Message was inserted into the Queue. Required. - :paramtype insertion_time: ~datetime.datetime - :keyword expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :paramtype expiration_time: ~datetime.datetime - :keyword pop_receipt: This value is required to delete the Message. If deletion fails using - this popreceipt then the message has been dequeued by another client. Required. - :paramtype pop_receipt: str - :keyword time_next_visible: The time that the message will again become visible in the Queue. - Required. - :paramtype time_next_visible: ~datetime.datetime - """ - super().__init__(**kwargs) - self.message_id = message_id - self.insertion_time = insertion_time - self.expiration_time = expiration_time - self.pop_receipt = pop_receipt - self.time_next_visible = time_next_visible - - -class GeoReplication(_serialization.Model): - """GeoReplication. - - All required parameters must be populated in order to send to server. - - :ivar status: The status of the secondary location. Required. Known values are: "live", - "bootstrap", and "unavailable". - :vartype status: str or ~azure.storage.queue.models.GeoReplicationStatusType - :ivar last_sync_time: A GMT date/time value, to the second. All primary writes preceding this - value are guaranteed to be available for read operations at the secondary. Primary writes after - this point in time may or may not be available for reads. Required. - :vartype last_sync_time: ~datetime.datetime - """ - - _validation = { - "status": {"required": True}, - "last_sync_time": {"required": True}, - } - - _attribute_map = { - "status": {"key": "Status", "type": "str"}, - "last_sync_time": {"key": "LastSyncTime", "type": "rfc-1123"}, - } - - def __init__( - self, - *, - status: Union[str, "_models.GeoReplicationStatusType"], - last_sync_time: datetime.datetime, - **kwargs: Any - ) -> None: - """ - :keyword status: The status of the secondary location. Required. Known values are: "live", - "bootstrap", and "unavailable". - :paramtype status: str or ~azure.storage.queue.models.GeoReplicationStatusType - :keyword last_sync_time: A GMT date/time value, to the second. All primary writes preceding - this value are guaranteed to be available for read operations at the secondary. Primary writes - after this point in time may or may not be available for reads. Required. - :paramtype last_sync_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.status = status - self.last_sync_time = last_sync_time - - -class KeyInfo(_serialization.Model): - """Key information. - - All required parameters must be populated in order to send to server. - - :ivar start: The date-time the key is active in ISO 8601 UTC time. - :vartype start: str - :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :vartype expiry: str - :ivar delegated_user_tid: The delegated user tenant id in Azure AD. - :vartype delegated_user_tid: str - """ - - _validation = { - "expiry": {"required": True}, - } - - _attribute_map = { - "start": {"key": "Start", "type": "str"}, - "expiry": {"key": "Expiry", "type": "str"}, - "delegated_user_tid": {"key": "DelegatedUserTid", "type": "str"}, - } - - def __init__( - self, *, expiry: str, start: Optional[str] = None, delegated_user_tid: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword start: The date-time the key is active in ISO 8601 UTC time. - :paramtype start: str - :keyword expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :paramtype expiry: str - :keyword delegated_user_tid: The delegated user tenant id in Azure AD. - :paramtype delegated_user_tid: str - """ - super().__init__(**kwargs) - self.start = start - self.expiry = expiry - self.delegated_user_tid = delegated_user_tid - - -class ListQueuesSegmentResponse(_serialization.Model): - """The object returned when calling List Queues on a Queue Service. - - All required parameters must be populated in order to send to server. - - :ivar service_endpoint: Required. - :vartype service_endpoint: str - :ivar prefix: Required. - :vartype prefix: str - :ivar marker: - :vartype marker: str - :ivar max_results: Required. - :vartype max_results: int - :ivar queue_items: - :vartype queue_items: list[~azure.storage.queue.models.QueueItem] - :ivar next_marker: Required. - :vartype next_marker: str - """ - - _validation = { - "service_endpoint": {"required": True}, - "prefix": {"required": True}, - "max_results": {"required": True}, - "next_marker": {"required": True}, - } - - _attribute_map = { - "service_endpoint": { - "key": "ServiceEndpoint", - "type": "str", - "xml": {"attr": True}, - }, - "prefix": {"key": "Prefix", "type": "str"}, - "marker": {"key": "Marker", "type": "str"}, - "max_results": {"key": "MaxResults", "type": "int"}, - "queue_items": { - "key": "QueueItems", - "type": "[QueueItem]", - "xml": {"name": "Queues", "wrapped": True, "itemsName": "Queue"}, - }, - "next_marker": {"key": "NextMarker", "type": "str"}, - } - _xml_map = {"name": "EnumerationResults"} - - def __init__( - self, - *, - service_endpoint: str, - prefix: str, - max_results: int, - next_marker: str, - marker: Optional[str] = None, - queue_items: Optional[list["_models.QueueItem"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword service_endpoint: Required. - :paramtype service_endpoint: str - :keyword prefix: Required. - :paramtype prefix: str - :keyword marker: - :paramtype marker: str - :keyword max_results: Required. - :paramtype max_results: int - :keyword queue_items: - :paramtype queue_items: list[~azure.storage.queue.models.QueueItem] - :keyword next_marker: Required. - :paramtype next_marker: str - """ - super().__init__(**kwargs) - self.service_endpoint = service_endpoint - self.prefix = prefix - self.marker = marker - self.max_results = max_results - self.queue_items = queue_items - self.next_marker = next_marker - - -class Logging(_serialization.Model): - """Azure Analytics Logging settings. - - All required parameters must be populated in order to send to server. - - :ivar version: The version of Storage Analytics to configure. Required. - :vartype version: str - :ivar delete: Indicates whether all delete requests should be logged. Required. - :vartype delete: bool - :ivar read: Indicates whether all read requests should be logged. Required. - :vartype read: bool - :ivar write: Indicates whether all write requests should be logged. Required. - :vartype write: bool - :ivar retention_policy: the retention policy. Required. - :vartype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - - _validation = { - "version": {"required": True}, - "delete": {"required": True}, - "read": {"required": True}, - "write": {"required": True}, - "retention_policy": {"required": True}, - } - - _attribute_map = { - "version": {"key": "Version", "type": "str"}, - "delete": {"key": "Delete", "type": "bool"}, - "read": {"key": "Read", "type": "bool"}, - "write": {"key": "Write", "type": "bool"}, - "retention_policy": {"key": "RetentionPolicy", "type": "RetentionPolicy"}, - } - - def __init__( - self, - *, - version: str, - delete: bool, - read: bool, - write: bool, - retention_policy: "_models.RetentionPolicy", - **kwargs: Any - ) -> None: - """ - :keyword version: The version of Storage Analytics to configure. Required. - :paramtype version: str - :keyword delete: Indicates whether all delete requests should be logged. Required. - :paramtype delete: bool - :keyword read: Indicates whether all read requests should be logged. Required. - :paramtype read: bool - :keyword write: Indicates whether all write requests should be logged. Required. - :paramtype write: bool - :keyword retention_policy: the retention policy. Required. - :paramtype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - super().__init__(**kwargs) - self.version = version - self.delete = delete - self.read = read - self.write = write - self.retention_policy = retention_policy - - -class Metrics(_serialization.Model): - """a summary of request statistics grouped by API in hour or minute aggregates for queues. - - All required parameters must be populated in order to send to server. - - :ivar version: The version of Storage Analytics to configure. - :vartype version: str - :ivar enabled: Indicates whether metrics are enabled for the Queue service. Required. - :vartype enabled: bool - :ivar include_apis: Indicates whether metrics should generate summary statistics for called API - operations. - :vartype include_apis: bool - :ivar retention_policy: the retention policy. - :vartype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - - _validation = { - "enabled": {"required": True}, - } - - _attribute_map = { - "version": {"key": "Version", "type": "str"}, - "enabled": {"key": "Enabled", "type": "bool"}, - "include_apis": {"key": "IncludeAPIs", "type": "bool"}, - "retention_policy": {"key": "RetentionPolicy", "type": "RetentionPolicy"}, - } - - def __init__( - self, - *, - enabled: bool, - version: Optional[str] = None, - include_apis: Optional[bool] = None, - retention_policy: Optional["_models.RetentionPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword version: The version of Storage Analytics to configure. - :paramtype version: str - :keyword enabled: Indicates whether metrics are enabled for the Queue service. Required. - :paramtype enabled: bool - :keyword include_apis: Indicates whether metrics should generate summary statistics for called - API operations. - :paramtype include_apis: bool - :keyword retention_policy: the retention policy. - :paramtype retention_policy: ~azure.storage.queue.models.RetentionPolicy - """ - super().__init__(**kwargs) - self.version = version - self.enabled = enabled - self.include_apis = include_apis - self.retention_policy = retention_policy - - -class PeekedMessageItem(_serialization.Model): - """The object returned in the QueueMessageList array when calling Peek Messages on a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_id: The Id of the Message. Required. - :vartype message_id: str - :ivar insertion_time: The time the Message was inserted into the Queue. Required. - :vartype insertion_time: ~datetime.datetime - :ivar expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :vartype expiration_time: ~datetime.datetime - :ivar dequeue_count: The number of times the message has been dequeued. Required. - :vartype dequeue_count: int - :ivar message_text: The content of the Message. Required. - :vartype message_text: str - """ - - _validation = { - "message_id": {"required": True}, - "insertion_time": {"required": True}, - "expiration_time": {"required": True}, - "dequeue_count": {"required": True}, - "message_text": {"required": True}, - } - - _attribute_map = { - "message_id": {"key": "MessageId", "type": "str"}, - "insertion_time": {"key": "InsertionTime", "type": "rfc-1123"}, - "expiration_time": {"key": "ExpirationTime", "type": "rfc-1123"}, - "dequeue_count": {"key": "DequeueCount", "type": "int"}, - "message_text": {"key": "MessageText", "type": "str"}, - } - _xml_map = {"name": "QueueMessage"} - - def __init__( - self, - *, - message_id: str, - insertion_time: datetime.datetime, - expiration_time: datetime.datetime, - dequeue_count: int, - message_text: str, - **kwargs: Any - ) -> None: - """ - :keyword message_id: The Id of the Message. Required. - :paramtype message_id: str - :keyword insertion_time: The time the Message was inserted into the Queue. Required. - :paramtype insertion_time: ~datetime.datetime - :keyword expiration_time: The time that the Message will expire and be automatically deleted. - Required. - :paramtype expiration_time: ~datetime.datetime - :keyword dequeue_count: The number of times the message has been dequeued. Required. - :paramtype dequeue_count: int - :keyword message_text: The content of the Message. Required. - :paramtype message_text: str - """ - super().__init__(**kwargs) - self.message_id = message_id - self.insertion_time = insertion_time - self.expiration_time = expiration_time - self.dequeue_count = dequeue_count - self.message_text = message_text - - -class QueueItem(_serialization.Model): - """An Azure Storage Queue. - - All required parameters must be populated in order to send to server. - - :ivar name: The name of the Queue. Required. - :vartype name: str - :ivar metadata: Dictionary of :code:``. - :vartype metadata: dict[str, str] - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "Name", "type": "str"}, - "metadata": {"key": "Metadata", "type": "{str}"}, - } - _xml_map = {"name": "Queue"} - - def __init__(self, *, name: str, metadata: Optional[dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword name: The name of the Queue. Required. - :paramtype name: str - :keyword metadata: Dictionary of :code:``. - :paramtype metadata: dict[str, str] - """ - super().__init__(**kwargs) - self.name = name - self.metadata = metadata - - -class QueueMessage(_serialization.Model): - """A Message object which can be stored in a Queue. - - All required parameters must be populated in order to send to server. - - :ivar message_text: The content of the message. Required. - :vartype message_text: str - """ - - _validation = { - "message_text": {"required": True}, - } - - _attribute_map = { - "message_text": {"key": "MessageText", "type": "str"}, - } - - def __init__(self, *, message_text: str, **kwargs: Any) -> None: - """ - :keyword message_text: The content of the message. Required. - :paramtype message_text: str - """ - super().__init__(**kwargs) - self.message_text = message_text - - -class RetentionPolicy(_serialization.Model): - """the retention policy. - - All required parameters must be populated in order to send to server. - - :ivar enabled: Indicates whether a retention policy is enabled for the storage service. - Required. - :vartype enabled: bool - :ivar days: Indicates the number of days that metrics or logging or soft-deleted data should be - retained. All data older than this value will be deleted. - :vartype days: int - """ - - _validation = { - "enabled": {"required": True}, - "days": {"minimum": 1}, - } - - _attribute_map = { - "enabled": {"key": "Enabled", "type": "bool"}, - "days": {"key": "Days", "type": "int"}, - } - - def __init__(self, *, enabled: bool, days: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword enabled: Indicates whether a retention policy is enabled for the storage service. - Required. - :paramtype enabled: bool - :keyword days: Indicates the number of days that metrics or logging or soft-deleted data should - be retained. All data older than this value will be deleted. - :paramtype days: int - """ - super().__init__(**kwargs) - self.enabled = enabled - self.days = days - - -class SignedIdentifier(_serialization.Model): - """signed identifier. - - All required parameters must be populated in order to send to server. - - :ivar id: a unique id. Required. - :vartype id: str - :ivar access_policy: The access policy. - :vartype access_policy: ~azure.storage.queue.models.AccessPolicy - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "Id", "type": "str"}, - "access_policy": {"key": "AccessPolicy", "type": "AccessPolicy"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - access_policy: Optional["_models.AccessPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: a unique id. Required. - :paramtype id: str - :keyword access_policy: The access policy. - :paramtype access_policy: ~azure.storage.queue.models.AccessPolicy - """ - super().__init__(**kwargs) - self.id = id - self.access_policy = access_policy - - -class StorageError(_serialization.Model): - """StorageError. - - :ivar message: - :vartype message: str - """ - - _attribute_map = { - "message": {"key": "Message", "type": "str"}, - } - - def __init__(self, *, message: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword message: - :paramtype message: str - """ - super().__init__(**kwargs) - self.message = message - - -class StorageServiceProperties(_serialization.Model): - """Storage Service Properties. - - :ivar logging: Azure Analytics Logging settings. - :vartype logging: ~azure.storage.queue.models.Logging - :ivar hour_metrics: A summary of request statistics grouped by API in hourly aggregates for - queues. - :vartype hour_metrics: ~azure.storage.queue.models.Metrics - :ivar minute_metrics: a summary of request statistics grouped by API in minute aggregates for - queues. - :vartype minute_metrics: ~azure.storage.queue.models.Metrics - :ivar cors: The set of CORS rules. - :vartype cors: list[~azure.storage.queue.models.CorsRule] - """ - - _attribute_map = { - "logging": {"key": "Logging", "type": "Logging"}, - "hour_metrics": {"key": "HourMetrics", "type": "Metrics"}, - "minute_metrics": {"key": "MinuteMetrics", "type": "Metrics"}, - "cors": {"key": "Cors", "type": "[CorsRule]", "xml": {"wrapped": True}}, - } - - def __init__( - self, - *, - logging: Optional["_models.Logging"] = None, - hour_metrics: Optional["_models.Metrics"] = None, - minute_metrics: Optional["_models.Metrics"] = None, - cors: Optional[list["_models.CorsRule"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword logging: Azure Analytics Logging settings. - :paramtype logging: ~azure.storage.queue.models.Logging - :keyword hour_metrics: A summary of request statistics grouped by API in hourly aggregates for - queues. - :paramtype hour_metrics: ~azure.storage.queue.models.Metrics - :keyword minute_metrics: a summary of request statistics grouped by API in minute aggregates - for queues. - :paramtype minute_metrics: ~azure.storage.queue.models.Metrics - :keyword cors: The set of CORS rules. - :paramtype cors: list[~azure.storage.queue.models.CorsRule] - """ - super().__init__(**kwargs) - self.logging = logging - self.hour_metrics = hour_metrics - self.minute_metrics = minute_metrics - self.cors = cors - - -class StorageServiceStats(_serialization.Model): - """Stats for the storage service. - - :ivar geo_replication: Geo-Replication information for the Secondary Storage Service. - :vartype geo_replication: ~azure.storage.queue.models.GeoReplication - """ - - _attribute_map = { - "geo_replication": {"key": "GeoReplication", "type": "GeoReplication"}, - } - - def __init__(self, *, geo_replication: Optional["_models.GeoReplication"] = None, **kwargs: Any) -> None: - """ - :keyword geo_replication: Geo-Replication information for the Secondary Storage Service. - :paramtype geo_replication: ~azure.storage.queue.models.GeoReplication - """ - super().__init__(**kwargs) - self.geo_replication = geo_replication - - -class UserDelegationKey(_serialization.Model): - """A user delegation key. - - All required parameters must be populated in order to send to server. - - :ivar signed_oid: The Azure Active Directory object ID in GUID format. Required. - :vartype signed_oid: str - :ivar signed_tid: The Azure Active Directory tenant ID in GUID format. Required. - :vartype signed_tid: str - :ivar signed_start: The date-time the key is active. Required. - :vartype signed_start: ~datetime.datetime - :ivar signed_expiry: The date-time the key expires. Required. - :vartype signed_expiry: ~datetime.datetime - :ivar signed_service: Abbreviation of the Azure Storage service that accepts the key. Required. - :vartype signed_service: str - :ivar signed_version: The service version that created the key. Required. - :vartype signed_version: str - :ivar signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if - DelegatedUserTid is specified. - :vartype signed_delegated_user_tid: str - :ivar value: The key as a base64 string. Required. - :vartype value: str - """ - - _validation = { - "signed_oid": {"required": True}, - "signed_tid": {"required": True}, - "signed_start": {"required": True}, - "signed_expiry": {"required": True}, - "signed_service": {"required": True}, - "signed_version": {"required": True}, - "value": {"required": True}, - } - - _attribute_map = { - "signed_oid": {"key": "SignedOid", "type": "str"}, - "signed_tid": {"key": "SignedTid", "type": "str"}, - "signed_start": {"key": "SignedStart", "type": "iso-8601"}, - "signed_expiry": {"key": "SignedExpiry", "type": "iso-8601"}, - "signed_service": {"key": "SignedService", "type": "str"}, - "signed_version": {"key": "SignedVersion", "type": "str"}, - "signed_delegated_user_tid": {"key": "SignedDelegatedUserTid", "type": "str"}, - "value": {"key": "Value", "type": "str"}, - } - - def __init__( - self, - *, - signed_oid: str, - signed_tid: str, - signed_start: datetime.datetime, - signed_expiry: datetime.datetime, - signed_service: str, - signed_version: str, - value: str, - signed_delegated_user_tid: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword signed_oid: The Azure Active Directory object ID in GUID format. Required. - :paramtype signed_oid: str - :keyword signed_tid: The Azure Active Directory tenant ID in GUID format. Required. - :paramtype signed_tid: str - :keyword signed_start: The date-time the key is active. Required. - :paramtype signed_start: ~datetime.datetime - :keyword signed_expiry: The date-time the key expires. Required. - :paramtype signed_expiry: ~datetime.datetime - :keyword signed_service: Abbreviation of the Azure Storage service that accepts the key. - Required. - :paramtype signed_service: str - :keyword signed_version: The service version that created the key. Required. - :paramtype signed_version: str - :keyword signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if - DelegatedUserTid is specified. - :paramtype signed_delegated_user_tid: str - :keyword value: The key as a base64 string. Required. - :paramtype value: str - """ - super().__init__(**kwargs) - self.signed_oid = signed_oid - self.signed_tid = signed_tid - self.signed_start = signed_start - self.signed_expiry = signed_expiry - self.signed_service = signed_service - self.signed_version = signed_version - self.signed_delegated_user_tid = signed_delegated_user_tid - self.value = value diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/models/_patch.py index 2e25743cab74..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,15 +1,124 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # 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 typing import Any, Callable, Dict, List, Optional + +from .._utils.serialization import JSON, Model, attribute_transformer + +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. 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. + + :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, + 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, key_transformer=key_transformer, **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] -from typing import List __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/__init__.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py index e53a2d5483fd..3fb890991836 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,10 +12,8 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._service_operations import ServiceOperations # type: ignore -from ._queue_operations import QueueOperations # type: ignore -from ._messages_operations import MessagesOperations # type: ignore -from ._message_id_operations import MessageIdOperations # type: ignore +from ._operations import ServiceOperations # type: ignore +from ._operations import QueueOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -24,8 +22,6 @@ __all__ = [ "ServiceOperations", "QueueOperations", - "MessagesOperations", - "MessageIdOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_message_id_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_message_id_operations.py deleted file mode 100644 index 39c22976afbe..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_message_id_operations.py +++ /dev/null @@ -1,302 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Optional, TypeVar - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureQueueStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_update_request( - url: str, - *, - pop_receipt: str, - visibilitytimeout: int, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") - _params["visibilitytimeout"] = _SERIALIZER.query( - "visibilitytimeout", visibilitytimeout, "int", maximum=604800, minimum=0 - ) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_delete_request( - url: str, - *, - pop_receipt: str, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class MessageIdOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`message_id` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def update( # pylint: disable=inconsistent-return-statements - self, - pop_receipt: str, - visibilitytimeout: int, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - queue_message: Optional[_models.QueueMessage] = None, - **kwargs: Any - ) -> None: - """The Update operation was introduced with version 2011-08-18 of the Queue service API. The - Update Message operation updates the visibility timeout of a message. You can also use this - operation to update the contents of a message. A message must be in a format that can be - included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in - size. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Required. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Delete operation deletes the specified message. - - :param pop_receipt: Required. Specifies the valid pop receipt value returned from an earlier - call to the Get Messages or Update Message operation. Required. - :type pop_receipt: str - :param timeout: The The timeout parameter is expressed in seconds. For more information, see HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if number_of_messages is not None: - _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int", minimum=1) - if visibilitytimeout is not None: - _params["visibilitytimeout"] = _SERIALIZER.query( - "visibilitytimeout", visibilitytimeout, "int", maximum=604800, minimum=0 - ) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_clear_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_enqueue_request( - url: str, - *, - content: Any, - version: str, - visibilitytimeout: Optional[int] = None, - message_time_to_live: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if visibilitytimeout is not None: - _params["visibilitytimeout"] = _SERIALIZER.query( - "visibilitytimeout", visibilitytimeout, "int", maximum=604800, minimum=0 - ) - if message_time_to_live is not None: - _params["messagettl"] = _SERIALIZER.query("message_time_to_live", message_time_to_live, "int", minimum=-1) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_peek_request( - url: str, - *, - version: str, - number_of_messages: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - peekonly: Literal["true"] = kwargs.pop("peekonly", _params.pop("peekonly", "true")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}/messages") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["peekonly"] = _SERIALIZER.query("peekonly", peekonly, "str") - if number_of_messages is not None: - _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int", minimum=1) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class MessagesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`messages` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def dequeue( - self, - number_of_messages: Optional[int] = None, - visibilitytimeout: Optional[int] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> list[_models.DequeuedMessageItem]: - """The Dequeue operation retrieves one or more messages from the front of the queue. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds, - relative to server time. The default value is 30 seconds. A specified value must be larger than - or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol - versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value - later than the expiry time. Default value is None. - :type visibilitytimeout: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """The Clear operation deletes all messages from the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.EnqueuedMessage]: - """The Enqueue operation adds a new message to the back of the message queue. A visibility timeout - can also be specified to make the message invisible until the visibility timeout expires. A - message must be in a format that can be included in an XML request with UTF-8 encoding. The - encoded message can be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size - for previous versions. - - :param queue_message: A Message object which can be stored in a Queue. Required. - :type queue_message: ~azure.storage.queue.models.QueueMessage - :param visibilitytimeout: Optional. If specified, the request must be made using an - x-ms-version of 2011-08-18 or later. If not specified, the default value is 0. Specifies the - new visibility timeout value, in seconds, relative to server time. The new value must be larger - than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message - cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value - smaller than the time-to-live value. Default value is None. - :type visibilitytimeout: int - :param message_time_to_live: Optional. Specifies the time-to-live interval for the message, in - seconds. Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For version - 2017-07-29 or later, the maximum time-to-live can be any positive number, as well as -1 - indicating that the message does not expire. If this parameter is omitted, the default - time-to-live is 7 days. Default value is None. - :type message_time_to_live: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.PeekedMessageItem]: - """The Peek operation retrieves one or more messages from the front of the queue, but does not - alter the visibility of the message. - - :param number_of_messages: Optional. A nonzero integer value that specifies the number of - messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible - messages are returned. By default, a single message is retrieved from the queue with this - operation. Default value is None. - :type number_of_messages: int - :param timeout: The The timeout parameter is expressed in seconds. For more information, see HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?restype=service&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_properties_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=service&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_statistics_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=service&comp=stats" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_user_delegation_key_request( # pylint: disable=name-too-long + *, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=service&comp=userdelegationkey" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_queues_request( + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?comp=list" + + # Construct parameters + if prefix is not None: + _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if maxresults is not None: + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if include is not None: + _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_create_request( + *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_get_properties_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?comp=metadata" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_delete_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_set_metadata_request( + *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?comp=metadata" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_get_access_policy_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?comp=acl" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_set_access_policy_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "?comp=acl" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_receive_messages_request( + *, + number_of_messages: Optional[int] = None, + visibility_timeout: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/messages" + + # Construct parameters + if number_of_messages is not None: + _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int") + if visibility_timeout is not None: + _params["visibilitytimeout"] = _SERIALIZER.query("visibility_timeout", visibility_timeout, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_clear_request(*, timeout: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "/messages" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_send_message_request( + *, + visibility_timeout: Optional[int] = None, + message_time_to_live: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/messages" + + # Construct parameters + if visibility_timeout is not None: + _params["visibilitytimeout"] = _SERIALIZER.query("visibility_timeout", visibility_timeout, "int") + if message_time_to_live is not None: + _params["messagettl"] = _SERIALIZER.query("message_time_to_live", message_time_to_live, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_peek_messages_request( + *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/messages?peekonly=true" + + # Construct parameters + if number_of_messages is not None: + _params["numofmessages"] = _SERIALIZER.query("number_of_messages", number_of_messages, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_update_message_request( + message_id: str, *, pop_receipt: str, visibility_timeout: int, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "/messages/{messageId}" + path_format_arguments = { + "messageId": _SERIALIZER.url("message_id", message_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") + _params["visibilitytimeout"] = _SERIALIZER.query("visibility_timeout", visibility_timeout, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_queue_delete_message_request( + message_id: str, *, pop_receipt: str, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) + # Construct URL + _url = "/messages/{messageId}" + path_format_arguments = { + "messageId": _SERIALIZER.url("message_id", message_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["popreceipt"] = _SERIALIZER.query("pop_receipt", pop_receipt, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.queue.QueuesClient`'s + :attr:`service` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def set_properties( # pylint: disable=inconsistent-return-statements + self, queue_service_properties: _models.QueueServiceProperties, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Sets properties for a storage account's Queue service endpoint, including properties for + Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :param queue_service_properties: The storage service properties to set. Required. + :type queue_service_properties: ~azure.storage.queue._generated.models.QueueServiceProperties + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(queue_service_properties) + + _request = build_service_set_properties_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_properties(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceProperties: + """Retrieves properties of a storage account's Queue service, including properties for Storage + Analytics and CORS (Cross-Origin Resource Sharing) rules. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceProperties. The QueueServiceProperties is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceProperties] = kwargs.pop("cls", None) + + _request = build_service_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceProperties, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_statistics(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.QueueServiceStats: + """Retrieves statistics related to replication for the Queue service. It is only available on the + secondary location endpoint when read-access geo-redundant replication is enabled for the + storage account. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: QueueServiceStats. The QueueServiceStats is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.QueueServiceStats + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.QueueServiceStats] = kwargs.pop("cls", None) + + _request = build_service_get_statistics_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.QueueServiceStats, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_user_delegation_key( + self, key_info: _models.KeyInfo, *, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.UserDelegationKey: + """Retrieves a user delegation key for the Queue service. This is only a valid operation when + using bearer token authentication. + + :param key_info: Key information. Required. + :type key_info: ~azure.storage.queue._generated.models.KeyInfo + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.UserDelegationKey + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) + + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.UserDelegationKey, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_queues( + self, + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + include: Optional[list[Union[str, _models.ListQueuesIncludeType]]] = None, + **kwargs: Any + ) -> _models.ListQueuesResponse: + """Returns a list of 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: 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. + :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: 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 + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListQueuesResponse] = kwargs.pop("cls", None) + + _request = build_service_get_queues_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, + timeout=timeout, + include=include, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListQueuesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class QueueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.queue.QueuesClient`'s + :attr:`queue` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: QueuesClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def create( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any + ) -> None: + """Creates a new queue. 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 + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_create_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_properties( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Returns all user-defined metadata and system properties for the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_get_properties_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("str", response.headers.get("x-ms-meta")) + response_headers["x-ms-approximate-messages-count"] = self._deserialize( + "int", response.headers.get("x-ms-approximate-messages-count") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Permanently deletes the specified queue. + + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def set_metadata( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, metadata: Optional[str] = None, **kwargs: Any + ) -> None: + """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 + :keyword metadata: The metadata headers. Default value is None. + :paramtype metadata: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_set_metadata_request( + timeout=timeout, + metadata=metadata, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_access_policy(self, *, timeout: Optional[int] = None, **kwargs: Any) -> _models.SignedIdentifiers: + """Gets the 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 + :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.SignedIdentifiers + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + + _request = build_queue_get_access_policy_request( + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.SignedIdentifiers, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def set_access_policy( # pylint: disable=inconsistent-return-statements + self, queue_acl: Optional[_models.SignedIdentifiers] = None, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Sets the permissions for the specified queue. + + :param queue_acl: The access control list. Default value is None. + :type queue_acl: ~azure.storage.queue._generated.models.SignedIdentifiers + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_acl else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_acl is not None: + _content = _get_element(queue_acl) + else: + _content = None + + _request = build_queue_set_access_policy_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def receive_messages( + self, + *, + number_of_messages: Optional[int] = None, + visibility_timeout: Optional[int] = None, + timeout: Optional[int] = None, + **kwargs: Any + ) -> _models.ReceivedMessages: + """Retrieves one or more messages from the front of the queue. + + :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. 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 + :return: ReceivedMessages. The ReceivedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ReceivedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ReceivedMessages] = kwargs.pop("cls", None) + + _request = build_queue_receive_messages_request( + number_of_messages=number_of_messages, + visibility_timeout=visibility_timeout, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ReceivedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def clear( # pylint: disable=inconsistent-return-statements + self, *, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """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: + """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: 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. 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: Specifies the time-to-live interval for the message, in seconds. + Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For + version 2017-07-29 or later, the maximum time-to-live can be any positive + number, as well as -1 indicating that the message does not expire. If this + parameter is omitted, the default time-to-live is 7 days. Default value is None. + :paramtype message_time_to_live: int + :keyword timeout: The timeout parameter is expressed in seconds. For more information, see + Setting + Timeouts for Queue Service Operations.. Default value is None. + :paramtype timeout: int + :return: ListOfSentMessage. The ListOfSentMessage is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.ListOfSentMessage + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.ListOfSentMessage] = kwargs.pop("cls", None) + + _content = _get_element(queue_message) + + _request = build_queue_send_message_request( + visibility_timeout=visibility_timeout, + message_time_to_live=message_time_to_live, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListOfSentMessage, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def peek_messages( + self, *, number_of_messages: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.PeekedMessages: + """Retrieves one or more messages from the front of the queue, but does not alter the visibility + of the message. + + :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 + :return: PeekedMessages. The PeekedMessages is compatible with MutableMapping + :rtype: ~azure.storage.queue._generated.models.PeekedMessages + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PeekedMessages] = kwargs.pop("cls", None) + + _request = build_queue_peek_messages_request( + number_of_messages=number_of_messages, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.PeekedMessages, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def update_message( # pylint: disable=inconsistent-return-statements + self, + message_id: str, + queue_message: Optional[_models.QueueMessage] = None, + *, + pop_receipt: str, + visibility_timeout: int, + timeout: Optional[int] = None, + **kwargs: Any + ) -> None: + """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. + :type message_id: str + :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: 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. 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 + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if queue_message else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if queue_message is not None: + _content = _get_element(queue_message) + else: + _content = None + + _request = build_queue_update_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + visibility_timeout=visibility_timeout, + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-popreceipt"] = self._deserialize("str", response.headers.get("x-ms-popreceipt")) + response_headers["x-ms-time-next-visible"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-time-next-visible") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def delete_message( # pylint: disable=inconsistent-return-statements + self, message_id: str, *, pop_receipt: str, timeout: Optional[int] = None, **kwargs: Any + ) -> None: + """Deletes the specified message. + + :param message_id: The ID of the queue message. Required. + :type message_id: str + :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 + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_queue_delete_message_request( + message_id=message_id, + pop_receipt=pop_receipt, + timeout=timeout, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py index 2e25743cab74..87676c65a8f0 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_patch.py @@ -1,17 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_queue_operations.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_queue_operations.py deleted file mode 100644 index ddd138f17de9..000000000000 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_queue_operations.py +++ /dev/null @@ -1,707 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureQueueStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_properties_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_metadata_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_access_policy_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_access_policy_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -class QueueOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`queue` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def create( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """creates a new queue under the given account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """operation permanently deletes the specified queue. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """Retrieves user-defined metadata and queue properties on the specified queue. Metadata is - associated with the queue as name-values pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets user-defined metadata on the specified queue. Metadata is associated with the queue as - name-value pairs. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see list[_models.SignedIdentifier]: - """returns details about any stored access policies specified on the queue that may be used with - Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: - """sets stored access policies for the queue that may be used with Shared Access Signatures. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_get_properties_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_statistics_request( - url: str, *, version: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["stats"] = kwargs.pop("comp", _params.pop("comp", "stats")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_user_delegation_key_request( - url: str, - *, - content: Any, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["userdelegationkey"] = kwargs.pop("comp", _params.pop("comp", "userdelegationkey")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_list_queues_segment_request( - url: str, - *, - version: str, - prefix: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - include: Optional[list[Literal["metadata"]]] = None, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if prefix is not None: - _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if maxresults is not None: - _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int", minimum=1) - if include is not None: - _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ServiceOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.queue.AzureQueueStorage`'s - :attr:`service` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureQueueStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements - self, - storage_service_properties: _models.StorageServiceProperties, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """Sets properties for a storage account's Queue service endpoint, including properties for - Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param storage_service_properties: The StorageService properties. Required. - :type storage_service_properties: ~azure.storage.queue.models.StorageServiceProperties - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceProperties: - """gets the properties of a storage account's Queue service, including properties for Storage - Analytics and CORS (Cross-Origin Resource Sharing) rules. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.StorageServiceStats: - """Retrieves statistics related to replication for the Queue service. It is only available on the - secondary location endpoint when read-access geo-redundant replication is enabled for the - storage account. - - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.UserDelegationKey: - """Retrieves a user delegation key for the Queue service. This is only a valid operation when - using bearer token authentication. - - :param key_info: Key information. Required. - :type key_info: ~azure.storage.queue.models.KeyInfo - :param timeout: The The timeout parameter is expressed in seconds. For more information, see _models.ListQueuesSegmentResponse: - """The List Queues Segment operation returns a list of the queues under the specified account. - - :param prefix: Filters the results to return only queues whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param marker: A string value that identifies the portion of the list of queues to be returned - with the next listing operation. The operation returns the NextMarker value within the response - body if the listing operation did not return all queues remaining to be listed with the current - page. The NextMarker value can be used as the value for the marker parameter in a subsequent - call to request the next page of list items. The marker value is opaque to the client. Default - value is None. - :type marker: str - :param maxresults: Specifies the maximum number of queues to return. If the request does not - specify maxresults, or specifies a value greater than 5000, the server will return up to 5000 - items. Note that if the listing operation crosses a partition boundary, then the service will - return a continuation token for retrieving the remainder of the results. For this reason, it is - possible that the service will return fewer results than specified by maxresults, or than the - default of 5000. Default value is None. - :type maxresults: int - :param include: Include this parameter to specify that the queues' metadata be returned as part - of the response body. Default value is None. - :type include: list[str] - :param timeout: The The timeout parameter is expressed in seconds. For more information, see None: self.key_encryption_key = None self.resolver = None - def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[str, Any]) -> object: - for message in obj: + def __call__( + self, + response: "PipelineResponse", + obj: Iterable, + headers: Dict[str, Any], + ) -> object: + # ``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 content = message.message_text @@ -89,7 +97,10 @@ def __call__(self, response: "PipelineResponse", obj: Iterable, headers: Dict[st self.key_encryption_key, self.resolver, ) - message.message_text = self.decode(content, response) + decoded = self.decode(content, response) + # Store decoded content on a side attribute to bypass the _RestField + # descriptor which would re-serialize bytes back to base64. + message._decoded_content = decoded return obj def configure( diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py index 5fd01179d74e..79a9f0664951 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_models.py @@ -13,7 +13,9 @@ 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 from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import Logging as GeneratedLogging @@ -29,7 +31,7 @@ from datetime import datetime -class RetentionPolicy(GeneratedRetentionPolicy): +class RetentionPolicy(_BackCompatMixin): """The retention policy which determines how long the associated data should persist. @@ -47,6 +49,16 @@ class RetentionPolicy(GeneratedRetentionPolicy): 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"}, + } + def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: self.enabled = enabled self.days = days @@ -62,8 +74,11 @@ def _from_generated(cls, generated: Any) -> Self: days=generated.days, ) + def _to_generated(self) -> GeneratedRetentionPolicy: + return GeneratedRetentionPolicy(enabled=self.enabled, days=self.days) + -class QueueAnalyticsLogging(GeneratedLogging): +class QueueAnalyticsLogging(_BackCompatMixin): """Azure Analytics Logging settings. All required parameters must be populated in order to send to Azure. @@ -86,6 +101,22 @@ class QueueAnalyticsLogging(GeneratedLogging): retention_policy: RetentionPolicy = RetentionPolicy() """The retention policy for the metrics.""" + _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) @@ -107,8 +138,20 @@ def _from_generated(cls, generated: Any) -> Self: ), ) + @staticmethod + def _to_generated(logging: Optional["QueueAnalyticsLogging"]) -> Optional[GeneratedLogging]: + if logging is None: + return None + return GeneratedLogging( + version=logging.version, + delete=logging.delete, + read=logging.read, + write=logging.write, + retention_policy=logging.retention_policy._to_generated(), # pylint: disable=protected-access + ) + -class Metrics(GeneratedMetrics): +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. @@ -129,6 +172,17 @@ class Metrics(GeneratedMetrics): 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"}, + "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) @@ -148,8 +202,19 @@ def _from_generated(cls, generated: Any) -> Self: ), ) + @staticmethod + def _to_generated(metrics: Optional["Metrics"]) -> Optional[GeneratedMetrics]: + if metrics is None: + return None + return GeneratedMetrics( + version=metrics.version, + enabled=metrics.enabled, + include_apis=metrics.include_apis, + retention_policy=metrics.retention_policy._to_generated(), # pylint: disable=protected-access + ) -class CorsRule(GeneratedCorsRule): + +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 @@ -181,9 +246,9 @@ class CorsRule(GeneratedCorsRule): 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.""" + 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.""" @@ -193,6 +258,22 @@ class CorsRule(GeneratedCorsRule): """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"}, + "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) @@ -274,7 +355,7 @@ def __init__( + ("p" if self.process else "") ) - def __str__(self): + def __str__(self) -> str: return self._str @classmethod @@ -300,7 +381,7 @@ def from_string(cls, permission: str) -> Self: return parsed -class AccessPolicy(GenAccessPolicy): +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 @@ -340,14 +421,20 @@ class AccessPolicy(GenAccessPolicy): 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.""" + _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, @@ -358,6 +445,26 @@ 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): + permission = str(permission) + return GenAccessPolicy( + start=serialize_iso(self.start), + expiry=serialize_iso(self.expiry), + permission=permission, + ) + class QueueMessage(DictMixin): """Represents a queue message.""" @@ -397,7 +504,13 @@ def __init__(self, content: Optional[Any] = None, **kwargs: Any) -> None: @classmethod def _from_generated(cls, generated: Any) -> Self: - message = cls(content=generated.message_text) + # Prefer _decoded_content if set by MessageDecodePolicy (handles base64 decoding and decryption). + # The decode policy stores results in _decoded_content because the generated model's message_text + # RestField descriptor may re-serialize bytes back to base64 if set directly. + content = getattr(generated, "_decoded_content", None) + if content is None: + content = generated.message_text + message = cls(content=content) message.id = generated.message_id message.inserted_on = generated.insertion_time message.expires_on = generated.expiration_time @@ -457,11 +570,13 @@ def _get_next_cb(self, continuation_token: Optional[str]) -> Any: def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: # There is no concept of continuation token, so raising on my own condition - if not messages: + if not messages or not messages.items_property: raise StopIteration("End of paging") if self._max_messages is not None: - self._max_messages = self._max_messages - len(messages) - return "TOKEN_IGNORED", [QueueMessage._from_generated(q) for q in messages] # pylint: disable=protected-access + self._max_messages = self._max_messages - len(messages.items_property) + return "TOKEN_IGNORED", [ + QueueMessage._from_generated(q) for q in messages.items_property # pylint: disable=protected-access + ] class QueueProperties(DictMixin): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_client.py index 17205bbf69eb..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 @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -15,14 +16,14 @@ from azure.core.tracing.decorator import distributed_trace from ._deserialize import deserialize_queue_creation, deserialize_queue_properties from ._encryption import modify_user_agent_for_encryption, StorageEncryptionMixin -from ._generated import AzureQueueStorage -from ._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier +from ._generated import QueuesClient as AzureQueueStorage +from ._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers from ._message_encoding import NoDecodePolicy, NoEncodePolicy from ._models import AccessPolicy, MessagesPaged, QueueMessage from ._queue_client_helpers import _format_url, _from_queue_url, _parse_url 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, @@ -135,8 +136,7 @@ def __init__( self._message_decode_policy = message_decode_policy or NoDecodePolicy() self._client = AzureQueueStorage( self.url, - get_api_version(api_version), - base_url=self.url, + version=get_api_version(api_version), pipeline=self._pipeline, ) self._configure_encryption(kwargs) @@ -489,12 +489,19 @@ def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwargs: An """ try: _, identifiers = cast( - Tuple[Dict, List], + Tuple[Dict, SignedIdentifiers], self._client.queue.get_access_policy(timeout=timeout, cls=return_headers_and_deserialized, **kwargs), ) except HttpResponseError as error: process_storage_error(error) - return {s.id: s.access_policy or AccessPolicy() for s in identifiers} + return ( + { + s.id: AccessPolicy._from_generated(s.access_policy) # pylint: disable=protected-access + for s in (identifiers.items_property or []) + } + if identifiers + else {} + ) @distributed_trace def set_queue_access_policy( @@ -542,12 +549,13 @@ 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) - identifiers.append(SignedIdentifier(id=key, access_policy=value)) + 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=identifiers or None, timeout=timeout, **kwargs) + self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -641,20 +649,20 @@ def send_message( new_message = GenQueueMessage(message_text=encoded_content) try: - enqueued = self._client.messages.enqueue( + enqueued = self._client.queue.send_message( queue_message=new_message, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, message_time_to_live=time_to_live, timeout=timeout, **kwargs ) queue_message = QueueMessage( content=content, - id=enqueued[0].message_id, - inserted_on=enqueued[0].insertion_time, - expires_on=enqueued[0].expiration_time, - pop_receipt=enqueued[0].pop_receipt, - next_visible_on=enqueued[0].time_next_visible, + id=enqueued.items_property[0].message_id, + inserted_on=enqueued.items_property[0].insertion_time, + expires_on=enqueued.items_property[0].expiration_time, + pop_receipt=enqueued.items_property[0].pop_receipt, + next_visible_on=enqueued.items_property[0].time_next_visible, ) return queue_message except HttpResponseError as error: @@ -715,15 +723,17 @@ def receive_message( resolver=self.key_resolver_function, ) try: - message = self._client.messages.dequeue( + message = self._client.queue.receive_messages( number_of_messages=1, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message[0]) if message != [] else None # pylint: disable=protected-access + QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access + if message.items_property + else None ) return wrapped_message except HttpResponseError as error: @@ -812,8 +822,8 @@ def receive_messages( ) try: command = functools.partial( - self._client.messages.dequeue, - visibilitytimeout=visibility_timeout, + self._client.queue.receive_messages, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs @@ -943,13 +953,13 @@ def update_message( try: response = cast( QueueMessage, - self._client.message_id.update( + self._client.queue.update_message( queue_message=updated, - visibilitytimeout=visibility_timeout or 0, + visibility_timeout=visibility_timeout or 0, timeout=timeout, pop_receipt=receipt, cls=return_response_headers, - queue_message_id=message_id, + message_id=message_id, **kwargs ), ) @@ -1026,11 +1036,11 @@ def peek_messages( resolver=self.key_resolver_function, ) try: - messages = self._client.messages.peek( + messages = self._client.queue.peek_messages( number_of_messages=max_messages, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_messages = [] - for peeked in messages: + for peeked in messages.items_property or []: wrapped_messages.append(QueueMessage._from_generated(peeked)) # pylint: disable=protected-access return wrapped_messages except HttpResponseError as error: @@ -1057,7 +1067,7 @@ def clear_messages(self, *, timeout: Optional[int] = None, **kwargs: Any) -> Non :caption: Clears all messages. """ try: - self._client.messages.clear(timeout=timeout, **kwargs) + self._client.queue.clear(timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -1115,6 +1125,6 @@ def delete_message( if receipt is None: raise ValueError("pop_receipt must be present") try: - self._client.message_id.delete(pop_receipt=receipt, timeout=timeout, queue_message_id=message_id, **kwargs) + self._client.queue.delete_message(pop_receipt=receipt, timeout=timeout, message_id=message_id, **kwargs) except HttpResponseError as error: process_storage_error(error) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_service_client.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_queue_service_client.py index 84fbef762fe0..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 @@ -14,10 +14,12 @@ from azure.core.pipeline import Pipeline from azure.core.tracing.decorator import distributed_trace from ._encryption import StorageEncryptionMixin -from ._generated import AzureQueueStorage -from ._generated.models import KeyInfo, StorageServiceProperties +from ._generated import QueuesClient as AzureQueueStorage +from ._generated.models import KeyInfo, QueueServiceProperties as StorageServiceProperties from ._models import ( CorsRule, + 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 @@ -133,12 +134,7 @@ def __init__( audience=audience, **kwargs, ) - self._client = AzureQueueStorage( - self.url, - get_api_version(api_version), - base_url=self.url, - pipeline=self._pipeline, - ) + self._client = AzureQueueStorage(self.url, version=get_api_version(api_version), pipeline=self._pipeline) self._configure_encryption(kwargs) def __enter__(self) -> Self: @@ -385,9 +381,9 @@ def set_service_properties( :caption: Setting queue service properties. """ props = StorageServiceProperties( - logging=analytics_logging, - hour_metrics=hour_metrics, - minute_metrics=minute_metrics, + 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: @@ -440,7 +436,7 @@ def list_queues( """ include = ["metadata"] if include_metadata else None command = functools.partial( - self._client.service.list_queues_segment, + self._client.service.get_queues, prefix=name_starts_with, include=include, timeout=timeout, diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/policies.py index f4f602d1c669..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) @@ -473,17 +467,26 @@ 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): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/response_handlers.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_shared/response_handlers.py index 5d9a5ee30fe9..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 @@ -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 @@ -95,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, @@ -223,8 +230,16 @@ def parse_to_internal_user_delegation_key(service_user_delegation_key): internal_user_delegation_key.signed_oid = service_user_delegation_key.signed_oid internal_user_delegation_key.signed_tid = service_user_delegation_key.signed_tid internal_user_delegation_key.signed_delegated_user_tid = service_user_delegation_key.signed_delegated_user_tid - internal_user_delegation_key.signed_start = _to_utc_datetime(service_user_delegation_key.signed_start) - internal_user_delegation_key.signed_expiry = _to_utc_datetime(service_user_delegation_key.signed_expiry) + internal_user_delegation_key.signed_start = ( + service_user_delegation_key.signed_start + if isinstance(service_user_delegation_key.signed_start, str) + else _to_utc_datetime(service_user_delegation_key.signed_start) + ) + internal_user_delegation_key.signed_expiry = ( + service_user_delegation_key.signed_expiry + if isinstance(service_user_delegation_key.signed_expiry, str) + else _to_utc_datetime(service_user_delegation_key.signed_expiry) + ) internal_user_delegation_key.signed_service = service_user_delegation_key.signed_service internal_user_delegation_key.signed_version = service_user_delegation_key.signed_version internal_user_delegation_key.value = service_user_delegation_key.value diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py b/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py index a2ba5779ef0d..195162b92aac 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/_version.py @@ -1,7 +1,9 @@ +# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- VERSION = "12.18.0b1" diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py index cbd506fbd183..90b04166b7ec 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_models.py @@ -65,11 +65,13 @@ async def _get_next_cb(self, continuation_token: Optional[str]) -> Any: async def _extract_data_cb(self, messages: Any) -> Tuple[str, List[QueueMessage]]: # There is no concept of continuation token, so raising on my own condition - if not messages: + if not messages or not messages.items_property: raise StopAsyncIteration("End of paging") if self._max_messages is not None: - self._max_messages = self._max_messages - len(messages) - return "TOKEN_IGNORED", [QueueMessage._from_generated(q) for q in messages] # pylint: disable=protected-access + self._max_messages = self._max_messages - len(messages.items_property) + return "TOKEN_IGNORED", [ + QueueMessage._from_generated(q) for q in messages.items_property # pylint: disable=protected-access + ] class QueuePropertiesPaged(AsyncPageIterator): diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_client_async.py b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_client_async.py index ed1c7e8b64b6..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 @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -17,8 +18,8 @@ from ._models import MessagesPaged from .._deserialize import deserialize_queue_creation, deserialize_queue_properties from .._encryption import modify_user_agent_for_encryption, StorageEncryptionMixin -from .._generated.aio import AzureQueueStorage -from .._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier +from .._generated.aio import QueuesClient as AzureQueueStorage +from .._generated.models import QueueMessage as GenQueueMessage, SignedIdentifier, SignedIdentifiers from .._message_encoding import NoDecodePolicy, NoEncodePolicy from .._models import AccessPolicy, QueueMessage from .._queue_client_helpers import _format_url, _from_queue_url, _parse_url @@ -29,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, @@ -147,10 +148,8 @@ def __init__( self._message_decode_policy = message_decode_policy or NoDecodePolicy() self._client = AzureQueueStorage( self.url, - get_api_version(api_version), - base_url=self.url, + version=get_api_version(api_version), pipeline=self._pipeline, - loop=loop, ) self._loop = loop self._configure_encryption(kwargs) @@ -503,14 +502,21 @@ async def get_queue_access_policy(self, *, timeout: Optional[int] = None, **kwar """ try: _, identifiers = cast( - Tuple[Dict, List], + Tuple[Dict, SignedIdentifiers], await self._client.queue.get_access_policy( timeout=timeout, cls=return_headers_and_deserialized, **kwargs ), ) except HttpResponseError as error: process_storage_error(error) - return {s.id: s.access_policy or AccessPolicy() for s in identifiers} + return ( + { + s.id: AccessPolicy._from_generated(s.access_policy) # pylint: disable=protected-access + for s in (identifiers.items_property or []) + } + if identifiers + else {} + ) @distributed_trace_async async def set_queue_access_policy( @@ -558,12 +564,13 @@ 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) - identifiers.append(SignedIdentifier(id=key, access_policy=value)) + 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=identifiers or None, timeout=timeout, **kwargs) + await self._client.queue.set_access_policy(queue_acl=signed_identifiers_model, timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -657,20 +664,20 @@ async def send_message( new_message = GenQueueMessage(message_text=encoded_content) try: - enqueued = await self._client.messages.enqueue( + enqueued = await self._client.queue.send_message( queue_message=new_message, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, message_time_to_live=time_to_live, timeout=timeout, **kwargs ) queue_message = QueueMessage( content=content, - id=enqueued[0].message_id, - inserted_on=enqueued[0].insertion_time, - expires_on=enqueued[0].expiration_time, - pop_receipt=enqueued[0].pop_receipt, - next_visible_on=enqueued[0].time_next_visible, + id=enqueued.items_property[0].message_id, + inserted_on=enqueued.items_property[0].insertion_time, + expires_on=enqueued.items_property[0].expiration_time, + pop_receipt=enqueued.items_property[0].pop_receipt, + next_visible_on=enqueued.items_property[0].time_next_visible, ) return queue_message except HttpResponseError as error: @@ -731,15 +738,17 @@ async def receive_message( resolver=self.key_resolver_function, ) try: - message = await self._client.messages.dequeue( + message = await self._client.queue.receive_messages( number_of_messages=1, - visibilitytimeout=visibility_timeout, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_message = ( - QueueMessage._from_generated(message[0]) if message != [] else None # pylint: disable=protected-access + QueueMessage._from_generated(message.items_property[0]) # pylint: disable=protected-access + if message.items_property + else None ) return wrapped_message except HttpResponseError as error: @@ -818,8 +827,8 @@ def receive_messages( ) try: command = functools.partial( - self._client.messages.dequeue, - visibilitytimeout=visibility_timeout, + self._client.queue.receive_messages, + visibility_timeout=visibility_timeout, timeout=timeout, cls=self._message_decode_policy, **kwargs @@ -949,13 +958,13 @@ async def update_message( try: response = cast( QueueMessage, - await self._client.message_id.update( + await self._client.queue.update_message( queue_message=updated, - visibilitytimeout=visibility_timeout or 0, + visibility_timeout=visibility_timeout or 0, timeout=timeout, pop_receipt=receipt, cls=return_response_headers, - queue_message_id=message_id, + message_id=message_id, **kwargs ), ) @@ -1032,11 +1041,11 @@ async def peek_messages( resolver=self.key_resolver_function, ) try: - messages = await self._client.messages.peek( + messages = await self._client.queue.peek_messages( number_of_messages=max_messages, timeout=timeout, cls=self._message_decode_policy, **kwargs ) wrapped_messages = [] - for peeked in messages: + for peeked in messages.items_property or []: wrapped_messages.append(QueueMessage._from_generated(peeked)) # pylint: disable=protected-access return wrapped_messages except HttpResponseError as error: @@ -1063,7 +1072,7 @@ async def clear_messages(self, *, timeout: Optional[int] = None, **kwargs: Any) :caption: Clears all messages. """ try: - await self._client.messages.clear(timeout=timeout, **kwargs) + await self._client.queue.clear(timeout=timeout, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -1121,8 +1130,8 @@ async def delete_message( if receipt is None: raise ValueError("pop_receipt must be present") try: - await self._client.message_id.delete( - pop_receipt=receipt, timeout=timeout, queue_message_id=message_id, **kwargs + await self._client.queue.delete_message( + pop_receipt=receipt, timeout=timeout, message_id=message_id, **kwargs ) except HttpResponseError as error: process_storage_error(error) diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_service_client_async.py b/sdk/storage/azure-storage-queue/azure/storage/queue/aio/_queue_service_client_async.py index bd694412a038..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 @@ -17,10 +17,12 @@ 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.aio import QueuesClient as AzureQueueStorage +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 @@ -135,10 +136,8 @@ def __init__( ) self._client = AzureQueueStorage( self.url, - get_api_version(api_version), - base_url=self.url, + version=get_api_version(api_version), pipeline=self._pipeline, - loop=loop, ) self._loop = loop self._configure_encryption(kwargs) @@ -386,9 +385,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=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: @@ -441,7 +440,7 @@ def list_queues( """ include = ["metadata"] if include_metadata else None command = functools.partial( - self._client.service.list_queues_segment, + self._client.service.get_queues, prefix=name_starts_with, include=include, timeout=timeout, diff --git a/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed b/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed index e69de29bb2d1..e5aff4f83af8 100644 --- a/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed +++ b/sdk/storage/azure-storage-queue/azure/storage/queue/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/storage/azure-storage-queue/pyproject.toml b/sdk/storage/azure-storage-queue/pyproject.toml index e0b490cb8fec..105505bc1ea5 100644 --- a/sdk/storage/azure-storage-queue/pyproject.toml +++ b/sdk/storage/azure-storage-queue/pyproject.toml @@ -1,3 +1,71 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-storage-queue" +authors = [ + { name = "Microsoft Corporation", email = "ascl@microsoft.com" }, +] +description = "Microsoft Corporation Azure Storage Queue Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "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"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.38.3", + "typing-extensions>=4.6.0", + "cryptography>=2.1.4", +] +dynamic = [ +"version", "readme" +] + +[project.optional-dependencies] +aio = [ + "azure-core[aio]>=1.38.3", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.storage.queue._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.storage", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] + [tool.azure-sdk-build] mypy = true pyright = false diff --git a/sdk/storage/azure-storage-queue/setup.py b/sdk/storage/azure-storage-queue/setup.py deleted file mode 100644 index a3791f2a8895..000000000000 --- a/sdk/storage/azure-storage-queue/setup.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -import re -import os.path -from io import open -from setuptools import find_packages, setup # type: ignore - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-storage-queue" -PACKAGE_PPRINT_NAME = "Azure Queue Storage" - -# a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace("-", "/") -# a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace("-", ".") - -# Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) # type: ignore - -if not version: - raise RuntimeError("Cannot find version information") - -with open("README.md", encoding="utf-8") as f: - readme = f.read() -with open("CHANGELOG.md", encoding="utf-8") as f: - changelog = f.read() - -setup( - name=PACKAGE_NAME, - version=version, - include_package_data=True, - description=f"Microsoft Azure {PACKAGE_PPRINT_NAME} Client Library for Python", - long_description=readme + "\n\n" + changelog, - long_description_content_type="text/markdown", - license="MIT License", - author="Microsoft Corporation", - author_email="ascl@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-queue", - keywords="azure, azure sdk", - classifiers=[ - "Development Status :: 4 - Beta", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Programming Language :: Python :: 3.14", - "License :: OSI Approved :: MIT License", - ], - zip_safe=False, - packages=find_packages( - exclude=[ - # Exclude packages that will be covered by PEP420 or nspkg - "azure", - "azure.storage", - "tests", - "tests.queue", - "tests.common", - ] - ), - python_requires=">=3.9", - install_requires=[ - "azure-core>=1.37.0", - "cryptography>=2.1.4", - "typing-extensions>=4.6.0", - "isodate>=0.6.1", - ], - extras_require={ - "aio": [ - "azure-core[aio]>=1.37.0", - ], - }, -) diff --git a/sdk/storage/azure-storage-queue/tests/conftest.py b/sdk/storage/azure-storage-queue/tests/conftest.py index 8a80ea7d6c86..b247291ef191 100644 --- a/sdk/storage/azure-storage-queue/tests/conftest.py +++ b/sdk/storage/azure-storage-queue/tests/conftest.py @@ -14,6 +14,8 @@ add_header_regex_sanitizer, add_oauth_response_sanitizer, add_uri_string_sanitizer, + add_remove_header_sanitizer, + set_custom_default_matcher, add_uri_regex_sanitizer, test_proxy, ) @@ -37,6 +39,8 @@ def add_sanitizers(test_proxy): ) add_uri_string_sanitizer(target=".preprod.", value=".") + add_remove_header_sanitizer(headers="Accept") + set_custom_default_matcher(ignore_query_ordering=True) add_uri_regex_sanitizer( regex=r"(?<=[?&]sktid=)[^&#]+", value="00000000-0000-0000-0000-000000000000", diff --git a/sdk/storage/azure-storage-queue/tests/test_queue.py b/sdk/storage/azure-storage-queue/tests/test_queue.py index f831b61cad69..828aa32b19c8 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 a890d4136fc8..ec41c11fa22a 100644 --- a/sdk/storage/azure-storage-queue/tests/test_queue_async.py +++ b/sdk/storage/azure-storage-queue/tests/test_queue_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/storage/azure-storage-queue/tsp-location.yaml b/sdk/storage/azure-storage-queue/tsp-location.yaml new file mode 100644 index 000000000000..f925a9401a4a --- /dev/null +++ b/sdk/storage/azure-storage-queue/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/storage/data-plane/QueueStorage +commit: a0af72e72c4467678f58e404670c18a3f00ce2e1 +repo: Azure/azure-rest-api-specs +additionalDirectories: