ably-python
Overview
This is a Python client library for Ably. The library currently targets the Ably 1.1 client library specification.
Running example
import asyncio
from ably import AblyRest
async def main():
async with AblyRest('api:key') as ably:
channel = ably.channels.get("channel_name")
if __name__ == "__main__":
asyncio.run(main())
Installation
The client library is available as a PyPI package.
From PyPI
pip install ably
Or, if you need encryption features:
pip install 'ably[crypto]'
Locally
git clone https://github.com/ably/ably-python.git
cd ably-python
python setup.py install
Breaking API Changes in Version 1.2.x
Please see our Upgrade / Migration Guide for notes on changes you need to make to your code to update it to use the new API introduced by version 1.2.x
Usage
All examples assume a client and/or channel has been created in one of the following ways:
With closing the client manually:
from ably import AblyRest
async def main():
client = AblyRest('api:key')
channel = client.channels.get('channel_name')
await client.close()
When using the client as a context manager, this will ensure that client is properly closed
while leaving the with
block:
from ably import AblyRest
async def main():
async with AblyRest('api:key') as ably:
channel = ably.channels.get("channel_name")
You can define the logging level for the whole library, and override for a specific module:
import logging
import ably
logging.getLogger('ably').setLevel(logging.WARNING)
logging.getLogger('ably.rest.auth').setLevel(logging.INFO)
You need to add a handler to see any output:
logger = logging.getLogger('ably')
logger.addHandler(logging.StreamHandler())
Publishing a message to a channel
await channel.publish('event', 'message')
Querying the History
message_page = await channel.history() # Returns a PaginatedResult
message_page.items # List with messages from this page
message_page.has_next() # => True, indicates there is another page
next_page = await message_page.next() # Returns a next page
next_page.items # List with messages from the second page
Current presence members on a channel
members_page = await channel.presence.get() # Returns a PaginatedResult
members_page.items
members_page.items[0].client_id # client_id of first member present
Querying the presence history
presence_page = await channel.presence.history() # Returns a PaginatedResult
presence_page.items
presence_page.items[0].client_id # client_id of first member
Symmetric end-to-end encrypted payloads on a channel
When a 128 bit or 256 bit key is provided to the library, all payloads are encrypted and decrypted automatically using that key on the channel. The secret key is never transmitted to Ably and thus it is the developer's responsibility to distribute a secret key to both publishers and subscribers.
key = ably.util.crypto.generate_random_key()
channel = rest.channels.get('communication', cipher={'key': key})
channel.publish(u'unencrypted', u'encrypted secret payload')
messages_page = await channel.history()
messages_page.items[0].data #=> "sensitive data"
Generate a Token
Tokens are issued by Ably and are readily usable by any client to connect to Ably:
token_details = await client.auth.request_token()
token_details.token # => "xVLyHw.CLchevH3hF....MDh9ZC_Q"
new_client = AblyRest(token=token_details)
await new_client.close()
Generate a TokenRequest
Token requests are issued by your servers and signed using your private API key. This is the preferred method of authentication as no secrets are ever shared, and the token request can be issued to trusted clients without communicating with Ably.
token_request = await client.auth.create_token_request(
{
'client_id': 'jim',
'capability': {'channel1': '"*"'},
'ttl': 3600 * 1000, # ms
}
)
# => {"id": ...,
# "clientId": "jim",
# "ttl": 3600000,
# "timestamp": ...,
# "capability": "{\"*\":[\"*\"]}",
# "nonce": ...,
# "mac": ...}
new_client = AblyRest(token=token_request)
await new_client.close()
Fetching your application's stats
stats = await client.stats() # Returns a PaginatedResult
stats.items
await client.close()
Fetching the Ably service time
await client.time()
await client.close()
Resources
Visit https://www.ably.io/documentation for a complete API reference and more examples.
Requirements
This SDK supports Python 3.5+.
We regression-test the SDK against a selection of Python versions (which we update over time, but usually consists of mainstream and widely used versions). Please refer to check.yml for the set of versions that currently undergo CI testing.
Known Limitations
Currently, this SDK only supports Ably REST. However, you can use the MQTT adapter to implement Ably's Realtime features using Python.
Support, Feedback and Troubleshooting
If you find any compatibility issues, please do raise an issue in this repository or contact Ably customer support for advice.
Support, feedback and troubleshooting
Please visit http://support.ably.io/ for access to our knowledge base and to ask for any assistance.
You can also view the community reported Github issues.
To see what has changed in recent versions of Bundler, see the CHANGELOG.
Contributing
For guidance on how to contribute to this project, see CONTRIBUTING.md