PubNub LogoDocs
SupportContact SalesLoginTry Our APIs

›API Reference

python

  • Getting Started
  • API Reference

    • Configuration
    • Publish & Subscribe
    • Presence
    • Access Manager
    • Channel Groups
    • Message Persistence
    • Mobile Push
    • Objects
    • Files
    • Message Actions
    • Miscellaneous
  • Status Events
  • Troubleshooting
  • Change Log
  • Feature Support
  • Platform Support
  • Reconnection Policies

Configuration API for PubNub Python SDK

Python version support

Python SDK versions 5.0.0 and higher no longer support Python v2.7 and the Twisted and Tornado frameworks. If you require support for any of these, use SDK version 4.8.1.

Note that PubNub will stop supporting versions of Python lower than 3.7 by the end of 2021.

Python complete API reference for building real-time applications on PubNub, including basic usage and sample code.

Configuration

Description

PNConfiguration instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.

Method(s)

To create configuration instance you can use the following function in the Python SDK:

pnconfig = PNConfiguration()
PropertiesTypeRequiredDefaultsDescription
subscribe_keyStringYessubscribe_key from Admin Portal.
publish_keyStringOptionalNonepublish_key from Admin Portal (only required if publishing).
secret_keyStringOptionalNonesecret_key (only required for modifying/revealing access permissions)
cipher_keyStringOptionalNoneIf cipher_key is passed, all communications to/from PubNub will be encrypted.
uuidStringYesUUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
auth_keyStringOptionalNoneIf Access Manager is utilized, client will use this authKey in all restricted requests.
sslBooleanOptionalFalseUse SSL.
connect_timeoutIntOptional5How long to wait before giving up connection to client.The value is in seconds.
subscribe_request_timeoutIntOptional310How long to keep the subscribe loop running before disconnect. The value is in seconds.
non_subscribe_request_timeoutIntOptional10On non subscribe operations, how long to wait for server response.The value is in seconds.
filter_expressionStringOptionalNoneFeature to subscribe with a custom filter expression.
heartbeat_notification_optionsPNHeartbeatNotificationOptionsOptionalPNHeartbeatNotificationOptions.FAILURESHeartbeat notifications, by default, the SDK will alert on failed heartbeats (equivalent to: PNHeartbeatNotificationOptions.FAILURES).
Other options such as all heartbeats (PNHeartbeatNotificationOptions.ALL) or no heartbeats (PNHeartbeatNotificationOptions.NONE) are supported.
reconnect_policyPNReconnectionPolicyOptionalPNReconnectionPolicy.NONESet to PNReconnectionPolicy.LINEAR for automatic reconnects. Use option PNReconnectionPolicy.NONE to disable automatic reconnects.Use option PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval.
originStringOptionalps.pndsn.comCustom origin if needed.
suppress_leave_eventsBooleanOptionalFalseIf True, the client doesn't send presence leave events during the unsubscribe process.
enable_subscribeBooleanOptionalTrueYou can disable the subscribe loop if you don't need to perform subscribe operations. By default, subscribe loop is enabled and extra threads/loops are started. They should be explicitly stopped by pubnub.stop() method invocation.
daemonBooleanOptionalFalseWhen set to True, spawned thread won't keep the application running after SIGTERM. (ctrl-c from command line, for example)
disable_token_managerBooleanOptionalFalseWhen set to True, the Token Manager System (TMS) will be disabled. Even if there are applicable tokens, no requests will be authorized.
use_random_initialization_vectorBooleanOptionalTrueWhen True the initialization vector (IV) is random for all requests (not just for file upload). When False the IV is hard-coded for all requests except for file upload.
Disabling random initialization vector

Disable random initialization vector (IV) only for backward compatibility (<5.1.0) with existing applications. Never disable random IV on new applications.

Basic Usage

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

from pubnub.pnconfiguration import PNConfiguration
from pubnub.enums import PNHeartbeatNotificationOptions

pn_configuration = PNConfiguration()
# subscribe_key from Admin Portal
pn_configuration.subscribe_key = "my_subscribe_key" // required
# publish_key from Admin Portal (only required if publishing)
pn_configuration.publish_key = "my_publish_key"
# secret_key (only required for modifying/revealing access permissions)
pn_configuration.secret_key = "my_secret_key"
# if cipher_key is passed, all communicatons to/from pubnub will be encrypted
pn_configuration.cipher_key = "my_cipher_key"
# UUID to be used as a device identifier, won't connect if not set
pn_configuration.uuid = "my_custom_uuid"
# if Access Manager is utilized, client will use this authKey in all restricted
# requests
pn_configuration.auth_key = "my_aut_key"
# use SSL
pn_configuration.ssl = True
# how long to wait before giving up connection to client
pn_configuration.connect_timeout = 100
# how long to keep the subscribe loop running before disconnect
pn_configuration.subscribe_request_timeout = 310
# on non subscribe operations, how long to wait for server response
pn_configuration.non_subscribe_timeout = 300
# PSV2 feature to subscribe with a custom filter expression
pn_configuration.filter_expression = "such=wow"
# heartbeat notifications, by default, the SDK will alert on failed heartbeats.
# other options such as all heartbeats or no heartbeats are supported.
pn_configuration.heartbeat_notification_options = PNHeartbeatNotificationOptions.All

