azure.storage.queue package

class azure.storage.queue.AccessPolicy(permission: QueueSasPermissions | str | None = None, expiry: datetime | str | None = None, start: datetime | str | None = None)[source]

Access Policy class used by the set and get access policy methods.

A stored access policy can specify the start time, expiry time, and permissions for the Shared Access Signatures with which it’s associated. Depending on how you want to control access to your resource, you can specify all of these parameters within the stored access policy, and omit them from the URL for the Shared Access Signature. Doing so permits you to modify the associated signature’s behavior at any time, as well as to revoke it. Or you can specify one or more of the access policy parameters within the stored access policy, and the others on the URL. Finally, you can specify all of the parameters on the URL. In this case, you can use the stored access policy to revoke the signature, but not to modify its behavior.

Together the Shared Access Signature and the stored access policy must include all fields required to authenticate the signature. If any required fields are missing, the request will fail. Likewise, if a field is specified both in the Shared Access Signature URL and in the stored access policy, the request will fail with status code 400 (Bad Request).

Parameters:
  • permission (Optional[Union[QueueSasPermissions, str]]) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy.

  • expiry (Optional[Union["datetime", str]]) – The time at which the shared access signature becomes invalid. Required unless an id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • start (Optional[Union["datetime", str]]) – The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. The provided datetime will always be interpreted as UTC.

Keyword Arguments:
  • start (str) – the date-time the policy is active.

  • expiry (str) – the date-time the policy expires.

  • permission (str) – the permissions for the acl policy.

as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

Return a dict that can be serialized using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

classmethod deserialize(data: Any, content_type: str | None = None) ModelType

Parse a str using the RestAPI syntax and return a model.

Parameters:
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) ModelType

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters:
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod is_xml_model() bool
serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

Return the JSON that would be sent to server from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns:

A dict JSON compatible object

Return type:

dict

expiry: datetime | str | None

The time at which the shared access signature becomes invalid.

permission: QueueSasPermissions | str | None

The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions.

start: datetime | str | None

The time at which the shared access signature becomes valid.

class azure.storage.queue.AccountSasPermissions(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, **kwargs)[source]

ResourceTypes class to be used with generate_account_sas function and for the AccessPolicies used with set_*_acl. There are two types of SAS which may be used to grant resource access. One is to grant access to a specific resource (resource-specific). Another is to grant access to the entire service for a specific account and allow certain operations based on perms found here.

Parameters:
  • read (bool) – Valid for all signed resources types (Service, Container, and Object). Permits read permissions to the specified resource type.

  • write (bool) – Valid for all signed resources types (Service, Container, and Object). Permits write permissions to the specified resource type.

  • delete (bool) – Valid for Container and Object resource types, except for queue messages.

  • delete_previous_version (bool) – Delete the previous blob version for the versioning enabled storage account.

  • list (bool) – Valid for Service and Container resource types only.

  • add (bool) – Valid for the following Object resource types only: queue messages, and append blobs.

  • create (bool) – Valid for the following Object resource types only: blobs and files. Users can create new blobs or files, but may not overwrite existing blobs or files.

  • update (bool) – Valid for the following Object resource types only: queue messages.

  • process (bool) – Valid for the following Object resource type only: queue messages.

Keyword Arguments:
  • tag (bool) – To enable set or get tags on the blobs in the container.

  • filter_by_tags (bool) – To enable get blobs by tags, this should be used together with list permission.

  • set_immutability_policy (bool) – To enable operations related to set/delete immutability policy. To get immutability policy, you just need read permission.

  • permanent_delete (bool) – To enable permanent delete on the blob is permitted. Valid for Object resource type of Blob only.

classmethod from_string(permission)[source]

Create AccountSasPermissions from a string.

To specify read, write, delete, etc. permissions you need only to include the first letter of the word in the string. E.g. for read and write permissions you would provide a string “rw”.

Parameters:

permission (str) – Specify permissions in the string with the first letter of the word.

Returns:

An AccountSasPermissions object

Return type:

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
class azure.storage.queue.BinaryBase64DecodePolicy[source]

Message decoding policy for base 64-encoded messages into bytes.

Decodes base64-encoded messages to bytes. If the input content is not valid base 64, a DecodeError will be raised.

configure(require_encryption: bool, key_encryption_key: KeyEncryptionKey | None, resolver: Callable[[str], KeyEncryptionKey] | None) None
decode(content: str, response: PipelineResponse) bytes[source]
key_encryption_key: KeyEncryptionKey | None = None

The user-provided key-encryption-key.

require_encryption: bool = False

Indicates whether encryption is required or not.

resolver: Callable[[str], KeyEncryptionKey] | None = None

The user-provided key resolver.

class azure.storage.queue.BinaryBase64EncodePolicy[source]

Base 64 message encoding policy for binary messages.

Encodes binary messages to base 64. If the input content is not bytes, a TypeError will be raised.

configure(require_encryption: bool, key_encryption_key: KeyEncryptionKey | None, resolver: Callable[[str], KeyEncryptionKey] | None, encryption_version: str = '1.0') None
encode(content: bytes) str[source]
encryption_version: str

Indicates the version of encryption being used.

key_encryption_key: KeyEncryptionKey | None

The user-provided key-encryption-key.

require_encryption: bool

Indicates whether encryption is required or not.

resolver: Callable[[str], KeyEncryptionKey] | None

The user-provided key resolver.

class azure.storage.queue.CorsRule(allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any)[source]

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 Azure.

Parameters:
  • allowed_origins (List[str]) – A list of origin domains that will be allowed via CORS, or “*” to allow all domains. The list must contain at least one entry. Limited to 64 origin domains. Each allowed origin can have up to 256 characters.

  • allowed_methods (List[str]) – A list of HTTP methods that are allowed to be executed by the origin. The list must contain at least one entry. For Azure Storage, permitted methods are DELETE, GET, HEAD, MERGE, POST, OPTIONS or PUT.

Keyword Arguments:
  • max_age_in_seconds (int) – The number of seconds that the client/browser should cache a pre-flight response.

  • exposed_headers (str) – Defaults to an empty list. A list of response headers to expose to CORS clients. Limited to 64 defined headers and two prefixed headers. Each header can be up to 256 characters.

  • allowed_headers (str) – Defaults to an empty list. A list of headers allowed to be part of the cross-origin request. Limited to 64 defined headers and 2 prefixed headers. Each header can be up to 256 characters.

  • allowed_origins (str) – The 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.

  • allowed_methods (str) – The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated). Required.

  • allowed_headers – the request headers that the origin domain may specify on the CORS request. Required.

  • 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.

  • max_age_in_seconds – The maximum amount time that a browser should cache the preflight OPTIONS request. Required.

