azure.storage.queue package

class azure.storage.queue.AccessPolicy(permission=None, expiry=None, start=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 (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 (datetime or 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 (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. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be 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=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify 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, content_type=None)

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()
classmethod from_dict(data, key_extractors=None, content_type=None)

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()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure 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

class azure.storage.queue.AccountSasPermissions(read=False, write=False, delete=False, list=False, add=False, create=False, update=False, process=False, delete_previous_version=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

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, key_encryption_key, resolver)
decode(content, response)[source]
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, key_encryption_key, resolver, encryption_version='1.0')
encode(content)[source]
class azure.storage.queue.CorsRule(allowed_origins, allowed_methods, **kwargs)[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 of 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 of 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=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify 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, content_type=None)

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()
classmethod from_dict(data, key_extractors=None, content_type=None)

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()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure 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

class azure.storage.queue.ExponentialRetry(initial_backoff=15, increment_base=3, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs)[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.

  • max_attempts (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)
get_backoff_time(settings)[source]

Calculates how long to sleep before retrying.

Returns

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

Return type

int or None

increment(settings, request, response=None, error=None)

Increment the retry counters.

Parameters
  • response – A pipeline response object.

  • error – An error encountered during the request, or None if the response was received successfully.

Returns

Whether the retry attempts are exhausted.

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)
class azure.storage.queue.LinearRetry(backoff=15, retry_total=3, retry_to_secondary=False, random_jitter_range=3, **kwargs)[source]

Linear retry.

Constructs a Linear retry object.

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

  • max_attempts (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)
get_backoff_time(settings)[source]

Calculates how long to sleep before retrying.

Returns

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

Return type

int or None

increment(settings, request, response=None, error=None)

Increment the retry counters.

Parameters
  • response – A pipeline response object.

  • error – An error encountered during the request, or None if the response was received successfully.

Returns

Whether the retry attempts are exhausted.

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)
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)[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_ap_is (bool) – Indicates whether metrics should generate summary statistics for called API operations.

  • retention_policy (RetentionPolicy) – Required. 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 (bool) – Indicates whether metrics should generate summary statistics for called API operations.

  • retention_policy – the retention policy.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify 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, content_type=None)

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()
classmethod from_dict(data, key_extractors=None, content_type=None)

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()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure 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

class azure.storage.queue.QueueAnalyticsLogging(**kwargs)[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) – Required. 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=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify 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, content_type=None)

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()
classmethod from_dict(data, key_extractors=None, content_type=None)

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()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure 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

class azure.storage.queue.QueueClient(account_url: str, queue_name: str, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = 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 – 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.

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) – The server timeout, expressed in seconds.

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(**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
  • metadata (dict(str,str)) – A dict containing name-value pairs to associate with the queue as metadata. Note that metadata names preserve the case with which they were created, but are case-insensitive when set or read.

  • timeout (int) – The server timeout, expressed in seconds.

Returns

None or the result of cls(response)

Return type

None

Raises

StorageErrorException

Example:

Create a queue.
queue.create_queue()
delete_message(message: Any, pop_receipt: Optional[str] = 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) – The server timeout, expressed in seconds.

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) – The server timeout, expressed in seconds.

Return type

None

Example:

Delete a queue.
queue.delete_queue()
classmethod from_connection_string(conn_str: str, queue_name: str, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any)QueueClient[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 – 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.

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: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any)QueueClient[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 – 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.

Returns

A queue client.

Return type

QueueClient

get_queue_access_policy(**kwargs: Any)Dict[str, azure.storage.queue._models.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) – The server timeout, expressed in seconds.

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: Optional[int] = None, **kwargs: Any)List[azure.storage.queue._models.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) – The server timeout, expressed in seconds.

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(**kwargs: Any)azure.storage.queue._models.QueueMessage[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 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.

  • timeout (int) – The server timeout, expressed in seconds.

Returns

Returns a message from the Queue.

Return type

QueueMessage

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]

print(message1.content)
print(message2.content)
print(message3.content)
receive_messages(**kwargs: Any)azure.core.paging.ItemPaged[azure.storage.queue._models.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.

  • timeout (int) – The server timeout, expressed in seconds.

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

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: Any, **kwargs: Any)azure.storage.queue._models.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 (obj) – 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) – The server timeout, expressed in seconds.

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(u"message1")
queue.send_message(u"message2", visibility_timeout=30)  # wait 30s before becoming visible
queue.send_message(u"message3")
queue.send_message(u"message4")
queue.send_message(u"message5")
set_queue_access_policy(signed_identifiers: Dict[str, azure.storage.queue._models.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) – The server timeout, expressed in seconds.

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: Optional[Dict[str, Any]] = None, **kwargs: Any)None[source]