Initialization

Add PubNub to your project using one of the procedures defined under How to Get It

Description

This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publish_key and subscribe_key.

Method(s)

To Initialize PubNub you can use the following method(s) in the Python SDK:

pubnub = PubNub(my_pnconfig)
ParameterTypeRequiredDescription
pn_configurationPNConfigurationYesGoto Configuration for more details.

Basic Usage

Initialize the PubNub client API:

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

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

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.ssl = True
pnconfig.uuid = "my_custom_uuid"
pubnub = PubNub(pnconfig)

Returns

It returns the PubNub instance for invoking PubNub APIs like publish(), subscribe(), history(), here_now(), etc.

Other Examples

  1. Initialize a non-secure client:

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "my_subkey"
    pnconfig.publish_key = "my_pubkey"
    pnconfig.ssl = False
    pnconfig.uuid = "my_custom_uuid"
    pubnub = PubNub(pnconfig)
    
  2. Initialization for a Read-Only client:

    In the case where a client will only read messages and never publish to a channel, you can simply omit the publish_key when initializing the client:

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "my_subkey"
    
    pubnub = PubNub(pnconfig)
    
  3. Use a custom UUID

    Set a custom UUID to identify your users.

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    
    pnconfig = PNConfiguration()
    
    pnconfig.subscribe_key = 'mySubscribeKey'
    pnconfig.publish_key = 'myPublishKey'
    pnconfig.uuid = 'myUniqueUUID'
    
    pubnub = PubNub(pnconfig)
    
  4. Initializing with SSL Enabled:

    This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with ssl set to True. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "my_subkey"
    pnconfig.publish_key = "my_pubkey"
    pnconfig.ssl = True
    pnconfig.uuid = "my_custom_uuid"
    pubnub = PubNub(pnconfig)
    
  5. Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
    https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

    Note

    Anyone with the secret_key can grant and revoke permissions to your app. Never let your secret_key be discovered, and to only exchange it / deliver it securely. Only use the secret_key on secure server-side platforms.

    When you init with secret_key, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

    For applications that will administer PAM permissions, the API is initialized with the secret_key as in the following example:

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "my_subkey"
    pnconfig.publish_key = "my_pubkey"
    pnconfig.secret_key = "my_secretkey"
    pnconfig.uuid = "my_custom_uuid"
    pnconfig.ssl = True
    
    pubnub = PubNub(pnconfig)
    

    Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the secret_key to sign all PAM messages to the PubNub Network.

Event Listeners

Description

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

Adding Listeners

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

