Azure Service Bus Queue - Python SDK Samples

Explore these practical samples demonstrating how to use the Azure Service Bus Python SDK to interact with Service Bus queues. These examples cover common operations like sending and receiving messages.

Sending Messages to a Queue

This sample shows how to connect to a Service Bus namespace and send messages to a specific queue.

Prerequisites:

Python Code:

```python import os import asyncio from azure.servicebus.aio import ServiceBusClient # Replace with your actual connection string and queue name CONNECTION_STR = os.environ.get("SERVICEBUS_CONNECTION_STRING", "YOUR_CONNECTION_STRING") QUEUE_NAME = "your-queue-name" async def send_message(): async with ServiceBusClient.from_connection_string(CONNECTION_STR) as servicebus_client: sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME) async with sender: message = {"data": "Hello, Service Bus!"} await sender.send_messages(message) print(f"Sent message: {message}") if __name__ == "__main__": asyncio.run(send_message()) ```

Note: It is recommended to use environment variables for connection strings rather than hardcoding them.

Receiving Messages from a Queue

This sample demonstrates how to connect to a Service Bus queue and receive messages asynchronously.

Prerequisites:

Python Code:

```python import os import asyncio from azure.servicebus.aio import ServiceBusClient # Replace with your actual connection string and queue name CONNECTION_STR = os.environ.get("SERVICEBUS_CONNECTION_STRING", "YOUR_CONNECTION_STRING") QUEUE_NAME = "your-queue-name" async def receive_messages(): async with ServiceBusClient.from_connection_string(CONNECTION_STR) as servicebus_client: receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME) async with receiver: async for message in receiver: print(f"Received message: {message}") # Complete the message to remove it from the queue await receiver.complete_message(message) print("Message completed.") if __name__ == "__main__": print(f"Receiving messages from queue: {QUEUE_NAME}") try: asyncio.run(receive_messages()) except KeyboardInterrupt: print("Receiving stopped by user.") ```

Note: The receiver will continue to run until interrupted or no more messages are available. Use Ctrl+C to stop the receiver.