For AI agents: this page in Markdown: https://www.pubnub.com/docs/sdks/asyncio/quickstart.md. Documentation index: https://www.pubnub.com/llms-full.txt.

Quickstart: PubNub Python-Asyncio SDK

In this quickstart you write a "Hello, World" script. The script connects to PubNub, subscribes to a channel, and publishes a message that arrives in the same script. You need Python 3.9 or later and a single file.

For other install options, refer to Set up your Python-Asyncio environment.

Before you begin​

You need a basic understanding of Python and asyncio, and a PubNub account.

Get your PubNub keys​

Get your PubNub keys:

  • Sign in or create an account on the PubNub Admin Portal
  • Create an app
  • Find your publish and subscribe keys in the app dashboard

When you create an app, PubNub generates a keyset. Use separate keysets for development and production.

Install​

SDK version

Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.

Install the SDK with pip:

1pip install pubnub

Initialize​

Create a Python script named pubnub_asyncio_demo.py. Create the PubNubAsyncio client inside an async function, so that it uses the running event loop. Replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

1import asyncio
2from pubnub.exceptions import PubNubException
3from pubnub.pnconfiguration import PNConfiguration
4from pubnub.pubnub_asyncio import PubNubAsyncio, SubscribeListener
5
6
7async def main():
8 pnconfig = PNConfiguration()
9 pnconfig.subscribe_key = 'demo' # Replace with your subscribe key
10 pnconfig.publish_key = 'demo' # Replace with your publish key
11 pnconfig.user_id = 'asyncio-user'
12
13 pubnub = PubNubAsyncio(pnconfig)

Set the user_id to identify the user or device that connects to PubNub, and keep it unchanged for the lifetime of that user or device. Without a user_id, you can't connect to PubNub.

See the Configuration section of the SDK documentation.

Subscribe​

Listeners let your app react to events and messages. This status listener prints each connection status change. It extends SubscribeListener, which also lets the script wait until the client is connected.

1class StatusListener(SubscribeListener):
2 def status(self, pubnub, status):
3 super().status(pubnub, status)
4 print(f'Status: {status.category.name}')

Add the listener inside main(), below the client:

1    status_listener = StatusListener()
2 pubnub.add_listener(status_listener)

To receive messages on a channel, subscribe to it. Create a subscription for the channel, set a message handler, and activate the subscription:

1    my_channel = 'example'
2 subscription = pubnub.channel(my_channel).subscription()
3 subscription.on_message = lambda message: print(f'Message received: {message.message}')
4 subscription.subscribe()
5 print(f'Subscribed to channel: {my_channel}')

See the Subscribe section of the SDK documentation.

Publish​

When you publish a message to a channel, PubNub delivers it to every subscriber of that channel. A message can be any JSON-serializable data smaller than 32 KiB, such as an object, array, integer, or string.

Wait until the client is connected, then publish. Wait a few seconds for the message to arrive, then call await pubnub.stop() to close the client before the script exits.

1    await status_listener.wait_for_connect()
2
3 try:
4 result = await pubnub.publish().channel(my_channel).message({'msg': 'Hello from PubNub Python-Asyncio SDK!'}).result()
5 print(f'Published message with timetoken: {result.timetoken}')
6 except PubNubException as e:
7 print(f'Publish failed: {e}')
8
9 await asyncio.sleep(3)
10 await pubnub.stop()
11 print('Cleanup complete.')

See the Publish section of the SDK documentation.

Run​

The script below combines the code from the previous steps and starts the event loop with asyncio.run(). Save it as pubnub_asyncio_demo.py, replace the demo keys, and run it from your terminal:

python pubnub_asyncio_demo.py
1import asyncio
2from pubnub.exceptions import PubNubException
3from pubnub.pnconfiguration import PNConfiguration
4from pubnub.pubnub_asyncio import PubNubAsyncio, SubscribeListener
5
6
7class StatusListener(SubscribeListener):
8 def status(self, pubnub, status):
9 super().status(pubnub, status)
10 print(f'Status: {status.category.name}')
11
12
13async def main():
14 pnconfig = PNConfiguration()
15 pnconfig.subscribe_key = 'demo' # Replace with your subscribe key
show all 44 lines

The script prints output similar to this:

Subscribed to channel: example
Status: PNConnectedCategory
Published message with timetoken: 16967543908123456
Message received: {'msg': 'Hello from PubNub Python-Asyncio SDK!'}
Cleanup complete.

You receive the message you published because the client subscribes to the same channel. The order of the Published and Message received lines can differ.

If the message does not arrive, see Troubleshooting. If the script prints a 403 (Access Denied) error, your keyset may have Access Manager enabled. Check that your token has read permissions for the subscribed channel. See Configure access control.

Next steps​

You created your first PubNub Python-Asyncio application. Here is what to explore next:

Was this page useful?

Last updated on