as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

Return a dict that can be serialized using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

classmethod deserialize(data: Any, content_type: str | None = None) ModelType

Parse a str using the RestAPI syntax and return a model.

Parameters:
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) ModelType

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters:
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod is_xml_model() bool
serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

Return the JSON that would be sent to server from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns:

A dict JSON compatible object

Return type:

dict

allowed_headers: str

The comma-delimited string representation of the list of headers allowed to be part of the cross-origin request.

allowed_methods: str

The comma-delimited string representation of the list HTTP methods that are allowed to be executed by the origin.

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.

exposed_headers: str

The comma-delimited string representation of the list of response headers to expose to CORS clients.

max_age_in_seconds: int

The number of seconds that the client/browser should cache a pre-flight response.

class azure.storage.queue.ExponentialRetry(initial_backoff: int = 15, increment_base: int = 3, retry_total: int = 3, retry_to_secondary: bool = False, random_jitter_range: int = 3, **kwargs: Any)[source]

Exponential retry.

Constructs an Exponential retry object. The initial_backoff is used for the first retry. Subsequent retries are retried after initial_backoff + increment_power^retry_count seconds.

Parameters:
  • initial_backoff (int) – The initial backoff interval, in seconds, for the first retry.

  • increment_base (int) – The base, in seconds, to increment the initial_backoff by after the first retry.

  • retry_total (int) – The maximum number of retry attempts.

  • retry_to_secondary (bool) – Whether the request should be retried to secondary, if able. This should only be enabled of RA-GRS accounts are used and potentially stale data can be handled.

  • random_jitter_range (int) – A number in seconds which indicates a range to jitter/randomize for the back-off interval. For example, a random_jitter_range of 3 results in the back-off interval x to vary between x+3 and x-3.

configure_retries(request: PipelineRequest) Dict[str, Any]
get_backoff_time(settings: Dict[str, Any]) float[source]

Calculates how long to sleep before retrying.

Parameters:

settings (Dict[str, Any]]) – The configurable values pertaining to get backoff time.

Returns:

A float indicating how long to wait before retrying the request, or None to indicate no retry should be performed.

Return type:

float

increment(settings: Dict[str, Any], request: PipelineRequest, response: PipelineResponse | None = None, error: AzureError | None = None) bool

Increment the retry counters.

Parameters:
  • settings (dict[str, Any]) – The configurable values pertaining to the increment operation.

  • request (PipelineRequest) – A pipeline request object.

  • response (Optional[PipelineResponse]) – A pipeline response object.

  • error (Optional[AzureError]) – An error encountered during the request, or None if the response was received successfully.

Returns:

Whether the retry attempts are exhausted.

Return type:

bool

send(request)

Abstract send method for a synchronous pipeline. Mutates the request.

Context content is dependent on the HttpTransport.

Parameters:

request (PipelineRequest) – The pipeline request object

Returns:

The pipeline response object.

Return type:

PipelineResponse

sleep(settings, transport)
connect_retries: int

The max number of connect retries.

increment_base: int

The base, in seconds, to increment the initial_backoff by after the first retry.

initial_backoff: int

The initial backoff interval, in seconds, for the first retry.

next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

random_jitter_range: int

A number in seconds which indicates a range to jitter/randomize for the back-off interval.

retry_read: int

The max number of read retries.

retry_status: int

The max number of status retries.

retry_to_secondary: bool

Whether the secondary endpoint should be retried.

total_retries: int

The max number of retries.

class azure.storage.queue.LinearRetry(backoff: int = 15, retry_total: int = 3, retry_to_secondary: bool = False, random_jitter_range: int = 3, **kwargs: Any)[source]

Linear retry.

Constructs a Linear retry object.

Parameters:
  • backoff (int) – The backoff interval, in seconds, between retries.

  • retry_total (int) – The maximum number of retry attempts.

  • retry_to_secondary (bool) – Whether the request should be retried to secondary, if able. This should only be enabled of RA-GRS accounts are used and potentially stale data can be handled.

  • random_jitter_range (int) – A number in seconds which indicates a range to jitter/randomize for the back-off interval. For example, a random_jitter_range of 3 results in the back-off interval x to vary between x+3 and x-3.

configure_retries(request: PipelineRequest) Dict[str, Any]
get_backoff_time(settings: Dict[str, Any]) float[source]

Calculates how long to sleep before retrying.

Parameters:

settings (Dict[str, Any]]) – The configurable values pertaining to the backoff time.

Returns:

A float indicating how long to wait before retrying the request, or None to indicate no retry should be performed.

Return type:

float

increment(settings: Dict[str, Any], request: PipelineRequest, response: PipelineResponse | None = None, error: AzureError | None = None) bool

Increment the retry counters.

Parameters:
  • settings (dict[str, Any]) – The configurable values pertaining to the increment operation.

  • request (PipelineRequest) – A pipeline request object.

  • response (Optional[PipelineResponse]) – A pipeline response object.

  • error (Optional[AzureError]) – An error encountered during the request, or None if the response was received successfully.

Returns:

Whether the retry attempts are exhausted.

Return type:

bool

send(request)

Abstract send method for a synchronous pipeline. Mutates the request.

Context content is dependent on the HttpTransport.

Parameters:

request (PipelineRequest) – The pipeline request object

Returns:

The pipeline response object.

Return type:

PipelineResponse

sleep(settings, transport)
connect_retries: int

The max number of connect retries.

initial_backoff: int

The backoff interval, in seconds, between retries.

next: HTTPPolicy[HTTPRequestType, HTTPResponseType]

Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.

random_jitter_range: int

A number in seconds which indicates a range to jitter/randomize for the back-off interval.

retry_read: int

The max number of read retries.

retry_status: int

The max number of status retries.

retry_to_secondary: bool

Whether the secondary endpoint should be retried.

total_retries: int

The max number of retries.

class azure.storage.queue.LocationMode[source]

Specifies the location the request should be sent to. This mode only applies for RA-GRS accounts which allow secondary read access. All other account types must use PRIMARY.

PRIMARY = 'primary'

Requests should be sent to the primary location.

SECONDARY = 'secondary'

Requests should be sent to the secondary location, if possible.

class azure.storage.queue.Metrics(**kwargs: Any)[source]

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.

