Python Quickstart
In this Quickstart, you'll learn how to build your first Python app that sends and receives messages, and how to use status and presence events to enhance your realtime application.
Sample App Quickstart | SDK Getting Started |
---|---|
PubNub Account
Sign in or create an account to create an app on the Admin Portal and get the keys you'll need for this Quickstart.
Download Sample App
You can clone the repository that contains the files we will use in this Quickstart. Remember to replace the publish and subscribe key placeholders with your own keys.
https://github.com/pubnub/python-quickstart-platform
Project Setup
This Quickstart project will consist of two Python scripts: one for the publisher (sender) and one for the subscriber (receiver):
Create a new folder for your Python scripts.
Create two new files in that folder with the names
pub.py
andsub.py
.Install the PubNub Python SDK using
pip
:pip install 'pubnub>=4.5.1'
Update Project Files
Add the following files in your project:
Open the
pub.py
file and add the following code:from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub ENTRY = "Earth" CHANNEL = "the_guide" the_update = None pnconfig = PNConfiguration() pnconfig.publish_key = "myPublishKey" pnconfig.subscribe_key = "mySubscribeKey" pnconfig.uuid = "serverUUID-PUB" pubnub = PubNub(pnconfig) print("*****************************************") print("* Submit updates to The Guide for Earth *") print("* Enter 42 to exit this process *") print("*****************************************") while the_update != "42": print the_update = input("Enter an update for Earth: ") the_message = {"entry": ENTRY, "update": the_update} envelope = pubnub.publish().channel(CHANNEL).message(the_message).sync() if envelope.status.is_error(): print("[PUBLISH: fail]") print("error: %s" % status.error) else: print("[PUBLISH: sent]") print("timetoken: %s" % envelope.result.timetoken)
Replace Pub/Sub Key Placeholders
Remember to replace the myPublishKey and mySubscribeKey placeholders with your own PubNub publish and subscribe keys.
Open the
sub.py
file and add the following code:import os from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub ENTRY = "Earth" CHANNEL = "the_guide" pnconfig = PNConfiguration() pnconfig.publish_key = "myPublishKey" pnconfig.subscribe_key = "mySubscribeKey" pnconfig.uuid = "serverUUID-SUB" pubnub = PubNub(pnconfig) class MySubscribeCallback(SubscribeCallback): def presence(self, pubnub, event): print("[PRESENCE: {}]".format(event.event)) print("uuid: {}, channel: {}".format(event.uuid, event.channel)) def status(self, pubnub, event): if event.category == PNStatusCategory.PNConnectedCategory: print("[STATUS: PNConnectedCategory]") print("connected to channels: {}".format(event.affected_channels)) def message(self, pubnub, event): print("[MESSAGE received]") if event.message["update"] == "42": print("The publisher has ended the session.") os._exit(0) else: print("{}: {}".format(event.message["entry"], event.message["update"])) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels(CHANNEL).with_presence().execute() print("***************************************************") print("* Waiting for updates to The Guide about {}... *".format(ENTRY)) print("***************************************************")
Run the Project
1. Start the subscriber process To run the subscriber script from the command line, enter: python sub.py You should see a message that it's waiting for updates. The subscriber process is implemented to receive updates from the publisher process, so there will be no further command line input for this process. A status and presence event is displayed which confirms that the process has successfully subscribed to the channel. 2. Start the publisher process Open another terminal window to run the publisher script: python pub.py .You should see a message that informs you how to exit the process and a prompt that awaits your next update. Enter "Harmless" (without the quotes) and hit the Enter key to submit that update. You'll also see the new update appear in the subscriber terminal. 3. Exit the process When you're finished submitting entries, you can enter "42" (without the quotes) to exit the publisher script. You'll notice that it also forces the subscriber script to exit. | ![]() ![]() |
Walkthrough
Let's review exactly what's happening for all this to work.
Install PubNub SDK
Using pip
, you installed the latest PubNub Python SDK. This enables the server to run scripts that will include PubNub code.
For the latest version, refer to the Python SDK documentation.
Subscriber Code Overview
The subscribe call is a blocking call (a connection is held open awaiting response), meaning you're unable to do anything else in this script. You can use Python asyncio cooperative multitasking library or spawn separate thread or process if you require different scenarios. Refer to the PubNub Python Asyncio SDK docs for more details.
Here is an overview of what's happening in the sub.py
script:
Imports
The import os
is specifically for the os._exit(0)
call that kills the process returning you to the command line.
The rest of the imports
are required to use different APIs of the PubNub Python SDK.
Initialize the PubNub Object
Using your own PubNub keys, you can configure and initialize a pubnub
object. This object allows you to make PubNub API calls, like addListener
and subscribe
. There are more configuration properties than what you see here, but this is all you need for this Quickstart.
pnconfig = PNConfiguration()
pnconfig.publish_key = "demo-36"
pnconfig.subscribe_key = "demo-36"
pnconfig.uuid = "serverUUID-SUB"
pubnub = PubNub(pnconfig)
PubNub Keys and UUID
When initializing PubNub inside server processes, you would typically include the PubNub keys and the UUID in a configuration file that the process reads at script startup. For secure servers, you would also include your PubNub secret key when you initialize PubNub.
Listen for Messages & Events
The SubscribeCallback
code has handler
functions where all published messages and other events are received. The SubscribeCallback is passed into the add_listener
function.
class MySubscribeCallback(SubscribeCallback):
def presence(self, pubnub, event):
"""handle presence events"""
def status(self, pubnub, event):
"""handle status events"""
def message(self, pubnub, event):
"""handle message events"""
pubnub.add_listener(MySubscribeCallback())
In this app, you only need to be concerned with message
, status
and presence
event handlers. There are several other event handlers that have no implementation, but you can use them for other features of PubNub.
Receiving Messages
The message
handler receives all messages published to all channels subscribed to by this client. When a message is received, you're simply outputting it to the terminal.
def message(self, pubnub, event):
print("[MESSAGE received]")
if event.message["update"] == "42":
print "The publisher has ended the session."
os._exit(0)
else:
print("{}: {}".format(event.message["entry"], event.message["update"]))
If the value of the update
key is "42
", then the subscribe process exits returning command line control back to the operator.
Receiving Status Events
The status
event handler allows you to monitor and manage the connection to the PubNub Platform and channels. When the client subscribes to a channel, a PNConnectedCategory
status event will be received to indicate a successful channel connection. There is no specific requirement for it in this Quickstart, but it's a place where you can implement code that relies on successful channel subscription confirmation.
def status(self, pubnub, event):
if event.category == PNStatusCategory.PNConnectedCategory:
print("[STATUS: PNConnectedCategory]")
print("connected to channels: {}".format(event.affected_channels))
Receiving Presence Events
The presence
handler allows you to monitor when this and other clients join and leave channels.
To receive presence events on a channel, you call the subscribe
method with the withPresence
parameter. In this app, you'll only receive a join
event. If you then joined the same channel using another client (such as the PubNub Developer Console), you would see a join
event for that client, too. You'll see leave
events when another client unsubscribes from a channel, or a timeout
event if it goes offline without first unsubscribing.
def presence(self, pubnub, event):
print("[PRESENCE: {}]".format(event.event))
print("uuid: {}, channel: {}".format(event.uuid, event.channel))
Subscribe to a Channel
This subscribe
opens a connection to PubNub and waits for messages to be publish
-ed to this channel. You can subscribe to more than one channel at a time but you only need the one for this Quickstart. The withPresence()
function enables presence events to be sent for the channel being subscribed to in this call.
pubnub.subscribe().channels(CHANNEL).with_presence().execute()
Publish Code Overview
In the publisher process, the call publish and the request are completed in a few milliseconds. The subscribe call is blocking and is constantly in flight, preventing the opportunity to make other calls while waiting for messages. Designing software using Python's concurrency techniques like Asyncio is one of the recommended solutions to solve this problem.
The publish process simply prompts for input and publishes whatever is entered at the command line and repeats this until the operator enters the exit command.
UUIDs
The imports and the configure and initialize code are the same as the subscriber process. The only thing worth noting is that the UUID for this publish process is different so that you're able to uniquely identify these two processes.
Here is an overview of what's happening in the pub.py
script:
Prompting for Input
This process prompts for operator input at the command line. When input is entered, it prompts for the next input. This repeats until the operator enters the special exit command, "42".
while the_update != "42":
the_update = input("Enter an update for Earth: ")
# more code goes here
When the operator enters "42", that value is published and received by the subscriber process which uses that value as a command to exit the process. This also satisfies the input prompt loop of the publisher process and ends it.
Publishing the Input
When the operator enters an update, you create a JSON payload that includes that input as the value of the "update"
key. Then, you publish that message to the channel which is received by the subscriber process. You also output the timetoken of the published message to the terminal before prompting for the next update.
the_message = {"entry": ENTRY, "update": the_update}
envelope = pubnub.publish().channel(CHANNEL).message(the_message).sync()
Next Steps
Now that you have a your Python app up and running with PubNub, learn more about what else you can do with Channels. To discover what else our Python SDK offers, go to our Python SDK Reference.