Python API & SDK Docs 10.4.1

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

  • Setting up a connection
  • Sending messages
  • Receiving messages in real-time

Overview

This guide will help you get up and running with PubNub in your Python application. The Python SDK provides a simple interface for integrating PubNub's real-time messaging capabilities into your applications. Whether you're building a web service, desktop application, or IoT device, this guide will show you how to get started.

Prerequisites

Before we dive in, make sure you have:

  • A basic understanding of Python
  • Python 3.9 or later installed
  • A PubNub account (we'll help you set this up!)

Setup

Get your PubNub keys

First, get your PubNub keys:

  • Sign in or create an account on the PubNub Admin Portal.
  • Create an app (or use an existing one).
  • Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

Install the SDK

SDK version

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

There are several ways to install the PubNub Python SDK:

Use pip

To integrate PubNub into your project using pip:

1pip install 'pubnub>=10.4.1'

Source code

You can also download the source code directly from the Python SDK repository.

View the supported platforms for more information about compatibility.

Steps

Initialize PubNub

In the IDE of your choice, create a new Python script with the following content. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to 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)

For more information, refer to the Configuration section of the SDK documentation.

Set up event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

The Python SDK provides a way to handle connection status changes using a listener. Add the following 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 # We're not implementing the message handler here as we'll use a subscription-specific handler
10
11# Add the listener to your PubNub instance
12status_listener = StatusListener()
13pubnub.add_listener(status_listener)

For more information, refer to the Listeners section of the SDK documentation.

Create a subscription

To receive messages sent to a particular channel, you need to subscribe to it. This is done by creating a subscription and activating it:

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}')

The SDK offers multiple ways to handle incoming messages, but using a subscription-specific handler (as shown above) is the recommended approach for most applications.

For more information, refer to the Subscribe section of the SDK documentation.

Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

1import time
2from pubnub.exceptions import PubNubException
3
4# Wait for a moment to ensure 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 makes the call synchronously, meaning it will wait for the response before proceeding. For asynchronous calls, you can use future() or async() depending on your application needs.

Run the app

To test the code, save it as pubnub_demo.py and run it from your terminal:

python pubnub_demo.py

When you run the application, you should see output similar to the following:

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

Note that you receive the message you just published because you're subscribed to the same channel.

Complete example

Here's the complete working example that puts everything together.

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 58 lines

Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

IssuePossible Solutions
No connection message
  • Check your internet connection.
  • Verify your publish and subscribe keys are correct.
  • Make sure you're not behind a firewall blocking PubNub's connections.
Message not received
  • Double-check that you're subscribed to the correct channel.
  • Verify that the message was actually sent (check for any error messages).
  • Make sure you're waiting long enough for the message to be delivered.
Import errors
  • Ensure you've installed the PubNub package correctly.
  • Check that you're using a compatible version of Python.
  • Make sure all imports are correct.

For more detailed troubleshooting information, refer to the Troubleshooting section of the SDK documentation.

Next steps

Great job! 🎉 You've successfully created your first PubNub application with Python. Here are some exciting things you can explore next:

  • Add Channel Groups to organize your channels.
  • Implement typing indicators and read receipts.
Last updated on