class MySubscribeCallback(SubscribeCallback):
    def message(self, pubnub, message):
        print("Message channel: %s" % message.channel)
        print("Message subscription: %s" % message.subscription)
        print("Message timetoken: %s" % message.timetoken)
        print("Message payload: %s" % message.message)
        print("Message publisher: %s" % message.publisher)

    def presence(self, pubnub, presence):
        # Can be join, leave, state-change, timeout, or interval
        print("Presence event: %s" % presence.event)

        # The channel to which the message was published
        print("Presence channel: %s" % presence.channel)

        # Number of users subscribed to the channel
        print("Presence occupancy: %s" % presence.occupancy)

        # User state
        print("Presence state: %s" % presence.state)

        # Channel group or wildcard subscription match, if any
        print("Presence subscription: %s" % presence.subscription)

        # UUID to which this event is related
        print("Presence UUID: %s" % presence.uuid)

        # Publish timetoken
        print("Presence timestamp: %s" % presence.timestamp)

        # Current timetoken
        print("Presence timetoken: %s" % presence.timetoken)

        # List of users that have joined the channel (if event is 'interval')
        joined = presence.join

        # List of users that have left the channel (if event is 'interval')
        left = presence.leave

        # List of users that have timed-out off the channel (if event is 'interval')
        timed_out = presence.timeout

    def status(self, pubnub, status):

        # The status object returned is always related to subscribe but could contain
        # information about subscribe, heartbeat, or errors
        # use the operationType to switch on different options
        if status.operation == PNOperationType.PNSubscribeOperation \
                or status.operation == PNOperationType.PNUnsubscribeOperation:
            if status.category == PNStatusCategory.PNConnectedCategory:
                pass
                # This is expected for a subscribe, this means there is no error or issue whatsoever
            elif status.category == PNStatusCategory.PNReconnectedCategory:
                pass
                # This usually occurs if subscribe temporarily fails but reconnects. This means
                # there was an error but there is no longer any issue
            elif status.category == PNStatusCategory.PNDisconnectedCategory:
                pass
                # This is the expected category for an unsubscribe. This means there
                # was no error in unsubscribing from everything
            elif status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
                pass
                # This is usually an issue with the internet connection, this is an error, handle
                # appropriately retry will be called automatically
            elif status.category == PNStatusCategory.PNAccessDeniedCategory:
                pass
                # This means that PAM does not allow this client to subscribe to this
                # channel and channel group configuration. This is another explicit error
            else:
                pass
                # This is usually an issue with the internet connection, this is an error, handle appropriately
                # retry will be called automatically
        elif status.operation == PNOperationType.PNSubscribeOperation:
            # Heartbeat operations can in fact have errors, so it is important to check first for an error.
            # For more information on how to configure heartbeat notifications through the status
            # PNObjectEventListener callback, consult http://www.pubnub.com/docs/sdks/python/api-reference/configuration#configuration
            if status.is_error():
                pass
                # There was an error with the heartbeat operation, handle here
            else:
                pass
                # Heartbeat operation was successful
        else:
            pass
            # Encountered unknown status type

    def signal(self, pubnub, signal):
        print("Signal channel: %s" % signal.channel)
        print("Signal subscription: %s" % signal.subscription)
        print("Signal timetoken: %s" % signal.timetoken)
        print("Signal payload: %s" % signal.message)
        print("Signal publisher: %s" % signal.publisher)

    def message_action(self, pubnub, message_action):
        print("Message action type: %s" % message_action.type)
        print("Message action value: %s" % message_action.value)
        print("Message action uuid: %s" % message_action.uuid)
        print("Message action action_timetoken: %s" % message_action.action_timetoken)
        print("Message action message_timetoken: %s" % message_action.message_timetoken)

pubnub.add_listener(MySubscribeCallback())

Removing Listeners

my_listener = MySubscribeCallback()

pubnub.add_listener(my_listener)

# some time later
pubnub.remove_listener(my_listener)

Handling Disconnects

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

class HandleDisconnectsCallback(SubscribeCallback):
    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
            # internet got lost, do some magic and call reconnect when ready
            pubnub.reconnect()
        elif status.category == PNStatusCategory.PNTimeoutCategory:
            # do some magic and call reconnect when ready
            pubnub.reconnect()
        else:
            logger.debug(status)

    def presence(self, pubnub, presence):
        pass

    def message(self, pubnub, message):
        pass

    def signal(self, pubnub, signal):
        pass

disconnect_listener = HandleDisconnectsCallback()

pubnub.add_listener(disconnect_listener)

Listener status events

CategoryDescription
PNTimeoutCategoryFailure to establish a connection to PubNub due to a timeout.
PNBadRequestCategoryThe server responded with a bad response error because the request is malformed.
PNNetworkIssuesCategoryA subscribe event experienced an exception when running. The SDK isn't able to reach the PubNub Data Stream Network. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNConnectedCategorySDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes.
PNUnexpectedDisconnectCategoryPreviously started subscribe loop did fail and at this moment client disconnected from real-time data channels.
PNUnknownCategoryReturned when the subscriber gets a non-200 HTTP response code from the server.

SubscribeListener should not be used with high-performance sections of your app.

Filter Expression

Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

Description

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set/get filters you can use the following methods. To learn more about filtering, refer to the Publish Messages documentation.

Method(s)

Set Filter Expression

The property accepts a string.

Get Filter Expression

The property returns a string

Basic Usage

Set Filter Expression

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

from pubnub.pnconfiguration import PNConfiguration

pnconfig = PNConfiguration()
pnconfig.filter_expression = "such=wow"

Get Filter Expression

filter = pnconfig.filter_expression
← Getting StartedPublish & Subscribe →
  • Configuration
    • Description
    • Method(s)
    • Basic Usage
  • Initialization
    • Description
    • Method(s)
    • Basic Usage
    • Returns
    • Other Examples
  • Event Listeners
    • Description
  • Filter Expression
    • Description
    • Method(s)
    • Basic Usage
© PubNub Inc. - Privacy Policy