Keyword Arguments:
  • version (str) – The version of Storage Analytics to configure.

  • enabled (bool) – Required. Indicates whether metrics are enabled for the service.

  • include_apis (bool) – Indicates whether metrics should generate summary statistics for called API operations.

  • retention_policy (RetentionPolicy) – The retention policy for the metrics.

  • version – The version of Storage Analytics to configure.

  • enabled – Indicates whether metrics are enabled for the Queue service. Required.

  • include_apis – Indicates whether metrics should generate summary statistics for called API operations.

  • retention_policy – the retention policy.

as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

Return a dict that can be serialized using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

classmethod deserialize(data: Any, content_type: str | None = None) ModelType

Parse a str using the RestAPI syntax and return a model.

Parameters:
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) ModelType

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters:
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod is_xml_model() bool
serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

Return the JSON that would be sent to server from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns:

A dict JSON compatible object

Return type:

dict

enabled: bool = False

Indicates whether metrics are enabled for the service.

include_apis: bool | None

Indicates whether metrics should generate summary statistics for called API operations.

retention_policy: RetentionPolicy = <azure.storage.queue._models.RetentionPolicy object>

The retention policy for the metrics.

version: str = '1.0'

The version of Storage Analytics to configure.

class azure.storage.queue.QueueAnalyticsLogging(**kwargs: Any)[source]

Azure Analytics Logging settings.

All required parameters must be populated in order to send to Azure.

Keyword Arguments:
  • version (str) – Required. The version of Storage Analytics to configure.

  • delete (bool) – Required. Indicates whether all delete requests should be logged.

  • read (bool) – Required. Indicates whether all read requests should be logged.

  • write (bool) – Required. Indicates whether all write requests should be logged.

  • retention_policy (RetentionPolicy) – The retention policy for the metrics.

  • version – The version of Storage Analytics to configure. Required.

  • delete – Indicates whether all delete requests should be logged. Required.

  • read – Indicates whether all read requests should be logged. Required.

  • write – Indicates whether all write requests should be logged. Required.

  • retention_policy – the retention policy. Required.

as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

Return a dict that can be serialized using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

classmethod deserialize(data: Any, content_type: str | None = None) ModelType

Parse a str using the RestAPI syntax and return a model.

Parameters:
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) ModelType

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters:
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod is_xml_model() bool
serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

Return the JSON that would be sent to server from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns:

A dict JSON compatible object

Return type:

dict

delete: bool = False

Indicates whether all delete requests should be logged.

read: bool = False

Indicates whether all read requests should be logged.

retention_policy: RetentionPolicy = <azure.storage.queue._models.RetentionPolicy object>

The retention policy for the metrics.

version: str = '1.0'

The version of Storage Analytics to configure.

write: bool = False

Indicates whether all write requests should be logged.

class azure.storage.queue.QueueClient(account_url: str, queue_name: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any)[source]

A client to interact with a specific Queue.

For more optional configuration, please click here.

Parameters:
  • account_url (str) – The URL to the storage account. In order to create a client given the full URI to the queue, use the from_queue_url() classmethod.

  • queue_name (str) – The name of the queue.

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:
  • api_version (str) – The Storage API version to use for requests. Default value is the most recent service version that is compatible with the current SDK. Setting to an older version may result in reduced feature compatibility.

  • secondary_hostname (str) – The hostname of the secondary endpoint.

  • message_encode_policy – The encoding policy to use on outgoing messages. Default is not to encode messages. Other options include TextBase64EncodePolicy, BinaryBase64EncodePolicy or None.

  • message_decode_policy – The decoding policy to use on incoming messages. Default value is not to decode messages. Other options include TextBase64DecodePolicy, BinaryBase64DecodePolicy or None.

  • audience (str) – The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://<account>.queue.core.windows.net.

Example:

Create the queue client with url and credential.
token_auth_queue = QueueClient.from_queue_url(
    queue_url=queue.url,
    credential=sas_token
)
clear_messages(**kwargs: Any) None[source]

Deletes all messages from the specified queue.

Keyword Arguments:

timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Example:

Clears all messages.
queue.clear_messages()
close()

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

create_queue(*, metadata: Dict[str, str] | None = None, **kwargs: Any) None[source]

Creates a new queue in the storage account.

If a queue with the same name already exists, the operation fails with a ResourceExistsError.

Keyword Arguments:
Returns:

None or the result of cls(response)

Return type:

None

Raises:

StorageErrorException

Example:

Create a queue.
queue.create_queue()
delete_message(message: str | QueueMessage, pop_receipt: str | None = None, **kwargs: Any) None[source]

Deletes the specified message.

Normally after a client retrieves a message with the receive messages operation, the client is expected to process and delete the message. To delete the message, you must have the message object itself, or two items of data: id and pop_receipt. The id is returned from the previous receive_messages operation. The pop_receipt is returned from the most recent receive_messages() or update_message() operation. In order for the delete_message operation to succeed, the pop_receipt specified on the request must match the pop_receipt returned from the receive_messages() or update_message() operation.

Parameters:
Keyword Arguments:

timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Example:

Delete a message.
# Get the message at the front of the queue
msg = next(queue.receive_messages())

# Delete the specified message
queue.delete_message(msg)
delete_queue(**kwargs: Any) None[source]

Deletes the specified queue and any messages it contains.

When a queue is successfully deleted, it is immediately marked for deletion and is no longer accessible to clients. The queue is later removed from the Queue service during garbage collection.

Note that deleting a queue is likely to take at least 40 seconds to complete. If an operation is attempted against the queue while it was being deleted, an HttpResponseError will be thrown.

Keyword Arguments:

timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Return type:

None

Example:

Delete a queue.
queue.delete_queue()
classmethod from_connection_string(conn_str: str, queue_name: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) Self[source]

Create QueueClient from a Connection String.

Parameters:
  • conn_str (str) – A connection string to an Azure Storage account.

  • queue_name (str) – The queue name.

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token, or the connection string already has shared access key values. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. Credentials provided here will take precedence over those in the connection string. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:

audience (str) – The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://<account>.queue.core.windows.net.

Returns:

A queue client.

Return type:

QueueClient

Example:

Create the queue client from connection string.
from azure.storage.queue import QueueClient
queue = QueueClient.from_connection_string(self.connection_string, "myqueue1")
classmethod from_queue_url(queue_url: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) Self[source]

A client to interact with a specific Queue.

Parameters:
  • queue_url (str) – The full URI to the queue, including SAS token if used.

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:

audience (str) – The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://<account>.queue.core.windows.net.

Returns:

A queue client.

