Getting started: Pub/Sub in Python

This guide will get you started with Ably Pub/Sub in Python.

It will take you through the following steps:

  • Create a client and establish a realtime connection to Ably.
  • Attach to a channel and subscribe to its messages.
  • Publish a message to the channel for your client to receive.
  • Join and subscribe to the presence set of the channel.
  • Retrieve the messages you sent in the guide from history.
  • Close a connection to Ably when it is no longer needed.

  • Sign up for an Ably account.
    • Create a new app, and create your first API key.
    • Your API key will need the publish, subscribe, presence and history capabilities.
  • Install the Ably CLI:
npm install -g @ably/cli
Copied!
  • Run the following to log in to your Ably account and set the default app and API key:
ably login ably apps switch ably auth keys switch
Copied!
  • Install Python version 3.8 or greater.
  • Create a new project and install the Ably Pub/Sub Python SDK:
# Create a new directory for your project mkdir ably-python-quickstart cd ably-python-quickstart # Create a virtual environment (recommended) python -m venv venv source venv/bin/activate # On Windows use: venv\Scripts\activate # Install the Ably SDK pip install ably
Copied!

Clients establish a connection with Ably when they instantiate an SDK instance. This enables them to send and receive messages in realtime across channels.

  • Create a get_started.py file in your project and add the following function to instantiate the SDK and establish a connection to Ably. At the minimum you need to provide an authentication mechanism. Use an API key for simplicity, but you should use token authentication in a production app. A client_id ensures the client is identified, which is required to use certain features, such as presence:
Python v2
import asyncio from ably import AblyRealtime async def get_started(): # Initialize the Ably Realtime client async with AblyRealtime("<loading API key, please wait>", client_id="my-first-client") as ably_realtime: def on_state_change(state_change): if state_change.current.value == "connected": print("Made my first connection!") ably_realtime.connection.on(on_state_change) await ably_realtime.connection.once_async("connected") await asyncio.Event().wait() asyncio.run(get_started())
Demo Only
Copied!

The Python SDK uses asyncio to provide asynchronous operations. This allows the client to handle events such as connection state changes, message receipt, and presence updates without blocking the main thread.

You can monitor the lifecycle of clients’ connections by registering a listener that will emit an event every time the connection state changes. For now, run the function with python get_started.py to log a message to the console to know that the connection attempt was successful. You’ll see the message printed to your console, and you can also inspect the connection event in the dev console of your app.

Messages contain the data that a client is communicating, such as a short ‘hello’ from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to.

  • Add the following lines to your get_started function before the await asyncio.Event().wait() line to create a channel instance and register a listener to subscribe to the channel. Then run it with python get_started.py:
Python v2
# Get a channel instance channel = ably_realtime.channels.get("my-first-channel") # Subscribe to messages on the channel def on_message(message): print(f"Received message: {message.data}") await channel.subscribe(on_message)
Copied!
  • Use the Ably CLI to publish a message to your first channel. The message will be received by the client you’ve subscribed to the channel, and be logged to the console.
ably channels publish my-first-channel 'Hello!'
Copied!
  • In a new terminal tab, subscribe to the same channel using the CLI:
ably channels subscribe my-first-channel
Copied!

Publish another message using the CLI and you will see that, in your other Terminal window, it’s received instantly by the client you have running locally, as well as the subscribed terminal instance.

To publish a message with the client running in your IDE, you can add the following line to your get_started function before the await asyncio.Event().wait() line:

Python v2
await channel.publish("example", "A message sent from my first client!")
Copied!

Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline. With the Python SDK you can retrieve the presence set but cannot enter it. This means you can see who is present on a channel, but you cannot announce your own presence from a Python client.

  • Have a client join the presence set using the Ably CLI:
ably channels presence enter my-first-channel --client-id "my-cli" --data '{"status":"learning about Ably!"}'
Copied!
  • Add the following lines to your get_started function before the await asyncio.Event().wait() line to retrieve the list of members in the presence set. Then run it with python get_started.py:
Python v2
members_page = await channel.presence.get() # Returns a PaginatedResult member_ids = [member.client_id for member in members_page.items] print(f"Members in presence set: {member_ids}")
Copied!

You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. This can be extended for longer if required.

If more than 2 minutes has passed since you published a regular message (excluding the presence events), then you can publish some more before trying out history. You can use the Pub/Sub SDK, Ably CLI or the dev console to do this.

For example, using the Ably CLI to publish 5 messages:

ably channels publish --count 5 my-first-channel "Message number {{.Count}}"
Copied!
  • Add the following lines to your get_started function before the await asyncio.Event().wait() line to retrieve any messages that were recently published to the channel. Then run it with python get_started.py:
Python v2
# Retrieve message history history = await channel.history() print([message.data for message in history.items])
Copied!

The output will look similar to the following:

[ 'Message number 5', 'Message number 4', 'Message number 3', 'Message number 2', 'Message number 1' ]
Copied!

Connections are automatically closed approximately 2 minutes after no heartbeat is detected by Ably. Explicitly closing connections when they are no longer needed is good practice to help save costs. It will also remove all listeners that were registered by the client.

Note that messages are streamed to clients as soon as they attach to a channel, as long as they have the necessary capabilities. Clients are implicitly attached to a channel when they call subscribe(). Detaching from a channel using the detach() method will stop the client from being streamed messages by Ably.

Listeners registered when subscribing to a channel are registered client-side. Unsubscribing by calling unsubscribe() will remove previously registered listeners for that channel. Detaching from a channel has no impact on listeners. As such, if a client reattaches to a channel that they previously registered listeners for, then those listeners will continue to function upon reattachment.

  • Update your on_state_change function to print a message when the connection is closed:
Python v2
def on_state_change(state_change): if state_change.current.value == "connected": print("Made my first connection!") elif state_change.current.value == "closed": print("Closed the connection to Ably!")
Copied!
  • Update the end of your get_started function replacing the existing await asyncio.Event().wait() line with the following:
Python v2
# Keep the connection open to process events await asyncio.sleep(10) await ably_realtime.close()
Copied!

Note that when using the async with context manager, the connection is automatically closed when exiting the context. The explicit close is shown here for educational purposes.

Continue to explore the documentation with Python as the selected language:

Read more about the concepts covered in this guide:

You can also explore the Ably CLI@ably/cli further.

Select...