Skip to main content

Microsoft Azure WebPubSub Service Client Library for Python

Project description

Azure Web PubSub service client library for Python

Azure Web PubSub Service is 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:

overflow

Use this library to:

  • Send messages to hubs and groups.
  • Send messages to particular users and connections.
  • Organize users and connections into groups.
  • Close connections
  • Grant, revoke, and check permissions for an existing connection

Source code | Package (Pypi) | API reference documentation | Product documentation

Disclaimer

Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691

Getting started

Prerequisites

1. Install the package

python -m pip install azure-messaging-webpubsubservice

2. Create and authenticate a WebPubSubServiceClient

You can authenticate the WebPubSubServiceClient using connection string:

>>> from azure.messaging.webpubsubservice import WebPubSubServiceClient

>>> service = WebPubSubServiceClient.from_connection_string(connection_string='<connection_string>', hub='hub')

Or using the service endpoint and the access key:

>>> from azure.messaging.webpubsubservice import WebPubSubServiceClient
>>> from azure.core.credentials import AzureKeyCredential

>>> service = WebPubSubServiceClient(endpoint='<endpoint>', hub='hub', credential=AzureKeyCredential("<access_key>"))

Or using Azure Active Directory:

  1. pip install azure-identity

  2. Follow the document to enable AAD authentication on your Webpubsub resource

  3. Update code to use DefaultAzureCredential

    >>> from azure.messaging.webpubsubservice import WebPubSubServiceClient
    >>> from azure.identity import DefaultAzureCredential
    >>> service = WebPubSubServiceClient(endpoint='<endpoint>', hub='hub', credential=DefaultAzureCredential())
    

Key concepts

Connection

A 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.

Hub

A 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.

Group

A 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.

User

Connections 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.

Message

When the client is connected, it can send messages to the upstream application, or receive messages from the upstream application, through the WebSocket connection.

Examples

Broadcast messages in JSON format

>>> from azure.messaging.webpubsubservice import WebPubSubServiceClient

>>> 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

>>> from azure.messaging.webpubsubservice import WebPubSubServiceClient
>>> 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

>>> import io
>>> from azure.messaging.webpubsubservice import WebPubSubServiceClient
>>> 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'.

Troubleshooting

Logging

This SDK uses Python standard logging library. You can configure logging print out debugging information to the stdout or anywhere you want.

import sys
import logging
from azure.identity import DefaultAzureCredential
>>> from azure.messaging.webpubsubservice import WebPubSubServiceClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

endpoint = "<endpoint>"
credential = DefaultAzureCredential()

# This WebPubSubServiceClient will log detailed information about its HTTP sessions, at DEBUG level
service = WebPubSubServiceClient(endpoint=endpoint, hub='hub', credential=credential, logging_enable=True)

Similarly, logging_enable can 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 steps

Check more samples here.

Contributing

This 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, visit https://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 the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure-messaging-webpubsubservice-1.0.1.zip (64.0 kB view details)

Uploaded Source

Built Distribution

File details

Details for the file azure-messaging-webpubsubservice-1.0.1.zip.

File metadata

  • Download URL: azure-messaging-webpubsubservice-1.0.1.zip
  • Upload date:
  • Size: 64.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.10.2

File hashes

Hashes for azure-messaging-webpubsubservice-1.0.1.zip
Algorithm Hash digest
SHA256 70915a477debda0f10bd947a9e879840b7e8a19966e678a9e61fcc79d0f8aa63
MD5 60270bd9afaac8deae53bade35a63ea6
BLAKE2b-256 6fd229815d91ed5ace96562c26af64c909e44e81c2e5c90aad6e57ff84bc27eb

See more details on using hashes here.

File details

Details for the file azure_messaging_webpubsubservice-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: azure_messaging_webpubsubservice-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 32.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.10.2

File hashes

Hashes for azure_messaging_webpubsubservice-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b5173fa300614bfdcee478251276d6da108ac51039301286bd2edbfcd8f37eee
MD5 9b82058d1206662fa622add9e5ef74d2
BLAKE2b-256 f30f0a97054ec814e3bbd463ca9f19db0e8bce34263010a92152fa32b1fb9094

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page