Return type:

QueueClient

get_queue_access_policy(**kwargs: Any) Dict[str, AccessPolicy][source]

Returns details about any stored access policies specified on the queue that may be used with Shared Access Signatures.

Keyword Arguments:

timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A dictionary of access policies associated with the queue.

Return type:

Dict[str, AccessPolicy]

get_queue_properties(**kwargs: Any) QueueProperties[source]

Returns all user-defined metadata for the specified queue.

The data returned does not include the queue’s list of messages.

Keyword Arguments:

timeout (int) – The timeout parameter is expressed in seconds.

Returns:

User-defined metadata for the queue.

Return type:

QueueProperties

Example:

Get the properties on the queue.
properties = queue.get_queue_properties().metadata
peek_messages(max_messages: int | None = None, **kwargs: Any) List[QueueMessage][source]

Retrieves one or more messages from the front of the queue, but does not alter the visibility of the message.

Only messages that are visible may be retrieved. When a message is retrieved for the first time with a call to receive_messages(), its dequeue_count property is set to 1. If it is not deleted and is subsequently retrieved again, the dequeue_count property is incremented. The client may use this value to determine how many times a message has been retrieved. Note that a call to peek_messages does not increment the value of dequeue_count, but returns this value for the client to read.

If the key-encryption-key or resolver field is set on the local service object, the messages will be decrypted before being returned.

Parameters:

max_messages (int) – A nonzero integer value that specifies the number of messages to peek from the queue, up to a maximum of 32. By default, a single message is peeked from the queue with this operation.

Keyword Arguments:

timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A list of QueueMessage objects. Note that next_visible_on and pop_receipt will not be populated as peek does not pop the message and can only retrieve already visible messages.

Return type:

list[QueueMessage]

Example:

Peek messages.
# Peek at one message at the front of the queue
msg = queue.peek_messages()

# Peek at the last 5 messages
messages = queue.peek_messages(max_messages=5)

# Print the last 5 messages
for message in messages:
    print(message.content)
receive_message(*, visibility_timeout: int | None = None, **kwargs: Any) QueueMessage | None[source]

Removes one message from the front of the queue.

When the message is retrieved from the queue, the response includes the message content and a pop_receipt value, which is required to delete the message. The message is not automatically deleted from the queue, but after it has been retrieved, it is not visible to other clients for the time interval specified by the visibility_timeout parameter.

If the key-encryption-key or resolver field is set on the local service object, the message will be decrypted before being returned.

Keyword Arguments:
  • visibility_timeout (int) – If not specified, the default value is 30. Specifies the new visibility timeout value, in seconds, relative to server time. The value must be larger than or equal to 1, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibility_timeout should be set to a value smaller than the time-to-live value.

  • timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

Returns a message from the Queue or None if the Queue is empty.

Return type:

QueueMessage or None

Example:

Receive one message from the queue.
# Pop two messages from the front of the queue
message1 = queue.receive_message()
message2 = queue.receive_message()
# We should see message 3 if we peek
message3 = queue.peek_messages()[0]

if not message1 or not message2 or not message3:
    raise ValueError("One of the messages are None.")

print(message1.content)
print(message2.content)
print(message3.content)
receive_messages(*, messages_per_page: int | None = None, visibility_timeout: int | None = None, max_messages: int | None = None, **kwargs: Any) ItemPaged[QueueMessage][source]

Removes one or more messages from the front of the queue.

When a message is retrieved from the queue, the response includes the message content and a pop_receipt value, which is required to delete the message. The message is not automatically deleted from the queue, but after it has been retrieved, it is not visible to other clients for the time interval specified by the visibility_timeout parameter. The iterator will continuously fetch messages until the queue is empty or max_messages is reached (if max_messages is set).

If the key-encryption-key or resolver field is set on the local service object, the messages will be decrypted before being returned.

Keyword Arguments:

messages_per_page (int) – 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. by_page() can be used to provide a page iterator on the AsyncItemPaged if messages_per_page is set. next() can be used to get the next page.

Example:

List pages and corresponding messages from the queue.
# Store two messages in each page
message_batches = queue.receive_messages(messages_per_page=2).by_page()

# Iterate through the page lists
print(list(next(message_batches)))
print(list(next(message_batches)))

# There are two iterations in the last page as well.
last_page = next(message_batches)
for message in last_page:
    print(message)
Keyword Arguments:
  • visibility_timeout (int) – If not specified, the default value is 30. Specifies the new visibility timeout value, in seconds, relative to server time. The value must be larger than or equal to 1, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibility_timeout should be set to a value smaller than the time-to-live value.

  • max_messages (int) – An integer that specifies the maximum number of messages to retrieve from the queue.

  • timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

Returns a message iterator of dict-like Message objects.

Return type:

ItemPaged[QueueMessage]

Example:

Receive messages from the queue.
# Receive messages one-by-one
messages = queue.receive_messages()
for msg in messages:
    print(msg.content)

# Receive messages by batch
messages = queue.receive_messages(messages_per_page=5)
for msg_batch in messages.by_page():
    for msg in msg_batch:
        print(msg.content)
        queue.delete_message(msg)
send_message(content: object | None, *, visibility_timeout: int | None = None, time_to_live: int | None = None, **kwargs: Any) QueueMessage[source]

Adds a new message to the back of the message queue.

The visibility timeout specifies the time that the message will be invisible. After the timeout expires, the message will become visible. If a visibility timeout is not specified, the default value of 0 is used.

The message time-to-live specifies how long a message will remain in the queue. The message will be deleted from the queue when the time-to-live period expires.

If the key-encryption-key field is set on the local service object, this method will encrypt the content before uploading.

Parameters:

content (Optional[object]) – Message content. Allowed type is determined by the encode_function set on the service. Default is str. The encoded message can be up to 64KB in size.

Keyword Arguments:
  • visibility_timeout (int) – If not specified, the default value is 0. Specifies the new visibility timeout value, in seconds, relative to server time. The 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. visibility_timeout should be set to a value smaller than the time-to-live value.

  • time_to_live (int) – Specifies the time-to-live interval for the message, in seconds. The time-to-live may be any positive number or -1 for infinity. If this parameter is omitted, the default time-to-live is 7 days.

  • timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A QueueMessage object. This object is also populated with the content although it is not returned from the service.

Return type:

QueueMessage

Example:

Send messages.
queue.send_message("message1")
queue.send_message("message2", visibility_timeout=30)  # wait 30s before becoming visible
queue.send_message("message3")
queue.send_message("message4")
queue.send_message("message5")
set_queue_access_policy(signed_identifiers: Dict[str, AccessPolicy], **kwargs: Any) None[source]

