Ably Python SDK
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
- breaking Version 3.0.0 introduced significant breaking changes, notably adding full Realtime publish support, presence, and mutable messages over WebSockets. This brings Python to feature parity with other SDKs but requires migration for users upgrading from v2.x or earlier, which had limited Realtime capabilities or required an MQTT adapter.
- gotcha Using raw API keys directly in your application code, especially in production, is a security risk. API keys in quickstarts are for demonstration purposes only.
- gotcha Versions of the SDK prior to `3.1.2` (including `2.1.4`) had a bug where message 'extras' (metadata) might not be preserved correctly in message update methods, potentially leading to data loss. [v3.1.2 release notes]
- gotcha Older versions of the SDK (e.g., prior to `3.1.1` and `2.1.4`) contained issues with handling normal WebSocket close frames and improving reconnection logic, which could lead to unexpected connection drops or delayed re-establishment. [v3.1.1 release notes, v2.1.4 release notes]
Install
-
pip install ably
Imports
- AblyRealtime
from ably import AblyRealtime
- AblyRest
from ably import AblyRest
Quickstart
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())