Azure WebPubSub Service Client Library for Python
The Azure Web PubSub service client library for Python enables developers to build real-time web applications using WebSockets and the publish-subscribe pattern. It provides server-side APIs to manage WebSocket client connections, send messages to clients, groups, or specific users, and control permissions. The library is actively maintained as part of the Azure SDK for Python, with a rapid release cadence, and the current stable version is 1.3.0.
Warnings
- breaking Support for Python 2.7 has officially ended as of January 1, 2022. Users on Python 2.7 will not receive updates and should migrate to Python 3.6+ (or preferably 3.8+ as per current PyPI requirements).
- gotcha When using Azure Active Directory (AAD) for authentication with `DefaultAzureCredential`, you must install the `azure-identity` package separately (`pip install azure-identity`) and enable AAD authentication on your Azure Web PubSub resource. Direct use of connection strings is simpler for initial setup but less secure for production.
- gotcha The SDK provides both synchronous (`WebPubSubServiceClient`) and asynchronous (`WebPubSubServiceAsyncClient` from `azure.messaging.webpubsubservice.aio`) clients. Mixing sync and async operations without proper `asyncio` context can lead to unexpected behavior or deadlocks. Choose the appropriate client for your application's concurrency model.
- gotcha Error handling for server-side issues will often involve `azure.core.exceptions.HttpResponseError` rather than client-side `ValidationError`. This means you need to catch these exceptions for robust error handling, especially for issues like malformed requests or service-side failures.
Install
-
pip install azure-messaging-webpubsubservice
Imports
- WebPubSubServiceClient
from azure.messaging.webpubsubservice import WebPubSubServiceClient
- WebPubSubServiceAsyncClient
from azure.messaging.webpubsubservice.aio import WebPubSubServiceClient
Quickstart
import os
from azure.messaging.webpubsubservice import WebPubSubServiceClient
# --- Authentication ---
# Option 1: Connection string (recommended for quickstart/dev)
# Set environment variable AZURE_WEBPUBSUB_CONNECTION_STRING
connection_string = os.environ.get('AZURE_WEBPUBSUB_CONNECTION_STRING', 'Endpoint=https://<your-service>.webpubsub.azure.com;AccessKey=<your-access-key>;Version=1.0;')
# Set environment variable AZURE_WEBPUBSUB_HUB
hub_name = os.environ.get('AZURE_WEBPUBSUB_HUB', 'myHub')
if not connection_string or 'Endpoint=' not in connection_string:
print("Please set the AZURE_WEBPUBSUB_CONNECTION_STRING environment variable or provide a valid connection string.")
exit(1)
if not hub_name or hub_name == 'myHub':
print("Please set the AZURE_WEBPUBSUB_HUB environment variable or provide a valid hub name.")
exit(1)
# Create a WebPubSubServiceClient instance
service_client = WebPubSubServiceClient.from_connection_string(connection_string, hub=hub_name)
# --- Send a message to all clients in the hub ---
try:
print(f"Sending 'Hello World' to all clients in hub '{hub_name}'...")
response = service_client.send_to_all("Hello World", content_type='text/plain')
print(f"Message sent. Response: {response}")
# Example: Send a JSON message
# response = service_client.send_to_all({'message': 'Hello from Python!', 'type': 'greeting'}, content_type='application/json')
# print(f"JSON message sent. Response: {response}")
except Exception as e:
print(f"An error occurred: {e}")