Sets stored access policies for the queue that may be used with Shared Access Signatures.

When you set permissions for a queue, the existing permissions are replaced. To update the queue’s permissions, call get_queue_access_policy() to fetch all access policies associated with the queue, modify the access policy that you wish to change, and then call this function with the complete set of data to perform the update.

When you establish a stored access policy on a queue, it may take up to 30 seconds to take effect. During this interval, a shared access signature that is associated with the stored access policy will throw an HttpResponseError until the access policy becomes active.

Parameters:

signed_identifiers (Dict[str, AccessPolicy]) – SignedIdentifier access policies to associate with the queue. This may contain up to 5 elements. An empty dict will clear the access policies set on the service.

Keyword Arguments:

timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Example:

Set an access policy on the queue.
# Create an access policy
from azure.storage.queue import AccessPolicy, QueueSasPermissions
access_policy = AccessPolicy()
access_policy.start = datetime.utcnow() - timedelta(hours=1)
access_policy.expiry = datetime.utcnow() + timedelta(hours=1)
access_policy.permission = QueueSasPermissions(read=True)
identifiers = {'my-access-policy-id': access_policy}

# Set the access policy
queue.set_queue_access_policy(identifiers)
set_queue_metadata(metadata: Dict[str, str] | None = None, **kwargs: Any) Dict[str, Any][source]

Sets user-defined metadata on the specified queue.

Metadata is associated with the queue as name-value pairs.

Parameters:

metadata (Optional[Dict[str, str]]) – A dict containing name-value pairs to associate with the queue as metadata.

Keyword Arguments:

timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A dictionary of response headers.

Return type:

Dict[str, Any]

Example:

Set metadata on the queue.
metadata = {'foo': 'val1', 'bar': 'val2', 'baz': 'val3'}
queue.set_queue_metadata(metadata=metadata)
update_message(message: str | QueueMessage, pop_receipt: str | None = None, content: object | None = None, *, visibility_timeout: int | None = None, **kwargs: Any) QueueMessage[source]

Updates the visibility timeout of a message. You can also use this operation to update the contents of a message.

This operation can be used to continually extend the invisibility of a queue message. This functionality can be useful if you want a worker role to “lease” a queue message. For example, if a worker role calls receive_messages() and recognizes that it needs more time to process a message, it can continually extend the message’s invisibility until it is processed. If the worker role were to fail during processing, eventually the message would become visible again and another worker role could process it.

If the key-encryption-key field is set on the local service object, this method will encrypt the content before uploading.

Parameters:
  • message (str or QueueMessage) – The message object or id identifying the message to update.

  • pop_receipt (str) – A valid pop receipt value returned from an earlier call to the receive_messages() or update_message() operation.

  • content (Optional[object]) – Message content. Allowed type is determined by the encode_function set on the service. Default is str.

Keyword Arguments:
  • visibility_timeout (int) – 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. A message can be updated until it has been deleted or has expired. The message object or message id identifying the message to update.

  • timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns:

A QueueMessage object. For convenience, this object is also populated with the content, although it is not returned by the service.

Return type:

QueueMessage

Example:

Update a message.
# Send a message
queue.send_message("update me")

# Receive the message
messages = queue.receive_messages()

# Update the message
list_result = next(messages)
message = queue.update_message(
    list_result.id,
    pop_receipt=list_result.pop_receipt,
    visibility_timeout=0,
    content="updated")
property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

property secondary_endpoint

The full secondary endpoint URL if configured.

If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

Return type:

str

Raises:

ValueError

property secondary_hostname

The hostname of the secondary endpoint.

If not available this will be None. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

Return type:

Optional[str]

property url

The full endpoint URL to this entity, including SAS token if used.

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode(). :returns: The full endpoint URL to this entity, including SAS token if used. :rtype: str

class azure.storage.queue.QueueMessage(content: Any | None = None, **kwargs: Any)[source]

Represents a queue message.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
content: Any

The message content. Type is determined by the decode_function set on the service. Default is str.

dequeue_count: int | None

Begins with a value of 1 the first time the message is received. This value is incremented each time the message is subsequently received.

expires_on: datetime | None

A UTC date value representing the time the message expires.

id: str

A GUID value assigned to the message by the Queue service that identifies the message in the queue. This value may be used together with the value of pop_receipt to delete a message from the queue after it has been retrieved with the receive messages operation.

inserted_on: datetime | None

A UTC date value representing the time the messages was inserted.

next_visible_on: datetime | None

A UTC date value representing the time the message will next be visible. Only returned by receive messages operations. Set to None for peek messages.

pop_receipt: str | None

A receipt str which can be used together with the message_id element to delete a message from the queue after it has been retrieved with the receive messages operation. Only returned by receive messages operations. Set to None for peek messages.

class azure.storage.queue.QueueProperties(**kwargs: Any)[source]

Queue Properties.

Keyword Arguments:

metadata (Optional[Dict[str, str]]) – A dict containing name-value pairs associated with the queue as metadata. This var is set to None unless the include=metadata param was included for the list queues operation.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
approximate_message_count: int | None

The approximate number of messages contained in the queue.

metadata: Dict[str, str] | None

A dict containing name-value pairs associated with the queue as metadata.

name: str

The name of the queue.

class azure.storage.queue.QueueSasPermissions(read: bool = False, add: bool = False, update: bool = False, process: bool = False)[source]

QueueSasPermissions class to be used with the generate_queue_sas() function and for the AccessPolicies used with set_queue_access_policy().

Parameters:
  • read (bool) – Read metadata and properties, including message count. Peek at messages.

  • add (bool) – Add messages to the queue.

  • update (bool) – Update messages in the queue. Note: Use the Process permission with Update so you can first get the message you want to update.

  • process (bool) – Get and delete messages from the queue.

classmethod from_string(permission: str) Self[source]

Create a QueueSasPermissions from a string.

To specify read, add, update, or process permissions you need only to include the first letter of the word in the string. E.g. For read and update permissions, you would provide a string “ru”.

Parameters:

permission (str) – The string which dictates the read, add, update, or process permissions.

Returns:

A QueueSasPermissions object

Return type:

QueueSasPermissions

add: bool = False

Add messages to the queue.

process: bool = False

Get and delete messages from the queue.

read: bool = False

Read metadata and properties, including message count.

update: bool = False

Update messages in the queue.

