opción
HogarHogar Skill Desarrollo de API azure-messaging-webpubsubservice-py

azure-messaging-webpubsubservice-py

microsoft/skills microsoft/skills

Envía mensajes en tiempo real y gestiona conexiones WebSocket utilizando el SDK de Azure Web PubSub Service para Python.

...Expandir todo
2
Tiempo actualizado 18 de septiembre de 2026

SDK de Azure Web PubSub para Python

Mensajería en tiempo real con conexiones WebSocket a gran escala.

Instalación

# SDK del servicio (lado del servidor)
pip install azure-messaging-webpubsubservice

# SDK del cliente (para clientes WebSocket de Python)
pip install azure-messaging-webpubsubclient

Variables de entorno

AZURE_WEBPUBSUB_HUB=my-hub  # Obligatorio para todos los métodos de autenticación
AZURE_TOKEN_CREDENTIALS=prod # Solo obligatorio si se usa DefaultAzureCredential en producción

Autenticación y ciclo de vida

🔑 Dos reglas se aplican a cada ejemplo de código a continuación:

  1. Preferir DefaultAzureCredential. Funciona localmente (Azure CLI / VS Code / Developer CLI) y en Azure (identidad administrada, identidad de carga de trabajo) sin cambios en el código. Evite las cadenas de conexión, claves de cuenta o claves de API, ya que eluden la auditoría y la rotación de Entra.
    • Desarrollo local: DefaultAzureCredential funciona tal cual.
    • Producción: establezca AZURE_TOKEN_CREDENTIALS=prod (o AZURE_TOKEN_CREDENTIALS=<credencial_específica>) para restringir la cadena de credenciales a credenciales seguras para producción.
  2. Envuelva cada cliente en un administrador de contexto para que las transferencias HTTP, los sockets y las cachés de tokens se liberen de forma determinista:
    • Síncrono: with <cliente>(...) as cliente:</cliente>
    • Asíncrono: async with <cliente>(...) as cliente:</cliente> y async with DefaultAzureCredential() as credencial: (de azure.identity.aio)

Los fragmentos pueden abreviar esta configuración, pero el código de producción debe seguir siempre ambas reglas.

Cliente del servicio (lado del servidor)

Autenticación

from azure.messaging.webpubsubservice import WebPubSubServiceClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential

# Desarrollo local: DefaultAzureCredential. Producción: establezca AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credencial_específica>
credencial = DefaultAzureCredential(require_envvar=True)
# O utilice una credencial específica directamente en producción:
# Consulte https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credencial = ManagedIdentityCredential()

with WebPubSubServiceClient(
    endpoint="https://<nombre>.webpubsub.azure.com",
    hub="my-hub",
    credential=credencial
) as cliente:
    # Utilice `cliente` para todas las operaciones posteriores (ver ejemplos a continuación)
    ...
</nombre></credencial_específica>

Generar token de acceso del cliente

# Token para usuario anónimo
token = cliente.get_client_access_token()
print(f"URL: {token['url']}")

# Token con ID de usuario
token = cliente.get_client_access_token(
    user_id="user123",
    roles=["webpubsub.sendToGroup", "webpubsub.joinLeaveGroup"]
)

# Token con grupos
token = cliente.get_client_access_token(
    user_id="user123",
    groups=["group1", "group2"]
)

Enviar a todos los clientes

# Enviar texto
cliente.send_to_all(message="¡Hola a todos!", content_type="text/plain")

# Enviar JSON
cliente.send_to_all(
    message={"type": "notification", "data": "Hola"},
    content_type="application/json"
)

Enviar a un usuario

cliente.send_to_user(
    user_id="user123",
    message="¡Hola usuario!",
    content_type="text/plain"
)

Enviar a un grupo

cliente.send_to_group(
    group="my-group",
    message="¡Hola grupo!",
    content_type="text/plain"
)

Enviar a una conexión

cliente.send_to_connection(
    connection_id="abc123",
    message="¡Hola conexión!",
    content_type="text/plain"
)

Gestión de grupos

# Añadir usuario al grupo
cliente.add_user_to_group(group="my-group", user_id="user123")

# Eliminar usuario del grupo
cliente.remove_user_from_group(group="my-group", user_id="user123")

# Añadir conexión al grupo
cliente.add_connection_to_group(group="my-group", connection_id="abc123")

# Eliminar conexión del grupo
cliente.remove_connection_from_group(group="my-group", connection_id="abc123")

