SuperAPI AI 工具集

azure-messaging-webpubsubservice-py

通用与其它

查看项目

更新于 10-16 10:48

技能介绍

Azure Web PubSub Service SDK for Python 是用于在 Azure Web PubSub 上实现实时消息传递的 Python 开发工具,面向需要大规模 WebSocket 连接与发布/订阅模式的场景。资料说明其核心能力是“Real-time messaging with WebSocket connections at scale”。

安装方式分为两部分。服务端 SDK 使用命令 pip install azure-messaging-webpubsubservice;面向 Python WebSocket 客户端的客户端 SDK 使用命令 pip install azure-messaging-webpubsubclient。

所需环境变量包括 AZURE_WEBPUBSUB_CONNECTION_STRING,其值形如 Endpoint=https://<name>.webpubsub.azure.com;AccessKey=...,以及 AZURE_WEBPUBSUB_HUB,用于指定 hub 名称。

服务端客户端支持两种认证方式:一是通过连接字符串,使用 WebPubSubServiceClient.from_connection_string(connection_string=..., hub="my-hub");二是使用 Entra ID,通过 azure.identity 的 DefaultAzureCredential,将 endpoint、hub 与 credential 传入 WebPubSubServiceClient。

主要功能包括:生成客户端访问令牌 get_client_access_token,可用于匿名用户,也可携带 user_id、roles(如 webpubsub.sendToGroup、webpubsub.joinLeaveGroup)或 groups 参数;消息发送方面,支持 send_to_all 向所有连接广播、send_to_user 向指定用户发送、send_to_group 向群组发送、send_to_connection 向指定连接发送,消息内容可为纯文本(content_type="text/plain")或 JSON(content_type="application/json")。群组管理提供 add_user_to_group、remove_user_from_group,以及针对连接的 add_connection_to_group、remove_connection_from_group。连接管理包括 connection_exists、user_exists、group_exists 检查,以及 close_connection(可带 reason)与 close_all_connections(针对用户)。权限方面支持 grant_permission、revoke_permission 与 check_permission,涉及权限如 joinLeaveGroup,并可指定 target_name。

客户端 SDK 方面,使用 WebPubSubClient(credential=token["url"]) 建立连接,通过 @client.on 注册事件处理器,例如 connected、server-message、group-message,然后调用 client.open() 连接,并使用 client.send_to_group("my-group", ...) 发送消息。

此外还提供异步服务端客户端,通过 azure.messaging.webpubsubservice.aio 导入 WebPubSubServiceClient、以 azure.identity.aio 导入 DefaultAzureCredential,在 async 函数中 await send_to_all 等操作,并在最后 await client.close() 与 await credential.close() 释放资源。

资料最后以表格列出服务端客户端操作,包括 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 等,其中 close_connection 一行的描述在原始资料中被截断。

适用场景为需要实时消息推送、WebSocket 连接管理与发布/订阅模式的 Python 应用。限制方面,具体定价、配额、服务等级、地域支持等信息暂未提供。