class azure.storage.queue.QueueServiceClient(account_url: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any)[source]

A client to interact with the Queue Service at the account level.

This client provides operations to retrieve and configure the account properties as well as list, create and delete queues within the account. For operations relating to a specific queue, a client for this entity can be retrieved using the get_queue_client() function.

For more optional configuration, please click here.

Parameters:
  • account_url (str) – The URL to the queue service endpoint. Any other entities included in the URL path (e.g. queue) will be discarded. This URL can be optionally authenticated with a SAS token.

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential - except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:
  • api_version (str) – The Storage API version to use for requests. Default value is the most recent service version that is compatible with the current SDK. Setting to an older version may result in reduced feature compatibility.

  • secondary_hostname (str) – The hostname of the secondary endpoint.

  • audience (str) – The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://<account>.queue.core.windows.net.

Example:

Creating the QueueServiceClient with an account url and credential.
from azure.storage.queue import QueueServiceClient
queue_service = QueueServiceClient(account_url=self.account_url, credential=self.access_key)
Creating the QueueServiceClient with Default Azure Identity credentials.
# Get a token credential for authentication
from azure.identity import DefaultAzureCredential
token_credential = DefaultAzureCredential()

# Instantiate a QueueServiceClient using a token credential
from azure.storage.queue import QueueServiceClient
queue_service = QueueServiceClient(account_url=self.account_url, credential=token_credential)
close()

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

create_queue(name: str, metadata: Dict[str, str] | None = None, **kwargs: Any) QueueClient[source]

Creates a new queue under the specified account.

If a queue with the same name already exists, the operation fails. Returns a client with which to interact with the newly created queue.

Parameters:
  • name (str) – The name of the queue to create.

  • metadata (Dict[str, str]) – A dict with name_value pairs to associate with the queue as metadata. Example: {‘Category’: ‘test’}

Keyword Arguments:

timeout (int) – The timeout parameter is expressed in seconds.

Returns:

A QueueClient for the newly created Queue.

Return type:

QueueClient

Example:

Create a queue in the service.
queue_service.create_queue("myqueue1")
delete_queue(queue: QueueProperties | str, **kwargs: Any) None[source]

Deletes the specified queue and any messages it contains.

When a queue is successfully deleted, it is immediately marked for deletion and is no longer accessible to clients. The queue is later removed from the Queue service during garbage collection.

Note that deleting a queue is likely to take at least 40 seconds to complete. If an operation is attempted against the queue while it was being deleted, an HttpResponseError will be thrown.

Parameters:

queue (str or QueueProperties) – The queue to delete. This can either be the name of the queue, or an instance of QueueProperties.

Keyword Arguments:

timeout (int) – The timeout parameter is expressed in seconds.

Return type:

None

Example:

Delete a queue in the service.
queue_service.delete_queue("myqueue1")
classmethod from_connection_string(conn_str: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) Self[source]

Create QueueServiceClient from a Connection String.

Parameters:
  • conn_str (str) – A connection string to an Azure Storage account.

  • credential (AzureNamedKeyCredential or AzureSasCredential or TokenCredential or str or dict[str, str] or None) – The credentials with which to authenticate. This is optional if the account URL already has a SAS token, or the connection string already has shared access key values. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. Credentials provided here will take precedence over those in the connection string. If using an instance of AzureNamedKeyCredential, “name” should be the storage account name, and “key” should be the storage account key.

Keyword Arguments:

audience (str) – The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://<account>.queue.core.windows.net.

Returns:

A Queue service client.

Return type:

QueueClient

Example:

Creating the QueueServiceClient with a connection string.
from azure.storage.queue import QueueServiceClient
queue_service = QueueServiceClient.from_connection_string(conn_str=self.connection_string)
get_queue_client(queue: QueueProperties | str, **kwargs: Any) QueueClient[source]

Get a client to interact with the specified queue.

The queue need not already exist.

Parameters:

queue (str or QueueProperties) – The queue. This can either be the name of the queue, or an instance of QueueProperties.

Returns:

A QueueClient object.

Return type:

QueueClient

Example:

Get the queue client.
# Get the queue client to interact with a specific queue
queue = queue_service.get_queue_client(queue="myqueue2")
get_service_properties(**kwargs: Any) Dict[str, Any][source]

Gets the properties of a storage account’s Queue service, including Azure Storage Analytics.

Keyword Arguments:

timeout (int) – The timeout parameter is expressed in seconds.

Returns:

An object containing queue service properties such as analytics logging, hour/minute metrics, cors rules, etc.

Return type:

Dict[str, Any]

Example:

Getting queue service properties.
properties = queue_service.get_service_properties()
get_service_stats(**kwargs: Any) Dict[str, Any][source]

Retrieves statistics related to replication for the Queue service.

It is only available when read-access geo-redundant replication is enabled for the storage account.

With geo-redundant replication, Azure Storage maintains your data durable in two locations. In both locations, Azure Storage constantly maintains multiple healthy replicas of your data. The location where you read, create, update, or delete data is the primary storage account location. The primary location exists in the region you choose at the time you create an account via the Azure Management Azure classic portal, for example, North Central US. The location to which your data is replicated is the secondary location. The secondary location is automatically determined based on the location of the primary; it is in a second data center that resides in the same region as the primary location. Read-only access is available from the secondary location, if read-access geo-redundant replication is enabled for your storage account.

Keyword Arguments:

timeout (int) – The timeout parameter is expressed in seconds.

Returns:

The queue service stats.

Return type:

Dict[str, Any]

list_queues(name_starts_with: str | None = None, include_metadata: bool | None = False, **kwargs: Any) ItemPaged[QueueProperties][source]

Returns a generator to list the queues under the specified account.

The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been returned.

Parameters:
  • name_starts_with (str) – Filters the results to return only queues whose names begin with the specified prefix.

  • include_metadata (bool) – Specifies that queue metadata be returned in the response.

Keyword Arguments:
  • results_per_page (int) – The maximum number of queue names to retrieve per API call. If the request does not specify the server will return up to 5,000 items.

  • timeout (int) – Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here. This function may make multiple calls to the service in which case the timeout value specified will be applied to each individual call.

Returns:

An iterable (auto-paging) of QueueProperties.

Return type:

ItemPaged[QueueProperties]

Example:

List queues in the service.
# List all the queues in the service
list_queues = queue_service.list_queues()
for queue in list_queues:
    print(queue)

# List the queues in the service that start with the name "my"
list_my_queues = queue_service.list_queues(name_starts_with="my")
for queue in list_my_queues:
    print(queue)
