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

Quickstart: PubNub Python SDK

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

To set up a virtual environment or install from source instead, refer to Set up your Python environment.

Before you begin​

You need Python 3.9 or later 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>=10.9.1'

Initialize​

Create a new Python script with the following content. This is the minimum configuration for sending and receiving messages.

Replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

1# Import required modules
2from pubnub.pnconfiguration import PNConfiguration
3from pubnub.pubnub import PubNub
4
5# Set up PubNub configuration
6pnconfig = PNConfiguration()
7pnconfig.subscribe_key = 'demo' # Replace with your subscribe key
8pnconfig.publish_key = 'demo' # Replace with your publish key
9pnconfig.user_id = 'python-user'
10pnconfig.enable_subscribe = True
11
12# Create a PubNub instance
13pubnub = PubNub(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, the PubNub constructor raises an AssertionError.

See the Configuration section of the SDK documentation.

Subscribe​

Listeners let your app react to events and messages. The Python SDK reports connection status changes to a listener. Add this code to set up a status listener:

1from pubnub.pubnub import SubscribeListener
2
3# Create a custom listener for status events
4class StatusListener(SubscribeListener):
5 def status(self, pubnub, status):
6 # This method is called when the status of the connection changes
7 print(f'Status: {status.category.name}')
8
9# Add the listener to your PubNub instance
10status_listener = StatusListener()
11pubnub.add_listener(status_listener)

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

1# Define the channel you want to subscribe to
2my_channel = 'my-channel'
3
4# Create a subscription for the channel
5subscription = pubnub.channel(my_channel).subscription()
6
7# Set up a message handler
8subscription.on_message = lambda message: print(f'Message received: {message.message}')
9
10# Subscribe to the channel
11subscription.subscribe()
12
13print(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.

1import time
2from pubnub.exceptions import PubNubException
3
4# Wait for a moment so the subscription is active
5time.sleep(1)
6
7# Create a message
8message = {
9 'msg': 'Hello from PubNub Python SDK!'
10}
11
12# Publish the message to the channel
13try:
14 envelope = pubnub.publish().channel(my_channel).message(message).sync()
15 print(f'Published message with timetoken: {envelope.result.timetoken}')
show all 17 lines

The sync() method waits for the response before the script continues. For other ways to run a request, see Publish.

Run​

The script below combines the code from the previous steps. Save it as pubnub_demo.py, replace the placeholder keys, and run it from your terminal:

1import time
2from pubnub.pnconfiguration import PNConfiguration
3from pubnub.pubnub import PubNub, SubscribeListener
4from pubnub.exceptions import PubNubException
5
6# Step 1: Initialize PubNub with configuration
7pnconfig = PNConfiguration()
8pnconfig.subscribe_key = 'demo' # Replace with your subscribe key
9pnconfig.publish_key = 'demo' # Replace with your publish key
10pnconfig.user_id = 'python-user'
11pnconfig.ssl = True # Enable SSL for secure connection
12pnconfig.enable_subscribe = True
13pnconfig.daemon = True # If using in a long-running app
14
15pubnub = PubNub(pnconfig)
show all 56 lines
python pubnub_demo.py

The script prints output similar to this:

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

You receive the message you published because you are subscribed to the same channel.

If the output differs, see Troubleshooting. If it shows a 403 (Access Denied) error, your keyset may have Access Manager enabled. See Configure access control.

Next steps​

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

Was this page useful?

Last updated on