azure-messaging-webpubsubservice-py
microsoft/skills
Python 用の Azure Web PubSub Service SDK を使用して、リアルタイム メッセージの送信と WebSocket 接続の管理を行います。
...すべて拡張しますAzure Web PubSub Service 用 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 を使用する場合にのみ必須
認証とライフサイクル
🔑 以下のすべてのコードサンプルに適用される2つのルール:
DefaultAzureCredentialを優先してください。 ローカル(Azure CLI / VS Code / Developer CLI)および Azure(マネージド ID、ワークロード ID)で、コード変更なしで動作します。接続文字列やアカウント/API キーを避けてください。これらは Entra の監査とローテーションをバイパスします。
- ローカル開発:
DefaultAzureCredentialはそのまま動作します。- 本番環境:
AZURE_TOKEN_CREDENTIALS=prod(またはAZURE_TOKEN_CREDENTIALS=<特定の資格情報>)を設定し、資格情報チェーンを本番環境に安全な資格情報に制限します。- すべてのクライアントをコンテキストマネージャーでラップ し、HTTP トランスポート、ソケット、トークンキャッシュが確定的に解放されるようにします:
- 同期:
with <クライアント>(...) as クライアント:</クライアント>- 非同期:
async with <クライアント>(...) as クライアント:</クライアント>およびasync with DefaultAzureCredential() as 資格情報:(azure.identity.aioから)スニペットはこの設定を省略することがありますが、本番コードは常に両方のルールに従う必要があります。
サービスクライアント(サーバー側)
認証
from azure.messaging.webpubsubservice import WebPubSubServiceClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
# ローカル開発:DefaultAzureCredential。本番環境:AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=<特定の資格情報> を設定
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://<名前>.webpubsub.azure.com",
hub="my-hub",
credential=credential
) as client:
# 以降のすべての操作に `client` を使用します(以下の例を参照)
...
</名前></特定の資格情報>クライアントアクセストークンの生成
# 匿名ユーザーのトークン
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="皆さん、こんにちは!", content_type="text/plain")
# JSON を送信
client.send_to_all(
message={"type": "notification", "data": "こんにちは"},
content_type="application/json"
)
ユーザーへの送信
client.send_to_user(
user_id="user123",
message="ユーザーさん、こんにちは!",
content_type="text/plain"
)
グループへの送信
client.send_to_group(
group="my-group",
message="グループの皆さん、こんにちは!",
content_type="text/plain"
)
接続への送信
client.send_to_connection(
connection_id="abc123",
message="接続さん、こんにちは!",
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="セッション終了")
# ユーザーのすべての接続を閉じる
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"接続済み: {e.connection_id}")
@client.on("server-message")
def on_message(e):
print(f"メッセージ: {e.data}")
@client.on("group-message")
def on_group_message(e):
print(f"グループ {e.group}: {e.data}")
client.send_to_group("my-group", "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://<名前>.webpubsub.azure.com",
hub="my-hub",
credential=credential
) as client:
await client.send_to_all("こんにちは 非同期!", content_type="text/plain")
</名前>クライアント操作
| 操作 | 説明 |
|---|---|
| `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非同期クライアントを混在させないこと。モジュールごとに1つのモードを選択してください。 - クライアントと非同期資格情報の常にコンテキストマネージャーを使用する。 すべてのクライアントを
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
コピー





家
