Python-Asyncio API & SDK Docs 10.2.0
In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNubPubNub
PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including:
- Message delivery and persistence
- Presence detection
- Access control
- Push notifications
- File sharing
- Serverless processing with Functions and Events & Actions
- Analytics and monitoring with BizOps Workspace
- AI–powered insights with Illuminate
- 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 using the asyncio API. The Python-Asyncio SDK provides a simple interface for integrating PubNub's real-time messaging capabilities into asynchronous Python 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 and asyncio
- Python 3.9 or later installed
- A PubNub account (we'll help you set this up!)
Setup
Get your PubNub keys
First things first – you'll need your PubNub keys to get started. Here's how to get them:
- Sign in or create an account on the PubNub Admin Portal.
- Create a new app (or use an existing one).
- Find your publishand subscribe
Publish Key
A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.keys in the app's dashboard.Subscribe Key
A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.
When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better 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
:
pip install pubnub
Git
You can also clone the repository directly:
git clone https://github.com/pubnub/python
Source code
You can 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.
# Import required modules
import asyncio
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio
# Set up PubNub configuration
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo' # Replace with your subscribe key
pnconfig.publish_key = 'demo' # Replace with your publish key
pnconfig.user_id = 'asyncio-user'
# Create a PubNub instance
pubnub = PubNubAsyncio(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-Asyncio SDK provides a way to handle connection status changes using a listener. Add the following code to set up a status listener:
from pubnub.pubnub_asyncio import SubscribeListener
# Create a custom listener for status events
class StatusListener(SubscribeListener):
def status(self, pubnub, status):
# This method is called when the status of the connection changes
print(f'Status: {status.category.name}')
# We're not implementing the message handler here as we'll use a subscription-specific handler
# Add the listener to your PubNub instance
status_listener = StatusListener()
pubnub.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:
# Define the channel you want to subscribe to
my_channel = 'example'
# Create a subscription for the channel
subscription = pubnub.channel(my_channel).subscription()
# Set up a message handler
subscription.on_message = lambda message: print(f'Message received: {message.message}')
# Subscribe to the channel
subscription.subscribe()
print(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.
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 JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.
import asyncio
from pubnub.exceptions import PubNubException
async def publish_message():
# Wait for a moment to ensure the subscription is active
await asyncio.sleep(1)
# Create a message
message = {
'msg': 'Hello from PubNub Python-Asyncio SDK!'
}
try:
# Publish using result() which directly returns the result (or raises an exception)
result = await pubnub.publish().channel(my_channel).message(message).result()
show all 21 linesThe asyncio SDK provides two ways to handle callbacks:
- Using
result()
which returns just the result and raises exceptions directly - Using
future()
which returns an envelope with both result and status objects
Run the app
To test the code, save it as pubnub_asyncio_demo.py
and run it from your terminal:
python pubnub_asyncio_demo.py
When you run the application, you should see output similar to the following:
Subscribed to channel: example
Status: PNConnectedCategory
Message received: {'msg': 'Hello from PubNub Python-Asyncio 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.
import asyncio
from pubnub.exceptions import PubNubException
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio, SubscribeListener
# Step 1: Initialize PubNub with configuration
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo' # Replace with your subscribe key
pnconfig.publish_key = 'demo' # Replace with your publish key
pnconfig.user_id = 'asyncio-user'
pnconfig.ssl = True # Enable SSL for secure connection
pubnub = PubNubAsyncio(pnconfig)
# Step 2: Create a status listener
show all 68 linesTroubleshooting
If you don't see the expected output, here are some common issues and how to fix them:
Issue | Possible Solutions |
---|---|
No connection message |
|
Message not received |
|
Import errors |
|
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-Asyncio. Here are some exciting things you can explore next:
- Build chat
- Advanced features
- Real examples
- More help
- Implement user Presence to show who's online.
- Add Channel Groups to organize your channels.
- Implement typing indicators and read receipts.
- Try out Presence to track online/offline status.
- Implement Message Persistence to store and retrieve messages.
- Use Access Manager to secure your channels.
- Explore our GitHub repository for more code samples.
- Check out the Python SDK examples for practical examples.
- Check out our SDK reference documentation for detailed API information.
- Join our Discord community to connect with other developers.
- Visit our support portal for additional resources.
- Ask our AI assistant (the looking glass icon at the top of the page) for help.