set_service_properties(analytics_logging: QueueAnalyticsLogging | None = None, hour_metrics: Metrics | None = None, minute_metrics: Metrics | None = None, cors: List[CorsRule] | None = None, **kwargs: Any) None[source]

Sets the properties of a storage account’s Queue service, including Azure Storage Analytics.

If an element (e.g. analytics_logging) is left as None, the existing settings on the service for that functionality are preserved.

Parameters:
  • analytics_logging (QueueAnalyticsLogging) – Groups the Azure Analytics Logging settings.

  • hour_metrics (Metrics) – The hour metrics settings provide a summary of request statistics grouped by API in hourly aggregates for queues.

  • minute_metrics (Metrics) – The minute metrics settings provide request statistics for each minute for queues.

  • cors (Optional[List[CorsRule]]) – You can include up to five CorsRule elements in the list. If an empty list is specified, all CORS rules will be deleted, and CORS will be disabled for the service.

Keyword Arguments:

timeout (int) – The timeout parameter is expressed in seconds.

Example:

Setting queue service properties.
# Create service properties
from azure.storage.queue import QueueAnalyticsLogging, Metrics, CorsRule, RetentionPolicy

# Create logging settings
logging = QueueAnalyticsLogging(read=True, write=True, delete=True, retention_policy=RetentionPolicy(enabled=True, days=5))

# Create metrics for requests statistics
hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5))
minute_metrics = Metrics(enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5))

# Create CORS rules
cors_rule1 = CorsRule(['www.xyz.com'], ['GET'])
allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"]
allowed_methods = ['GET', 'PUT']
max_age_in_seconds = 500
exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"]
allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"]
cors_rule2 = CorsRule(
    allowed_origins,
    allowed_methods,
    max_age_in_seconds=max_age_in_seconds,
    exposed_headers=exposed_headers,
    allowed_headers=allowed_headers
)

cors = [cors_rule1, cors_rule2]

# Set the service properties
queue_service.set_service_properties(logging, hour_metrics, minute_metrics, cors)
property api_version

The version of the Storage API used for requests.

Return type:

str

property location_mode

The location mode that the client is currently using.

By default this will be “primary”. Options include “primary” and “secondary”.

Return type:

str

property primary_endpoint

The full primary endpoint URL.

Return type:

str

property primary_hostname

The hostname of the primary endpoint.

Return type:

str

property secondary_endpoint

The full secondary endpoint URL if configured.

If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

Return type:

str

Raises:

ValueError

property secondary_hostname

The hostname of the secondary endpoint.

If not available this will be None. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

Return type:

Optional[str]

property url

The full endpoint URL to this entity, including SAS token if used.

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode(). :returns: The full endpoint URL to this entity, including SAS token if used. :rtype: str

class azure.storage.queue.ResourceTypes(service: bool = False, container: bool = False, object: bool = False)[source]

Specifies the resource types that are accessible with the account SAS.

Parameters:
  • service (bool) – Access to service-level APIs (e.g., Get/Set Service Properties, Get Service Stats, List Containers/Queues/Shares)

  • container (bool) – Access to container-level APIs (e.g., Create/Delete Container, Create/Delete Queue, Create/Delete Share, List Blobs/Files and Directories)

  • object (bool) – Access to object-level APIs for blobs, queue messages, and files(e.g. Put Blob, Query Entity, Get Messages, Create File, etc.)

classmethod from_string(string)[source]

Create a ResourceTypes from a string.

To specify service, container, or object you need only to include the first letter of the word in the string. E.g. service and container, you would provide a string “sc”.

Parameters:

string (str) – Specify service, container, or object in in the string with the first letter of the word.

Returns:

A ResourceTypes object

Return type:

ResourceTypes

container: bool = False
object: bool = False
service: bool = False
class azure.storage.queue.RetentionPolicy(enabled: bool = False, days: int | None = None)[source]

The retention policy which determines how long the associated data should persist.

All required parameters must be populated in order to send to Azure.

Parameters:
  • enabled (bool) – Required. Indicates whether a retention policy is enabled for the storage service.

  • days (int) – 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.

Keyword Arguments:
  • enabled (bool) – Indicates whether a retention policy is enabled for the storage service. Required.

  • days (int) – 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.

as_dict(keep_readonly: bool = True, key_transformer: ~typing.Callable[[str, ~typing.Dict[str, ~typing.Any], ~typing.Any], ~typing.Any] = <function attribute_transformer>, **kwargs: ~typing.Any) MutableMapping[str, Any]

Return a dict that can be serialized using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

key_transformer (function) – A key transformer function.

Returns:

A dict JSON compatible object

Return type:

dict

classmethod deserialize(data: Any, content_type: str | None = None) ModelType

Parse a str using the RestAPI syntax and return a model.

Parameters:
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod enable_additional_properties_sending() None
classmethod from_dict(data: Any, key_extractors: Callable[[str, Dict[str, Any], Any], Any] | None = None, content_type: str | None = None) ModelType

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters:
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns:

An instance of this model

Raises:

DeserializationError if something went wrong

classmethod is_xml_model() bool
serialize(keep_readonly: bool = False, **kwargs: Any) MutableMapping[str, Any]

Return the JSON that would be sent to server from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters:

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns:

A dict JSON compatible object

Return type:

dict

days: int | None = None

Indicates the number of days that metrics or logging or soft-deleted data should be retained.

enabled: bool = False

Indicates whether a retention policy is enabled for the storage service.

class azure.storage.queue.Services(*, blob: bool = False, queue: bool = False, fileshare: bool = False)[source]

Specifies the services accessible with the account SAS.

Keyword Arguments:
  • blob (bool) – Access for the ~azure.storage.blob.BlobServiceClient. Default is False.

  • queue (bool) – Access for the ~azure.storage.queue.QueueServiceClient. Default is False.

  • fileshare (bool) – Access for the ~azure.storage.fileshare.ShareServiceClient. Default is False.

classmethod from_string(string)[source]

Create Services from a string.

To specify blob, queue, or file you need only to include the first letter of the word in the string. E.g. for blob and queue you would provide a string “bq”.

Parameters:

string (str) – Specify blob, queue, or file in in the string with the first letter of the word.

Returns:

A Services object

Return type:

Services

