Package: azure-messaging-webpubsubservice
Azure Web PubSub service client library for PythonAzure Web PubSub Serviceis an Azure-managed service that helps developers easily build web applications with real-time features and publish-subscribe pattern. Any scenario that requires real-time publish-subscribe messaging between server and clients or among clients can use Azure Web PubSub service. Traditional real-time features that often require polling from server or submitting HTTP requests can also use Azure Web PubSub service.You can use this library in your app server side to manage the WebSocket client connections, as shown in below diagram:Use this library to:Send messages to hubs and groups.Send messages to particular users and connections.Organize users and connections into groups.Close connectionsGrant, revoke, and check permissions for an existing connectionSource code|Package (Pypi)|API reference documentation|Product documentationDisclaimerAzure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer tohttps://github.com/Azure/azure-sdk-for-python/issues/20691Getting startedPrerequisitesPython 3.6 or later is required to use this package.You need anAzure subscription, and aAzure WebPubSub service instanceto use this package.An existing Azure Web PubSub service instance.1. Install the packagepython-mpipinstallazure-messaging-webpubsubservice2. Create and authenticate a WebPubSubServiceClientYou can authenticate theWebPubSubServiceClientusingconnection string:>>>fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient>>>service=WebPubSubServiceClient.from_connection_string(connection_string='<connection_string>',hub='hub')Or using the service endpoint and the access key:>>>fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient>>>fromazure.core.credentialsimportAzureKeyCredential>>>service=WebPubSubServiceClient(endpoint='<endpoint>',hub='hub',credential=AzureKeyCredential("<access_key>"))Or usingAzure Active Directory:pipinstallazure-identityFollow the document toenable AAD authentication on your Webpubsub resourceUpdate code to useDefaultAzureCredential>>>fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient>>>fromazure.identityimportDefaultAzureCredential>>>service=WebPubSubServiceClient(endpoint='<endpoint>',hub='hub',credential=DefaultAzureCredential())Key conceptsConnectionA connection, also known as a client or a client connection, represents an individual WebSocket connection connected to the Web PubSub service. When successfully connected, a unique connection ID is assigned to this connection by the Web PubSub service.HubA hub is a logical concept for a set of client connections. Usually you use one hub for one purpose, for example, a chat hub, or a notification hub. When a client connection is created, it connects to a hub, and during its lifetime, it belongs to that hub. Different applications can share one Azure Web PubSub service by using different hub names.GroupA group is a subset of connections to the hub. You can add a client connection to a group, or remove the client connection from the group, anytime you want. For example, when a client joins a chat room, or when a client leaves the chat room, this chat room can be considered to be a group. A client can join multiple groups, and a group can contain multiple clients.UserConnections to Web PubSub can belong to one user. A user might have multiple connections, for example when a single user is connected across multiple devices or multiple browser tabs.MessageWhen the client is connected, it can send messages to the upstream application, or receive messages from the upstream application, through the WebSocket connection.ExamplesBroadcast messages in JSON format>>>fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient>>>service=WebPubSubServiceClient.from_connection_string('<connection_string>',hub='hub1')>>>service.send_to_all(message={'from':'user1','data':'Hello world'})The WebSocket client will receive JSON serialized text:{"from": "user1", "data": "Hello world"}.Broadcast messages in plain-text format>>>fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient>>>service=WebPubSubServiceClient.from_connection_string('<connection_string>',hub='hub1')>>>service.send_to_all(message='Hello world',content_type='text/plain')The WebSocket client will receive text:Hello world.Broadcast messages in binary format>>>importio>>>fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient>>>service=WebPubSubServiceClient.from_connection_string('<connection_string>',hub='hub')>>>service.send_to_all(message=io.StringIO('Hello World'),content_type='application/octet-stream')The WebSocket client will receive binary text:b'Hello world'.TroubleshootingLoggingThis SDK uses Python standard logging library.
You can configure logging print out debugging information to the stdout or anywhere you want.importsysimportloggingfromazure.identityimportDefaultAzureCredential>>>fromazure.messaging.webpubsubserviceimportWebPubSubServiceClient# Create a logger for the 'azure' SDKlogger=logging.getLogger('azure')logger.setLevel(logging.DEBUG)# Configure a console outputhandler=logging.StreamHandler(stream=sys.stdout)logger.addHandler(handler)endpoint="<endpoint>"credential=DefaultAzureCredential()# This WebPubSubServiceClient will log detailed information about its HTTP sessions, at DEBUG levelservice=WebPubSubServiceClient(endpoint=endpoint,hub='hub',credential=credential,logging_enable=True)Similarly,logging_enablecan enable detailed logging for a single call,
even when it isn't enabled for the WebPubSubServiceClient:result=service.send_to_all(...,logging_enable=True)Http request and response details are printed to stdout with this logging config.Next stepsCheckmore samples here.ContributingThis project welcomes contributions and suggestions. Most contributions require
you to agree to a Contributor License Agreement (CLA) declaring that you have
the right to, and actually do, grant us the rights to use your contribution.
For details, visithttps://cla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether
you need to provide a CLA and decorate the PR appropriately (e.g., label,
comment). Simply follow the instructions provided by the bot. You will only
need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct. For more information,
see the Code of Conduct FAQ or contactopencode@microsoft.comwith any
additional questions or comments.