Azure service bus queue with .net core and python

This article covers implementing publishing and reading in the Azure Service Bus queue using both .Net Core and Python.

Azure is primarily a .NETCore shop but it does support other famous languages as well and one of them is Python. During a recent implementation of queues, I came across a thought of implementing service bus queues in python and honestly, it is simpler compared to .NET Core.

I will be using Visual Studio Code for implementation and the Python version is 3.12.3. Make sure that you have an Azure Service Bus resource ready with a queue in it

Let's start with .NET Core implementation first.

.NET CORE
 

Message Sender

For sending a message I have created a sample web API project. Just open the terminal, go to the folder where you want to add the solution and run the below command to create a web API project.

dotnet new webapi --use-controllers -o AzureServiceBus

This creates a web api solution.

Now open the solution in VSCode and install the below NugetPackage using the terminal itself.

dotnet add package Azure.Messaging.ServiceBus

Once this is done add a new model class to your solution. This will be the structure of the message that we will be sending.

namespace AzureServiceBus;
public class EmployeeModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Designation { get; set; }
    public string Department { get; set; }
    public string Note { get; set; }

}

Now, add a new Controller with endpoints to send the message to the queue.

using Microsoft.AspNetCore.Mvc;
using Azure.Messaging.ServiceBus;
using Newtonsoft.Json;
namespace AzureServiceBus.Controllers;
[ApiController]
[Route("[controller]")]
public class ServiceBusController: ControllerBase
{
    public ServiceBusController(){
    }
    [HttpPost]
    public async Task<IActionResult> SendMessageAsync([FromBody] EmployeeModel employee)
    {
        string connectionString = "your_connection_string";
        string queueName = "your_queue_name";
        var client = new ServiceBusClient(connectionString);
        var sender = client.CreateSender(queueName);
        string body = JsonConvert.SerializeObject(employee);
        var message = new ServiceBusMessage(body);
        await sender.SendMessageAsync(message);       
        return Ok("Message sent to the service bus queue");
        
    }

}

Now, I do not suggest putting connection string and queue name in code, it should rather come from app settings, but that is beyond the scope of this article.

Run the solution and call this endpoint with the body to create a message.

Endpoint

Active message

Message Receiver

We will be using a console application to receive these messages.

In order to create a console application using the terminal, run the below command.

dotnet new console -n AzureServiceBusReceiver

This creates a console application named AzureServiceBusReceiver.

Now open the solution in VSCode and install the below NugetPackage using the terminal itself.

dotnet add package Azure.Messaging.ServiceBus

Once, this is done, add the below code to the Program. cs.

using Azure.Messaging.ServiceBus;
string connectionString = "your_connection_string";
string queueName = "your_queue_name";
var client = new ServiceBusClient(connectionString);
var processor = client.CreateProcessor(queueName);
processor.ProcessMessageAsync += MessageHandler;
processor.ProcessErrorAsync += ErrorHandler;
await processor.StartProcessingAsync();
Console.ReadKey();
async Task MessageHandler(ProcessMessageEventArgs args)
{
    string body = args.Message.Body.ToString();
    Console.WriteLine($"Received: {body}");
    await args.CompleteMessageAsync(args.Message);
}
async Task ErrorHandler(ProcessErrorEventArgs args)
{
    Console.WriteLine(args.Exception.ToString());
}

Once you run this console application, it will read any existing messages in the queue. If you run both the above solutions together, you can send messages from web API solution and it will be received by the console application

Console Application

Python

Now, let's try to achieve the same using Python.

Create a folder for Python files and install the below package. This package is used to write and read messages to the Azure service bus queue.

pip install azure-servicebus

Create a file for pushing messages to the service bus queue and use the code below.

import asyncio
from azure.servicebus.aio import ServiceBusClient
from azure.servicebus import ServiceBusMessage
connection_string = 'your_connection_string'
queue = 'your_queue_name'
async def publish_message():
    async with ServiceBusClient.from_connection_string(connection_string) as client:
        async with client.get_queue_sender(queue) as sender:
            message = ServiceBusMessage("Hi, this is from python code")
            await sender.send_messages(message)
            print("Message sent successfully.")
asyncio.run(publish_message())

This code is quite straightforward. It creates a client using a connection string and then creates an object od the queue and then pushes the message to the queue. Asyncio is used to run the method asynchronously.

Now, create another file to read the messages from the queue.

import asyncio
from azure.servicebus.aio import ServiceBusClient
from azure.servicebus import ServiceBusMessage
connection_string = 'your_connection_string'
queue = 'your_queue_name'
async def read_message():
    async with ServiceBusClient.from_connection_string(connection_string) as client:
        async with client.get_queue_receiver(queue) as receiver:
            received_message = await receiver.receive_messages(max_wait_time=5, max_message_count=20)
            for message in received_message:
                print(message)
                await receiver.complete_message(message)
asyncio.run(read_message())

This method is similar to the previous one, the only difference is that we are reading the message in this one. This is also making sure to delete the message from the queue by marking it as deleted.

Now, let's run both files together using the below code.

python AzureServiceBusPub.py; python AzureServiceBusReceiver.py

We get the below result.

Result

As you can see, the message is sent by the publisher and then read by the receiver.

Hope this article helps you in setting up basic Azure service queue integration with .netcore and Python.


Similar Articles