Azure WebPubSub Service Client Library for Python

1.3.0 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate `WebPubSubServiceClient` using a connection string from an environment variable and send a plain text message to all connected clients within a specified hub. Ensure `AZURE_WEBPUBSUB_CONNECTION_STRING` and `AZURE_WEBPUBSUB_HUB` environment variables are set for authentication and hub selection, respectively.

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}")

view raw JSON →