옵션
집 Skill API 개발 azure-messaging-webpubsubservice-py

azure-messaging-webpubsubservice-py

microsoft/skills microsoft/skills

Azure Web PubSub Service용 Python SDK를 사용하여 실시간 메시지를 보내고 WebSocket 연결을 관리합니다.

...모든 것을 확장하십시오
2
업데이트 된 시간 2026년 9월 18일

Azure Python용 Web PubSub 서비스 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(관리된 ID, 워크로드 ID)에서 작동합니다. 연결 문자열, 계정/API 키를 피하십시오 — 이는 Entra 감사 및 회전 우회합니다.
    • 로컬 개발: DefaultAzureCredential은 그대로 작동합니다.
    • 프로덕션: AZURE_TOKEN_CREDENTIALS=prod(또는 AZURE_TOKEN_CREDENTIALS=<특정_인증정보>)를 설정하여 인증 정보 체인을 프로덕션 안전 인증 정보로 제한합니다.
  2. 모든 클라이언트를 컨텍스트 관리자로 감싸십시오. HTTP 전송, 소켓 및 토큰 캐시가 결정적으로 해제되도록 합니다:
    • 동기: with <클라이언트>(...) as 클라이언트:</클라이언트>
    • 비동기: async with <클라이언트>(...) as 클라이언트:</클라이언트> 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=<특정_인증정보> 설정
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`연결 상태 확인

모범 사례

  1. 동기 또는 비동기 중 하나를 선택하고 일관성을 유지하십시오. 동일한 호출 경로에서 azure.xxx 동기 클라이언트와 azure.xxx.aio 비동기 클라이언트를 혼합하지 마십시오. 모듈당 하나의 모드를 선택하십시오.
  2. 클라이언트 및 비동기 인증 정보에 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를 with Client(...) as client: (동기) 또는 async with Client(...) as client: (비동기)로 감싸십시오. azure.identity.aio의 비동기 DefaultAzureCredential의 경우 토큰과 전송을 정리하기 위해 async with credential:도 사용하십시오.
  3. 로컬 개발 및 Azure 전반의 포터블 인증을 위해 DefaultAzureCredential을 사용하십시오 (가능한 경우 연결 문자열 / 액세스 키 피함).
  4. 클라이언트 권한을 제한하기 위해 역할(roles)을 사용하십시오
  5. 타겟팅된 메시징을 위해 그룹(groups)을 사용하십시오
  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가 자동으로 감지하고 사용합니다.
저장소 microsoft/skills

관련 스킬

brightdata-cli
업데이트 된 시간 2026년 6월 29일
humanize
업데이트 된 시간 2026년 7월 7일
agentwallet
업데이트 된 시간 2026년 7월 7일
korean-stock-search
업데이트 된 시간 2026년 7월 8일
OR