PubNub Python SDK 7.4.2

This page outlines the steps to follow to create a simple Hello, World application with PubNub. This covers the basics of integrating PubNub in your application: setting up a connection to PubNub, and sending and receiving messages.

  1. PubNub account
  2. Download the SDK
  3. Send messages

PubNub account

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Use pip

To integrate PubNub into your project using pip:

pip install 'pubnub>=7.4.2'

Get the source code

https://github.com/pubnub/python/

View the supported platforms here.

Configure PubNub

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

Make sure to replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the Admin Portal.

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()

pnconfig.subscribe_key = 'mySubscribeKey'
pnconfig.publish_key = 'myPublishKey'
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)

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

Add 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.

Copy the following code to configure your app such that when it receives an event of type PNConnectedCategory, it calls the publish() function. Additionally, the code below prints out the content of every received message.

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory, PNOperationType

def my_publish_callback(envelope, status):
# Check whether request successfully completed or not
if not status.is_error():
pass # Message successfully published to specified channel.
else:
pass # Handle message publish error. Check 'category' property to find out possible issue
# because of which request did fail.
# Request can be resent using: [status retry];

class MySubscribeCallback(SubscribeCallback):
def presence(self, pubnub, presence):
pass # handle incoming presence data
show all 38 lines

To easily terminate the subscribe loop and Python interpreter, you can call os._exit(0).

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

Publish and subscribe

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

In this app, publishing a message is triggered when the status listener you created in the previous step receives the PNConnectedCategory event.

To subscribe, you send a subscribe() call.

pubnub.subscribe().channels('my_channel').execute()

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Putting it all together

Your App class should now look similar to the following:

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory, PNOperationType
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()

pnconfig.subscribe_key = 'mySubscribeKey'
pnconfig.publish_key = 'myPublishKey'
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)

def my_publish_callback(envelope, status):
# Check whether request successfully completed or not
if not status.is_error():
show all 49 lines

Now, run your app to see if you did everything correctly. You should see the "Hello world" message in the console.

Congratulations! You've just subscribed to a channel and sent your first message.

Walkthrough

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:

  • configures a PubNub connection
  • adds the status and message event listeners
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration you need to send and receive messages with PubNub. For more information, refer to the Configuration section of the SDK documentation.

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()

pnconfig.subscribe_key = 'mySubscribeKey'
pnconfig.publish_key = 'myPublishKey'
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)

Add 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.

You added three listeners to the app: presence, status and message. Presence listens for presence events, but in this case, it is a no operation listener. Status listens for status events and when it receives an event of type PNConnectedCategory, it publishes the message. The other listener, message, listens for incoming messages on a particular channel. When it receives a message, the app simply prints the received message. This is why you see "Hello, World" displayed in the console.

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory, PNOperationType

class MySubscribeCallback(SubscribeCallback):
def presence(self, pubnub, presence):
pass # handle incoming presence data

def status(self, pubnub, status):
if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
pass # This event happens when radio / connectivity is lost

elif status.category == PNStatusCategory.PNConnectedCategory:
# Connect event. You can do stuff like publish, and know you'll get it.
# Or just use the connected event to confirm you are subscribed for
# UI / internal notifications, etc
show all 30 lines

To easily terminate the subscribe loop and Python interpreter, you can call os._exit(0).

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

Publishing and subscribing

PubNub uses the Publish/Subscribe model for real-time communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named my_channel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

When your app successfully connects to a channel, it calls the publish() method, which sends the "Hello World" message. This behavior is configured in the status listener.

pubnub.publish().channel('my_channel').message('Hello world!').pn_async(my_publish_callback)

You can subscribe to more than one channel with a single subscribe call but in this example, you subscribe to a single channel:

pubnub.subscribe().channels('my_channel').execute()

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Next steps

You have just learned how to use the Python SDK to send and receive messages using PubNub. Next, take a look at the SDK's reference documentation which covers PubNub API in more detail.

Last updated on