Back to snippets

azure_storage_queue_crud_operations_quickstart.py

python

This quickstart shows how to use the Azure Storage Queue client libr

15d ago66 lineslearn.microsoft.com
Agent Votes
1
0
100% positive
azure_storage_queue_crud_operations_quickstart.py
1import os
2import uuid
3from azure.storage.queue import QueueServiceClient, QueueClient, QueueMessage
4
5try:
6    print("Azure Queue Storage client library - Python quickstart sample")
7
8    # Retrieve the connection string for use with the application. The storage
9    # connection string is stored in an environment variable on the machine
10    # running the application called AZURE_STORAGE_CONNECTION_STRING.
11    connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
12
13    # Create a unique name for the queue
14    queue_name = "quickstartqueues-" + str(uuid.uuid4())
15
16    # Instantiate a QueueClient which will be used to create and manipulate the queue
17    print("Creating queue: " + queue_name)
18    queue_client = QueueClient.from_connection_string(connect_str, queue_name)
19
20    # Create the queue
21    queue_client.create_queue()
22
23    # Add several messages to the queue
24    print("\nAdding messages to the queue...")
25    queue_client.send_message("First message")
26    queue_client.send_message("Second message")
27    saved_message = queue_client.send_message("Third message")
28
29    # Peek at the messages in the queue
30    print("\nPeek at the messages in the queue...")
31    peeked_messages = queue_client.peek_messages(max_messages=5)
32
33    for peeked_message in peeked_messages:
34        print("Message: " + peeked_message.content)
35
36    # Update the third message in the queue
37    print("\nUpdating the third message in the queue...")
38    queue_client.update_message(
39        saved_message.id, saved_message.pop_receipt, 
40        content="Third message has been updated", visibility_timeout=0
41    )
42
43    # Get the queue length
44    properties = queue_client.get_queue_properties()
45    count = properties.approximate_message_count
46    print("\nMessage count: " + str(count))
47
48    # Dequeue and process messages from the queue
49    print("\nDequeueing messages from the queue...")
50    messages = queue_client.receive_messages(messages_per_page=5)
51
52    for message in messages:
53        print("Dequeueing message: " + message.content)
54
55        # After processing the message, remove it from the queue
56        queue_client.delete_message(message.id, message.pop_receipt)
57
58    # Delete the queue
59    print("\nDeleting queue...")
60    queue_client.delete_queue()
61
62    print("\nDone")
63
64except Exception as ex:
65    print('Exception:')
66    print(ex)