azure-messaging-webpubsubservice-py
microsoft/skills
使用適用於 Python 的 Azure Web PubSub 服務 SDK 傳送實時訊息並管理 WebSocket 連線。
...展開全部Azure Web PubSub 服務 Python SDK
以大規模方式透過 WebSocket 連線進行實時訊息傳輸。
安裝
# 服務 SDK(伺服器端)
pip install azure-messaging-webpubsubservice
# 客戶端 SDK(用於 Python WebSocket 客戶端)
pip install azure-messaging-webpubsubclient
環境變數
AZURE_WEBPUBSUB_HUB=my-hub # 所有身份驗證方法必需
AZURE_TOKEN_CREDENTIALS=prod # 僅在生產環境中使用 DefaultAzureCredential 時必需
身份驗證與生命週期
🔑 以下每個程式碼示例均適用兩條規則:
- 優先使用
DefaultAzureCredential。 它在本地(Azure CLI / VS Code / Developer CLI)和 Azure(託管標識、工作負載標識)中無需更改程式碼即可工作。避免使用連線字串、帳戶/API 金鑰——它們會繞過 Entra 審計和輪換機制。
- 本地開發:
DefaultAzureCredential可直接使用。- 生產環境:設定
AZURE_TOKEN_CREDENTIALS=prod(或AZURE_TOKEN_CREDENTIALS=<specific_credential></specific_credential>)以將憑據鏈限制為生產安全的憑據。- 將每個客戶端包裝在上下文管理器中,以便確定性地釋放 HTTP 傳輸、套接字和令牌快取:
- 同步:
with <client>(...) as client:</client>- 非同步:
async with <client>(...) as client:</client>以及async with DefaultAzureCredential() as credential:(來自azure.identity.aio)程式碼片段可能會簡化此設定,但生產程式碼應始終遵循這兩條規則。
服務客戶端(伺服器端)
身份驗證
from azure.messaging.webpubsubservice import WebPubSubServiceClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
# 本地開發:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生產環境中直接使用特定憑據:
# 請參閱 https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with WebPubSubServiceClient(
endpoint="https://<name>.webpubsub.azure.com",
hub="my-hub",
credential=credential
) as client:
# 對 `client` 執行所有後續操作(見以下示例)
...
</name></specific_credential>生成客戶端訪問令牌
# 匿名使用者的令牌
token = client.get_client_access_token()
print(f"URL: {token['url']}")
# 帶有使用者 ID 的令牌
token = client.get_client_access_token(
user_id="user123",
roles=["webpubsub.sendToGroup", "webpubsub.joinLeaveGroup"]
)
# 帶有組的令牌
token = client.get_client_access_token(
user_id="user123",
groups=["group1", "group2"]
)
向所有客戶端傳送訊息
# 傳送文字
client.send_to_all(message="Hello everyone!", content_type="text/plain")
# 傳送 JSON
client.send_to_all(
message={"type": "notification", "data": "Hello"},
content_type="application/json"
)
向使用者傳送訊息
client.send_to_user(
user_id="user123",
message="Hello user!",
content_type="text/plain"
)
向組傳送訊息
client.send_to_group(
group="my-group",
message="Hello group!",
content_type="text/plain"
)
向連線傳送訊息
client.send_to_connection(
connection_id="abc123",
message="Hello connection!",
content_type="text/plain"
)
組管理
# 將使用者新增到組
client.add_user_to_group(group="my-group", user_id="user123")
# 從組中移除使用者
client.remove_user_from_group(group="my-group", user_id="user123")
# 將連線新增到組
client.add_connection_to_group(group="my-group", connection_id="abc123")
# 從組中移除連線
client.remove_connection_from_group(group="my-group", connection_id="abc123")
連線管理
# 檢查連線是否存在
exists = client.connection_exists(connection_id="abc123")
# 檢查使用者是否有連線
exists = client.user_exists(user_id="user123")
# 檢查組是否有連線
exists = client.group_exists(group="my-group")
# 關閉連線
client.close_connection(connection_id="abc123", reason="Session ended")
# 關閉使用者的所有連線
client.close_all_connections(user_id="user123")
授予/撤銷許可權
from azure.messaging.webpubsubservice import WebPubSubServiceClient
# 授予許可權
client.grant_permission(
permission="joinLeaveGroup",
connection_id="abc123",
target_name="my-group"
)
# 撤銷許可權
client.revoke_permission(
permission="joinLeaveGroup",
connection_id="abc123",
target_name="my-group"
)
# 檢查許可權
has_permission = client.check_permission(
permission="joinLeaveGroup",
connection_id="abc123",
target_name="my-group"
)
客戶端 SDK(Python WebSocket 客戶端)
from azure.messaging.webpubsubclient import WebPubSubClient
with WebPubSubClient(credential=token["url"]) as client:
@client.on("connected")
def on_connected(e):
print(f"Connected: {e.connection_id}")
@client.on("server-message")
def on_message(e):
print(f"Message: {e.data}")
@client.on("group-message")
def on_group_message(e):
print(f"Group {e.group}: {e.data}")
client.send_to_group("my-group", "Hello from Python!")
非同步服務客戶端
from azure.messaging.webpubsubservice.aio import WebPubSubServiceClient
from azure.identity.aio import DefaultAzureCredential
async def broadcast():
async with DefaultAzureCredential() as credential:
async with WebPubSubServiceClient(
endpoint="https://<name>.webpubsub.azure.com",
hub="my-hub",
credential=credential
) as client:
await client.send_to_all("Hello async!", content_type="text/plain")
</name>客戶端操作
| 操作 | 描述 |
|---|---|
| `get_client_access_token` | 生成 WebSocket 連線 URL |
| `send_to_all` | 向所有連線廣播 |
| `send_to_user` | 向特定使用者傳送 |
| `send_to_group` | 向組成員傳送 |
| `send_to_connection` | 向特定連線傳送 |
| `add_user_to_group` | 將使用者新增到組 |
| `remove_user_from_group` | 從組中移除使用者 |
| `close_connection` | 斷開客戶端連線 |
| `connection_exists` | 檢查連線狀態 |
最佳實踐
- 選擇同步或非同步並保持一致。 不要在同一個呼叫路徑中混合使用
azure.xxx同步客戶端和azure.xxx.aio非同步客戶端。每個模組選擇一種模式。 - 始終對客戶端和非同步憑據使用上下文管理器。 將每個客戶端包裝在
with Client(...) as client:(同步)或async with Client(...) as client:(非同步)中。對於來自azure.identity.aio的非同步DefaultAzureCredential,也請使用async with credential:,以便清理令牌和傳輸層。 - 使用
DefaultAzureCredential以實現本地開發和 Azure 之間的可移植身份驗證(儘可能避免使用連線字串/訪問金鑰)。 - 使用角色 限制客戶端許可權
- 使用組 進行定向訊息傳輸
- 生成短期有效的令牌 以確保安全
- 使用使用者 ID 跨連線向使用者傳送訊息
- 在客戶端應用程式中處理重連
- 使用 JSON 內容型別進行結構化資料傳輸
- 使用原因優雅地關閉連線
---
name: azure-messaging-webpubsubservice-py
description: Send real-time messages and manage WebSocket connections using Azure Web PubSub Service SDK for Python.
license: MIT
---
# Azure Web PubSub Service SDK for Python
Real-time messaging with WebSocket connections at scale.
## Installation
```bash
# Service SDK (server-side)
pip install azure-messaging-webpubsubservice
# Client SDK (for Python WebSocket clients)
pip install azure-messaging-webpubsubclient
```
## Environment Variables
```bash
AZURE_WEBPUBSUB_HUB=my-hub # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
## Service Client (Server-Side)
### Authentication
```python
from azure.messaging.webpubsubservice import WebPubSubServiceClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with WebPubSubServiceClient(
endpoint="https://<name>.webpubsub.azure.com",
hub="my-hub",
credential=credential
) as client:
# Use `client` for all subsequent operations (see examples below)
...
```
### Generate Client Access Token
```python
# Token for anonymous user
token = client.get_client_access_token()
print(f"URL: {token['url']}")
# Token with user ID
token = client.get_client_access_token(
user_id="user123",
roles=["webpubsub.sendToGroup", "webpubsub.joinLeaveGroup"]
)
# Token with groups
token = client.get_client_access_token(
user_id="user123",
groups=["group1", "group2"]
)
```
### Send to All Clients
```python
# Send text
client.send_to_all(message="Hello everyone!", content_type="text/plain")
# Send JSON
client.send_to_all(
message={"type": "notification", "data": "Hello"},
content_type="application/json"
)
```
### Send to User
```python
client.send_to_user(
user_id="user123",
message="Hello user!",
content_type="text/plain"
)
```
### Send to Group
```python
client.send_to_group(
group="my-group",
message="Hello group!",
content_type="text/plain"
)
```
### Send to Connection
```python
client.send_to_connection(
connection_id="abc123",
message="Hello connection!",
content_type="text/plain"
)
```
### Group Management
```python
# Add user to group
client.add_user_to_group(group="my-group", user_id="user123")
# Remove user from group
client.remove_user_from_group(group="my-group", user_id="user123")
# Add connection to group
client.add_connection_to_group(group="my-group", connection_id="abc123")
# Remove connection from group
client.remove_connection_from_group(group="my-group", connection_id="abc123")
```
### Connection Management
```python
# Check if connection exists
exists = client.connection_exists(connection_id="abc123")
# Check if user has connections
exists = client.user_exists(user_id="user123")
# Check if group has connections
exists = client.group_exists(group="my-group")
# Close connection
client.close_connection(connection_id="abc123", reason="Session ended")
# Close all connections for user
client.close_all_connections(user_id="user123")
```
### Grant/Revoke Permissions
```python
from azure.messaging.webpubsubservice import WebPubSubServiceClient
# Grant permission
client.grant_permission(
permission="joinLeaveGroup",
connection_id="abc123",
target_name="my-group"
)
# Revoke permission
client.revoke_permission(
permission="joinLeaveGroup",
connection_id="abc123",
target_name="my-group"
)
# Check permission
has_permission = client.check_permission(
permission="joinLeaveGroup",
connection_id="abc123",
target_name="my-group"
)
```
## Client SDK (Python WebSocket Client)
```python
from azure.messaging.webpubsubclient import WebPubSubClient
with WebPubSubClient(credential=token["url"]) as client:
@client.on("connected")
def on_connected(e):
print(f"Connected: {e.connection_id}")
@client.on("server-message")
def on_message(e):
print(f"Message: {e.data}")
@client.on("group-message")
def on_group_message(e):
print(f"Group {e.group}: {e.data}")
client.send_to_group("my-group", "Hello from Python!")
```
## Async Service Client
```python
from azure.messaging.webpubsubservice.aio import WebPubSubServiceClient
from azure.identity.aio import DefaultAzureCredential
async def broadcast():
async with DefaultAzureCredential() as credential:
async with WebPubSubServiceClient(
endpoint="https://<name>.webpubsub.azure.com",
hub="my-hub",
credential=credential
) as client:
await client.send_to_all("Hello async!", content_type="text/plain")
```
## Client Operations
| Operation | Description |
|-----------|-------------|
| `get_client_access_token` | Generate WebSocket connection URL |
| `send_to_all` | Broadcast to all connections |
| `send_to_user` | Send to specific user |
| `send_to_group` | Send to group members |
| `send_to_connection` | Send to specific connection |
| `add_user_to_group` | Add user to group |
| `remove_user_from_group` | Remove user from group |
| `close_connection` | Disconnect client |
| `connection_exists` | Check connection status |
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.xxx` sync clients with `azure.xxx.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use `DefaultAzureCredential`** for portable auth across local dev and Azure (avoid connection strings / access keys when possible).
4. **Use roles** to limit client permissions
4. **Use groups** for targeted messaging
5. **Generate short-lived tokens** for security
6. **Use user IDs** to send to users across connections
7. **Handle reconnection** in client applications
8. **Use JSON** content type for structured data
9. **Close connections** gracefully with reasons
所有檔案
0 個檔案安裝 azure-messaging-webpubsubservice-py
將技能檔案下載並解壓至你的 .claude/skills/ 目錄。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-messaging-webpubsubservice-py # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
