Ably Python SDK

3.1.2 · active · verified Sun Apr 12

The Ably Python SDK provides a client library for the Ably realtime messaging service, enabling developers to build applications with features like Pub/Sub messaging, presence, and message history. Currently at version 3.1.2, it's an actively developed library with frequent patch releases, designed to offer high performance, reliability, and scalability, including support for production AI infrastructure.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to Ably using the `AblyRealtime` client, subscribe to a channel, and publish a message. It leverages Python's `asyncio` for asynchronous operations. Remember to replace the placeholder API key with your actual Ably API key, ideally retrieved from an environment variable for production applications.

import asyncio
import os
from ably import AblyRealtime

async def main():
    api_key = os.environ.get('ABLY_API_API_KEY', 'your_ably_api_key:YOUR_SECRET_KEY')
    if api_key == 'your_ably_api_key:YOUR_SECRET_KEY':
        print("WARNING: Replace 'your_ably_api_key:YOUR_SECRET_KEY' with your actual Ably API key or set ABLY_API_API_KEY environment variable.")
        print("You can obtain a demo key from your Ably dashboard (https://ably.com/dashboard).")

    async with AblyRealtime(api_key, client_id='my-python-client') as ably_realtime:
        # Wait for connection to be established
        await ably_realtime.connection.once_async('connected')
        print('Connected to Ably!')

        channel = ably_realtime.channels.get('my-test-channel')

        # Subscribe to messages
        def on_message(message):
            print(f"Received message: {message.data}")

        await channel.subscribe_async(on_message)
        print("Subscribed to 'my-test-channel'")

        # Publish a message
        await channel.publish('greeting', 'Hello from Ably Python SDK!')
        print("Published 'Hello from Ably Python SDK!' to 'my-test-channel'")

        # Keep the connection open for a bit to receive the message
        await asyncio.sleep(5)


if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →