Azure Message Queue in Python

Hey, Fellow Developers!!

In this blog I am going to write about Azure Message Queue and how you can use it in your Python project easily by following this blog.

Let's dive into the blog without wasting much time.

Table of contents

  1. What is an Azure Message Queue?
  2. Implement Azure Message Queue in Python

1. What is an Azure Message Queue?

In simple terms as stated in Microsoft docs, Azure message queue is a service to store large number of messages. These messages can be accessed from anywhere in the world via authenticated HTTPS calls. This queue behaves the same as the queue data structure. The messages up to 64KB can be stored in message queue. It's highly scalable as it has the capacity to store millions of messages.

2. Implement Azure Message Queue in Python

Let's dive into some code now. I assume that you have created an Azure storage account and have the connection string with you.

1. Establish connection and create a new queue

To use the Azure queue client, first you need to install the azure-storage-queue as dependency in your virtual environment.

Install azure queue storage using this command

pip install azure-storage-queue

Now we have required dependency installed let's write code to establish connection and create a new queue storage.

#import queue client from azure queue storage
from azure.storage.queue import QueueClient

#set connection string
connection_str = "Your azure storage connection string"

#set name
queue_name = "test-queue" 

#create an instance of queue
test_queue = QueueClient.from_connection_string(conn_str=connection_str,
                                                       queue_name=queue_name)

#create a queue
test_queue.create_queue()

Running the code will create a new queue with name "test-queue". Let's test this further by sending a message to the queue storage.

2. Sending messages to the queue

We would use the created queue and try sending messages to it. This will make sure that the queue has been created successfully and it's working fine.

test_queue.send_message("Hey, test message!")
test_queue.send_message("Hey, How are you?")
test_queue.send_message("Hey, queue is working fine.")

3. Reading messages from the queue

Now, we would try to dequeue all the messages added to the "test queue".

#use the instance to get messages
responses = test_queue.receive_messages()

#iterate and print all the messages
for msg in responses:
    print(msg.content)
    test_queue.delete_message(msg) #delete the messages after reading

This would print all the messages we have added to the queue.

That's all for this blog. Happy coding

Comments

Popular posts from this blog

Introduction To Cloud Computing

Fundaments Of Microsoft Azure