title | description | author | ms.author | ms.service | ms.custom | ms.topic | ms.date |
---|---|---|---|---|---|---|---|
Reference - Python Client-side SDK for Azure Web PubSub | This reference describes the Python client-side SDK for Azure Web PubSub service. | vicancy | lianwei | azure-web-pubsub | devx-track-python | reference | 01/23/2024 |
Note
Details about the terms used here are described in key concepts article.
The client-side SDK aims to speed up developer's workflow; more specifically,
- simplifies managing client connections
- simplifies sending messages among clients
- automatically retries after unintended drops of client connection
- reliably deliveries messages in number and in order after recovering from connection drops
As shown in the diagram, your clients establish WebSocket connections with your Web PubSub resource.
:::image type="content" source="./media/reference-client-sdk-python/flow-overview.png" alt-text="Screenshot showing clients establishing WebSocket connection with a Web PubSub resource":::
- Python 3.8+
- An Azure subscription
- A Web PubSub resource
pip install azure-messaging-webpubsubclient
A client uses a Client Access URL
to connect and authenticate with the service, which follows a pattern of wss://<service_name>.webpubsub.azure.com/client/hubs/<hub_name>?access_token=<token>
. A client can have a few ways to obtain the Client Access URL
. For this quick start, you can copy and paste one from Azure portal shown.
:::image type="content" source="./media/reference-client-sdk-python/get-client-access-url.png" alt-text="Screenshot showing how to get Client Access Url on Azure portal":::
As shown in the diagram, the client has the permissions to send messages to and join a specific group named group1
.
fromazure.messaging.webpubsubclientimportWebPubSubClientclient=WebPubSubClient("<client-access-url>") withclient: # The client can join/leave groups, send/receive messages to and from those groups all in real-time ...
A client can only receive messages from groups that it has joined and you need to add a callback to specify the logic when receiving messages.
fromazure.messaging.webpubsubclient.modelsimportCallbackType# ...continues the code snippet from above# Registers a listener for the event 'group-message' early before joining a group to not miss messagesgroup_name="group1"; client.subscribe(CallbackType.GROUP_MESSAGE, lambdae: print(f"Received message: {e.data}")); # A client needs to join the group it wishes to receive messages fromclient.join_group(groupName);
# ...continues the code snippet from above# Send a message to a joined groupclient.send_to_group(group_name, "hello world", "text"); # In the Console tab of your developer tools found in your browser, you should see the message printed there.
When a client is successfully connected to your Web PubSub resource, the
connected
event is triggered.fromazure.messaging.webpubsubclient.modelsimportCallbackTypeclient.subscribe(CallbackType.CONNECTED, lambdae: print(f"Connection {e.connection_id} is connected"))
When a client is disconnected and fails to recover the connection, the
disconnected
event is triggered.fromazure.messaging.webpubsubclient.modelsimportCallbackTypeclient.subscribe(CallbackType.DISCONNECTED, lambdae: print(f"Connection disconnected: {e.message}"))
The
stopped
event is triggered when the client is disconnected and the client stops trying to reconnect. This usually happens after theclient.stop()
is called, orauto_reconnect
is disabled or a specified limit to trying to reconnect has reached. If you want to restart the client, you can callclient.start()
in the stopped event.fromazure.messaging.webpubsubclient.modelsimportCallbackTypeclient.subscribe(CallbackType.STOPPED, lambda : print("Client has stopped"))
A client can add callbacks to consume messages from your application server or groups. Note, for group-message
event the client can only receive group messages that it has joined.
fromazure.messaging.webpubsubclient.modelsimportCallbackType# Registers a listener for the "server-message". The callback is invoked when your application server sends message to the connectionID, to or broadcast to all connections.client.subscribe(CallbackType.CONNECTED, lambdae: print(f"Received message {e.data}")) # Registers a listener for the "group-message". The callback is invoked when the client receives a message from the groups it has joined.client.subscribe(CallbackType.GROUP_MESSAGE, lambdae: print(f"Received message from {e.group}: {e.data}"))
When a client is disconnected and fails to recover, all group contexts are cleaned up in your Web PubSub resource. This means when the client reconnects, it needs to rejoin groups. By default, the client has auto_rejoin_groups
option enabled.
However, you should be aware of auto_rejoin_groups
's limitations.
- The client can only rejoin groups that it's originally joined by the client code not by the server side code.
- "rejoin group" operations may fail due to various reasons, for example, the client doesn't have permission to join the groups. In such cases, you need to add a callback to handle this failure.
fromazure.messaging.webpubsubclient.modelsimportCallbackType# By default auto_rejoin_groups=True. You can disable it by setting to False.client=WebPubSubClient("<client-access-url>", auto_rejoin_groups=True); # Registers a listener to handle "rejoin-group-failed" eventclient.subscribe(CallbackType.REJOIN_GROUP_FAILED, lambdae: print(f"Rejoin group {e.group} failed: {e.error}"))
By default, the operation such as client.join_group()
, client.leave_group()
, client.send_to_group()
, client.send_event()
has three retries. You can configure through the key-word arguments. If all retries have failed, an error is thrown. You can keep retrying by passing in the same ack_id
as previous retries so that the Web PubSub service can deduplicate the operation.
try: client.join_group(group_name) exceptSendMessageErrorase: client.join_group(group_name, ack_id=e.ack_id)
You can set the following environment variable to get the debug logs when using this library.
export AZURE_LOG_LEVEL=verbose
For more detailed instructions on how to enable logs, you can look at the @azure/logger package docs.
Use Live Trace tool from Azure portal to inspect live message traffic through your Web PubSub resource.