Troubleshoot the PubNub Python SDK

This page shows how to find your PubNub Python SDK version and handle errors.

How to find the version of your SDK​

Access your SDK version via constant​

The following snippet prints the SDK version from the PubNub class.

Steps to access the SDK version​

  1. Import the required modules.
  2. Retrieve the version with PubNub.SDK_VERSION.
  3. Log or print the version for future reference.
1import os
2from pubnub.pnconfiguration import PNConfiguration
3from pubnub.pubnub import PubNub
4
5def main():
6 # Display the current SDK version
7 print(f"Current PubNub SDK Version: {PubNub.SDK_VERSION}")
8
9 # Optional: You can also initialize a PubNub instance and check the version
10 pn_config = PNConfiguration()
11 pn_config.subscribe_key = os.getenv('SUBSCRIBE_KEY', 'demo') # Replace 'demo' with your subscribe key from the PubNub Admin Portal
12 pn_config.user_id = os.getenv('USER_ID', 'my_custom_user_id')
13
14 pubnub = PubNub(pn_config)
15 print(f"Initialized PubNub with SDK Version: {pubnub.SDK_VERSION}")
show all 18 lines

Error handling with sync()​

When you call sync(), the SDK wraps results and errors in an Envelope or a PubNubException. Both provide the following fields:

  • e.result - the request result object on success, otherwise None

  • e.status - a PNStatus object with details about the finished request. Call the e.is_error() helper to check whether the request failed.

sync() usage​

1import os
2from pubnub.pnconfiguration import PNConfiguration
3from pubnub.pubnub import PubNub
4from pubnub.exceptions import PubNubException
5
6def publish_message(pubnub: PubNub):
7 try:
8 envelope = pubnub.publish() \
9 .channel("my_channel") \
10 .message("hello!") \
11 .sync()
12 print(f"Published message with timetoken: {envelope.result.timetoken}")
13 print(f"Full result: {str(envelope.result)}")
14 except PubNubException as e:
15 print(f"Error: {str(e)}")
show all 32 lines

Error handling with pn_async()​

When you call pn_async(), check for errors with the status.is_error() helper:

1import os
2import time
3from pubnub.pnconfiguration import PNConfiguration
4from pubnub.pubnub import PubNub
5from pubnub.callbacks import SubscribeCallback
6from pubnub.enums import PNStatusCategory, PNOperationType
7
8class MySubscribeCallback(SubscribeCallback):
9 def status(self, pubnub, status):
10 if status.is_error():
11 print(f"Error: {str(status.error_data.exception)}")
12 print(f"Error category: {status.category}")
13 elif status.category == PNStatusCategory.PNConnectedCategory:
14 print("Connected to PubNub!")
15 elif status.category == PNStatusCategory.PNReconnectedCategory:
show all 72 lines

Was this page useful?

Last updated on