选项
首页首页 Skill API开发 azure-messaging-webpubsubservice-py

azure-messaging-webpubsubservice-py

microsoft/skills microsoft/skills

使用适用于 Python 的 Azure Web PubSub 服务 SDK 发送实时消息并管理 WebSocket 连接。

...展开全部
2
更新时间 2026-09-18

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 时必需

身份验证与生命周期

🔑 以下每个代码示例均适用两条规则:

  1. 优先使用 DefaultAzureCredential 它在本地(Azure CLI / VS Code / Developer CLI)和 Azure(托管标识、工作负载标识)中无需更改代码即可工作。避免使用连接字符串、帐户/API 密钥——它们会绕过 Entra 审计和轮换机制。
    • 本地开发:DefaultAzureCredential 可直接使用。
    • 生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod(或 AZURE_TOKEN_CREDENTIALS=<specific_credential></specific_credential>)以将凭据链限制为生产安全的凭据。
  2. 将每个客户端包装在上下文管理器中,以便确定性地释放 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`检查连接状态

最佳实践

  1. 选择同步或异步并保持一致。 不要在同一个调用路径中混合使用 azure.xxx 同步客户端和 azure.xxx.aio 异步客户端。每个模块选择一种模式。
  2. 始终对客户端和异步凭据使用上下文管理器。 将每个客户端包装在 with Client(...) as client:(同步)或 async with Client(...) as client:(异步)中。对于来自 azure.identity.aio 的异步 DefaultAzureCredential,也请使用 async with credential:,以便清理令牌和传输层。
  3. 使用 DefaultAzureCredential 以实现本地开发和 Azure 之间的可移植身份验证(尽可能避免使用连接字符串/访问密钥)。
  4. 使用角色 限制客户端权限
  5. 使用组 进行定向消息传输
  6. 生成短期有效的令牌 以确保安全
  7. 使用用户 ID 跨连接向用户发送消息
  8. 在客户端应用程序中处理重连
  9. 使用 JSON 内容类型进行结构化数据传输
  10. 使用原因优雅地关闭连接
在 GitHub 上查看
---
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

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ 目录。Claude 将自动检测并使用该技能。

相关技能

agentwallet
更新时间 2026-07-07
brightdata-cli
更新时间 2026-06-29
humanize
更新时间 2026-07-07
korean-stock-search
更新时间 2026-07-08
OR