class azure.storage.queue.StorageErrorCode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

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_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_SYSTEM_ALREADY_EXISTS = 'FilesystemAlreadyExists'
FILE_SYSTEM_BEING_DELETED = 'FilesystemBeingDeleted'
FILE_SYSTEM_NOT_FOUND = 'FilesystemNotFound'
INCREMENTAL_COPY_BLOB_MISMATCH = 'IncrementalCopyBlobMismatch'
INCREMENTAL_COPY_OF_EARLIER_VERSION_SNAPSHOT_NOT_ALLOWED = 'IncrementalCopyOfEarlierVersionSnapshotNotAllowed'
INCREMENTAL_COPY_OF_ERALIER_VERSION_SNAPSHOT_NOT_ALLOWED = 'IncrementalCopyOfEarlierVersionSnapshotNotAllowed'

Please use INCREMENTAL_COPY_OF_EARLIER_VERSION_SNAPSHOT_NOT_ALLOWED instead.

Type:

Deprecated

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_OPERATION_NOT_SUPPORTED = 'ShareSnapshotOperationNotSupported'
SHARING_VIOLATION = 'SharingViolation'
SNAPHOT_OPERATION_RATE_EXCEEDED = 'SnapshotOperationRateExceeded'

Please use SNAPSHOT_OPERATION_RATE_EXCEEDED instead.

Type:

Deprecated

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'
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[source]

Message decoding policy for base 64-encoded messages into text.

Decodes base64-encoded messages to text (unicode). If the input content is not valid base 64, a DecodeError will be raised. Message data must support UTF-8.

configure(require_encryption: bool, key_encryption_key: KeyEncryptionKey | None, resolver: Callable[[str], KeyEncryptionKey] | None) None
decode(content: str, response: PipelineResponse) str[source]
key_encryption_key: KeyEncryptionKey | None = None

The user-provided key-encryption-key.

require_encryption: bool = False

Indicates whether encryption is required or not.

resolver: Callable[[str], KeyEncryptionKey] | None = None

The user-provided key resolver.

class azure.storage.queue.TextBase64EncodePolicy[source]

Base 64 message encoding policy for text messages.

Encodes text (unicode) messages to base 64. If the input content is not text, a TypeError will be raised. Input text must support UTF-8.

configure(require_encryption: bool, key_encryption_key: KeyEncryptionKey | None, resolver: Callable[[str], KeyEncryptionKey] | None, encryption_version: str = '1.0') None
encode(content: str) str[source]
encryption_version: str

Indicates the version of encryption being used.

key_encryption_key: KeyEncryptionKey | None

The user-provided key-encryption-key.

require_encryption: bool

Indicates whether encryption is required or not.

resolver: Callable[[str], KeyEncryptionKey] | None

The user-provided key resolver.

azure.storage.queue.generate_account_sas(account_name: str, account_key: str, resource_types: ResourceTypes | str, permission: AccountSasPermissions | str, expiry: datetime | str, start: datetime | str | None = None, ip: str | None = None, *, services: ~azure.storage.queue._shared.models.Services | str = <azure.storage.queue._shared.models.Services object>, sts_hook: ~typing.Callable[[str], None] | None = None, **kwargs: ~typing.Any) str[source]

Generates a shared access signature for the queue service.

Use the returned signature with the credential parameter of any Queue Service.

Parameters:
  • account_name (str) – The storage account name used to generate the shared access signature.

  • account_key (str) – The account key, also called shared key or access key, to generate the shared access signature.

  • resource_types (ResourceTypes) – Specifies the resource types that are accessible with the account SAS.

  • permission (AccountSasPermissions or str) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions.

  • expiry (datetime or str) – The time at which the shared access signature becomes invalid. The provided datetime will always be interpreted as UTC.

  • start (datetime or str) – The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. The provided datetime will always be interpreted as UTC.

  • ip (str) – Specifies an IP address or a range of IP addresses from which to accept requests. If the IP address from which the request originates does not match the IP address or address range specified on the SAS token, the request is not authenticated. For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS restricts the request to those IP addresses.

Keyword Arguments:
  • services (Union[Services, str]) – Specifies the services that the Shared Access Signature (sas) token will be able to be utilized with. Will default to only this package (i.e. queue) if not provided.

  • protocol (str) – Specifies the protocol permitted for a request made. The default value is https.

  • sts_hook (Optional[Callable[[str], None]]) – For debugging purposes only. If provided, the hook is called with the string to sign that was used to generate the SAS.

Returns:

A Shared Access Signature (sas) token.

Return type:

str

azure.storage.queue.generate_queue_sas(account_name: str, queue_name: str, account_key: str, permission: QueueSasPermissions | str | None = None, expiry: datetime | str | None = None, start: datetime | str | None = None, policy_id: str | None = None, ip: str | None = None, *, sts_hook: Callable[[str], None] | None = None, **kwargs: Any) str[source]

Generates a shared access signature for a queue.

Use the returned signature with the credential parameter of any Queue Service.

Parameters:
  • account_name (str) – The storage account name used to generate the shared access signature.

  • queue_name (str) – The name of the queue.

  • account_key (str) – The account key, also called shared key or access key, to generate the shared access signature.

  • permission (QueueSasPermissions or str) – The permissions associated with the shared access signature. The user is restricted to operations allowed by the permissions. Required unless a policy_id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy.

  • expiry (datetime or str) – The time at which the shared access signature becomes invalid. Required unless a policy_id is given referencing a stored access policy which contains this field. This field must be omitted if it has been specified in an associated stored access policy. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be UTC.

  • start (datetime or str) – The time at which the shared access signature becomes valid. If omitted, start time for this call is assumed to be the time when the storage service receives the request. The provided datetime will always be interpreted as UTC.

  • policy_id (str) – A unique value up to 64 characters in length that correlates to a stored access policy. To create a stored access policy, use set_queue_access_policy().

  • ip (str) – Specifies an IP address or a range of IP addresses from which to accept requests. If the IP address from which the request originates does not match the IP address or address range specified on the SAS token, the request is not authenticated. For example, specifying sip=’168.1.5.65’ or sip=’168.1.5.60-168.1.5.70’ on the SAS restricts the request to those IP addresses.

Keyword Arguments:
  • protocol (str) – Specifies the protocol permitted for a request made. The default value is https.

  • sts_hook (Optional[Callable[[str], None]]) – For debugging purposes only. If provided, the hook is called with the string to sign that was used to generate the SAS.

Returns:

A Shared Access Signature (sas) token.

Return type:

str

Example:

Generate a sas token.
from azure.storage.queue import generate_queue_sas
sas_token = generate_queue_sas(
    queue.account_name,
    queue.queue_name,
    queue.credential.account_key,
    policy_id='my-access-policy-id'
)

Subpackages