Gestión de conexiones

# Comprobar si existe la conexión
existe = cliente.connection_exists(connection_id="abc123")

# Comprobar si el usuario tiene conexiones
existe = cliente.user_exists(user_id="user123")

# Comprobar si el grupo tiene conexiones
existe = cliente.group_exists(group="my-group")

# Cerrar conexión
cliente.close_connection(connection_id="abc123", reason="Sesión finalizada")

# Cerrar todas las conexiones para el usuario
cliente.close_all_connections(user_id="user123")

Conceder/revocar permisos

from azure.messaging.webpubsubservice import WebPubSubServiceClient

# Conceder permiso
cliente.grant_permission(
    permission="joinLeaveGroup",
    connection_id="abc123",
    target_name="my-group"
)

# Revocar permiso
cliente.revoke_permission(
    permission="joinLeaveGroup",
    connection_id="abc123",
    target_name="my-group"
)

# Comprobar permiso
tiene_permiso = cliente.check_permission(
    permission="joinLeaveGroup",
    connection_id="abc123",
    target_name="my-group"
)

SDK del cliente (cliente WebSocket de Python)

from azure.messaging.webpubsubclient import WebPubSubClient

with WebPubSubClient(credential=token["url"]) as cliente:
    @cliente.on("connected")
    def on_connected(e):
        print(f"Conectado: {e.connection_id}")

    @cliente.on("server-message")
    def on_message(e):
        print(f"Mensaje: {e.data}")

    @cliente.on("group-message")
    def on_group_message(e):
        print(f"Grupo {e.group}: {e.data}")

    cliente.send_to_group("my-group", "¡Hola desde Python!")

Cliente de servicio asíncrono

from azure.messaging.webpubsubservice.aio import WebPubSubServiceClient
from azure.identity.aio import DefaultAzureCredential

async def broadcast():
    async with DefaultAzureCredential() as credencial:
        async with WebPubSubServiceClient(
            endpoint="https://<nombre>.webpubsub.azure.com",
            hub="my-hub",
            credential=credencial
        ) as cliente:
            await cliente.send_to_all("¡Hola asíncrono!", content_type="text/plain")
</nombre>

Operaciones del cliente

OperaciónDescripción
`get_client_access_token`Generar URL de conexión WebSocket
`send_to_all`Difundir a todas las conexiones
`send_to_user`Enviar a un usuario específico
`send_to_group`Enviar a miembros del grupo
`send_to_connection`Enviar a una conexión específica
`add_user_to_group`Añadir usuario al grupo
`remove_user_from_group`Eliminar usuario del grupo
`close_connection`Desconectar cliente
`connection_exists`Comprobar estado de la conexión

Mejores prácticas

  1. Elija síncrono O asíncrono y mantenga la coherencia. No mezcle clientes síncronos azure.xxx con clientes asíncronos azure.xxx.aio en la misma ruta de llamada. Elija un modo por módulo.
  2. Utilice siempre administradores de contexto para clientes y credenciales asíncronas. Envuelva cada cliente en with Cliente(...) as cliente: (síncrono) o async with Cliente(...) as cliente: (asíncrono). Para DefaultAzureCredential asíncrono de azure.identity.aio, utilice también async with credencial: para que los tokens y las transferencias se limpien correctamente.
  3. Utilice DefaultAzureCredential para una autenticación portátil entre el desarrollo local y Azure (evite cadenas de conexión o claves de acceso cuando sea posible).
  4. Utilice roles para limitar los permisos del cliente
  5. Utilice grupos para mensajes dirigidos
  6. Genere tokens de corta duración por seguridad
  7. Utilice IDs de usuario para enviar mensajes a usuarios a través de conexiones
  8. Gestione la reconexión en las aplicaciones cliente
  9. Utilice el tipo de contenido JSON para datos estructurados
  10. Cierre las conexiones de forma elegante con motivos
Ver en 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

Todos los archivos

0 archivos

Instalar azure-messaging-webpubsubservice-py

Descarga y extrae los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

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

Copiar Copiar
Configuración rápida: Copie la carpeta de habilidades a .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

brightdata-cli
Tiempo actualizado 29 de junio de 2026
humanize
Tiempo actualizado 7 de julio de 2026
agentwallet
Tiempo actualizado 7 de julio de 2026
korean-stock-search
Tiempo actualizado 8 de julio de 2026
OR