Azure Queue Storage Client Library for Python

12.15.0 · active · verified Sat Mar 28

The Azure Queue Storage client library for Python (azure-storage-queue) enables Python applications to interact with Azure Queue Storage, a service for storing large numbers of messages. A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, facilitating asynchronous work backlogs and decoupled distributed applications. The library is actively maintained as part of the Azure SDK for Python, with version 12.15.0 being the latest stable release.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `QueueServiceClient` (using either a connection string or `DefaultAzureCredential`), create a queue, send messages, peek at messages, receive and delete messages, and finally delete the queue. It highlights the use of `BinaryBase64EncodePolicy` and `BinaryBase64DecodePolicy` for message handling. Ensure `AZURE_STORAGE_CONNECTION_STRING` or `AZURE_STORAGE_ACCOUNT_URL` and necessary Azure Identity environment variables (e.g., `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`) are set for authentication.

import os, uuid
from azure.identity import DefaultAzureCredential
from azure.storage.queue import QueueServiceClient, QueueClient, BinaryBase64EncodePolicy, BinaryBase64DecodePolicy

try:
    print('Azure Queue storage - Python quickstart sample')

    # Retrieve the connection string for use with the application.
    # The storage connection string is a key for accessing your storage account.
    # It is recommended to use passwordless authentication in production.
    connect_str = os.environ.get('AZURE_STORAGE_CONNECTION_STRING', '')
    queue_name = "quickstart-" + str(uuid.uuid4())

    # Create the QueueServiceClient object
    if connect_str:
        # Authenticate with connection string
        queue_service_client = QueueServiceClient.from_connection_string(
            connect_str, 
            message_encode_policy=BinaryBase64EncodePolicy(),
            message_decode_policy=BinaryBase64DecodePolicy()
        )
        print("Using connection string for authentication.")
    else:
        # Authenticate with DefaultAzureCredential
        account_url = os.environ.get('AZURE_STORAGE_ACCOUNT_URL') # e.g., 'https://<account-name>.queue.core.windows.net'
        if not account_url:
            raise ValueError("Please set AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT_URL environment variable.")

        credential = DefaultAzureCredential()
        queue_service_client = QueueServiceClient(
            account_url=account_url, 
            credential=credential,
            message_encode_policy=BinaryBase64EncodePolicy(),
            message_decode_policy=BinaryBase64DecodePolicy()
        )
        print("Using DefaultAzureCredential for authentication.")

    # Get a client to interact with the queue
    queue_client = queue_service_client.get_queue_client(queue_name)

    # Create a queue
    print(f"Creating queue: {queue_name}")
    queue_client.create_queue()

    # Send a message
    message1 = "Hello, Azure Queue!"
    print(f"Adding message: {message1}")
    queue_client.send_message(message1)

    message2 = "This is a second message."
    print(f"Adding message: {message2}")
    queue_client.send_message(message2)

    # Peek at messages
    print("Peeking at messages...")
    peeked_messages = queue_client.peek_messages(max_messages=5)
    for peeked_message in peeked_messages:
        print(f"Peeked message: {peeked_message.content}")

    # Receive and delete messages
    print("Receiving and deleting messages...")
    messages = queue_client.receive_messages(messages_per_page=1)
    for message in messages:
        print(f"Received message: {message.content}")
        queue_client.delete_message(message)
        print(f"Deleted message: {message.content}")

    print(f"Successfully completed the quickstart. Deleting queue: {queue_name}")
    queue_client.delete_queue()

except Exception as ex:
    print(f"Exception: {ex}")

view raw JSON →