Sets user-defined metadata on the specified queue.

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

Parameters

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

Keyword Arguments

timeout (int) – The server timeout, expressed in seconds.

Example:

Set metadata on the queue.
metadata = {'foo': 'val1', 'bar': 'val2', 'baz': 'val3'}
queue.set_queue_metadata(metadata=metadata)
update_message(message: Any, pop_receipt: Optional[str] = None, content: Optional[Any] = None, **kwargs: Any)azure.storage.queue._models.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 (obj) – 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) – The server timeout, expressed in seconds.

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(u"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=u"updated")
property api_version

The version of the Storage API used for requests.

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

Type

str

property primary_endpoint

The full primary endpoint URL.

Type

str

property primary_hostname

The hostname of the primary endpoint.

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.

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.

Type

str or None

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().

class azure.storage.queue.QueueMessage(content=None)[source]

Represents a queue message.

Variables
  • 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 (date) – A UTC date value representing the time the messages was inserted.

  • expires_on (date) – A UTC date value representing the time the message expires.

  • dequeue_count (int) – Begins with a value of 1 the first time the message is received. This value is incremented each time the message is subsequently received.

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

  • next_visible_on (date) – 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.

Parameters

content (obj) – The message content. Type is determined by the decode_function set on the service. Default is str.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.storage.queue.QueueProperties(**kwargs)[source]

Queue Properties.

Variables

name (str) – The name of the queue.

Keyword Arguments

metadata (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. If this parameter was specified but the

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.storage.queue.QueueSasPermissions(read=False, add=False, update=False, process=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)[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

class azure.storage.queue.QueueServiceClient(account_url: str, credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = 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 – 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.

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 Azure Identity credentials.
# Get a token credential for authentication
from azure.identity import ClientSecretCredential
token_credential = ClientSecretCredential(
    self.active_directory_tenant_id,
    self.active_directory_application_id,
    self.active_directory_application_secret
)

# 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: Optional[Dict[str, str]] = None, **kwargs: Any)azure.storage.queue._queue_client.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.

Return type

QueueClient

Example:

Create a queue in the service.
queue_service.create_queue("myqueue1")
delete_queue(queue: Union[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: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, "TokenCredential"]] # pylint: disable=line-too-long = None, **kwargs: Any)QueueServiceClient[source]

Create QueueServiceClient from a Connection String.

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

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

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: Union[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: Optional[str] = None, include_metadata: Optional[bool] = 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) – The server timeout, expressed in seconds. 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: Optional[QueueAnalyticsLogging] = None, hour_metrics: Optional[Metrics] = None, minute_metrics: Optional[Metrics] = None, cors: Optional[List[CorsRule]] = 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 (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.

Return type

None

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.

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

Type

str

property primary_endpoint

The full primary endpoint URL.

Type

str

property primary_hostname

The hostname of the primary endpoint.

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.

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.

Type

str or None

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().

class azure.storage.queue.ResourceTypes(service=False, container=False, object=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

class azure.storage.queue.RetentionPolicy(enabled=False, days=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=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify 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, content_type=None)

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()
classmethod from_dict(data, key_extractors=None, content_type=None)

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()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure 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

class azure.storage.queue.StorageErrorCode(value)[source]

An enumeration.

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_ERALIER_VERSION_SNAPSHOT_NOT_ALLOWED = 'IncrementalCopyOfEralierVersionSnapshotNotAllowed'
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 = 'SnaphotOperationRateExceeded'
SNAPSHOTS_PRESENT = 'SnapshotsPresent'
SNAPSHOT_COUNT_EXCEEDED = 'SnapshotCountExceeded'
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, key_encryption_key, resolver)
decode(content, response)[source]
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, key_encryption_key, resolver, encryption_version='1.0')
encode(content)[source]
azure.storage.queue.generate_account_sas(account_name: str, account_key: str, resource_types: Union[ResourceTypes, str], permission: Union[AccountSasPermissions, str], expiry: Optional[Union[datetime, str]], start: Optional[Union[datetime, str]] = None, ip: Optional[str] = None, **kwargs: 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) – 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. 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 (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. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be 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

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

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: Optional[Union[QueueSasPermissions, str]] = None, expiry: Optional[Union[datetime, str]] = None, start: Optional[Union[datetime, str]] = None, policy_id: Optional[str] = None, ip: Optional[str] = None, **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) – 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. Azure will always convert values to UTC. If a date is passed in without timezone info, it is assumed to be 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.

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'
)