Configuration API for Python SDK
Complete API reference for building real-time applications on PubNub with the Python Software Development Kit (SDK). This page covers configuration, initialization, and event handling with concise, working examples.
Configuration
PNConfiguration
stores user-provided settings that control PubNub client behavior. It includes properties for precise client configuration.
Method(s)
To create configuration
instance you can use the following function in the Python SDK:
pnconfig = PNConfiguration()
Parameter | Description |
---|---|
subscribe_key *Type: String Default: n/a | subscribe_key from Admin Portal. |
publish_key Type: String Default: None | publish_key from Admin Portal (only required if publishing). |
secret_key Type: String Default: None | secret_key (only required for modifying/revealing access permissions) |
user_id *Type: String Default: n/a | user_id to use. You should set a unique user_id to identify the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set theuser_id , you won't be able to connect to PubNub. |
auth_key Type: String Default: None | If Access Manager is utilized, client will use this authKey in all restricted requests. |
ssl Type: Boolean Default: True | Use Secure Sockets Layer (SSL). |
connect_timeout Type: Int Default: 5 | How long to wait before giving up connection to client. The value is in seconds. |
subscribe_request_timeout Type: Int Default: 310 | How long to keep the subscribe loop running before disconnect. The value is in seconds. |
non_subscribe_request_timeout Type: Int Default: 10 | On non subscribe operations, how long to wait for server response. The value is in seconds. |
filter_expression Type: String Default: None | Feature to subscribe with a custom filter expression. |
heartbeat_notification_options Type: PNHeartbeatNotificationOptions Default: PNHeartbeatNotificationOptions.FAILURES | Heartbeat 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_policy Type: PNReconnectionPolicy Default: PNReconnectionPolicy.EXPONENTIAL (subscribe only) | Custom reconnection configuration parameters. PNReconnectionPolicy is the type of policy to be used. Available values:
For more information, refer to SDK connection lifecycle. |
maximum_reconnection_retries Type: int Default: 10 | Number of times a request can be retried. Only applicable to PNReconnectionPolicy.LINEAR . |
reconnection_interval Type: float Default: 2.0 | The delay in seconds between failed retry attempts. Only applicable to PNReconnectionPolicy.LINEAR . |
suppress_leave_events Type: Boolean Default: False | If True , the client doesn't send presence leave events during the unsubscribe process. |
enable_subscribe Type: Boolean Default: True | You 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. |
daemon Type: Boolean Default: False | When set to True , spawned thread won't keep the application running after SIGTERM. (ctrl-c from command line, for example) |
disable_token_manager Type: Boolean Default: False | When set to True , the Token Manager System (TMS) will be disabled. Even if there are applicable tokens, no requests will be authorized. |
cipher_mode Type: AES.MODE_CBC or AES.MODE_GCM Default: AES.MODE_CBC | The cipher method to be used for message encryption for the legacy crypto module. By default, all PubNub SDKs use CBC. ⚠️Warning! If you set the Python SDK's cipher_mode to GCM, ensure that all other clients can decode the message. |
fallback_cipher_mode Type: AES.MODE_CBC or AES.MODE_GCM Default: None | The secondary cipher method used for message decryption for the legacy crypto module. It is used if the method set in the cipher_mode parameter fails to decrypt the messages. |
cipher_key Type: String Default: None | If cipher_key is passed, all communications to/from PubNub will be encrypted. |
use_random_initialization_vector Type: Boolean Default: True | When 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. |
crypto_module Type: PubNubCryptoModule Default: None | The cryptography module used for encryption and decryption of messages and files. Takes the config (PNConfiguration instance with cipher_key and use_random_initialization_vector ) parameter as argument. For more information, refer to the crypto_module section. |
uuid Type: Default: n/a | This parameter is deprecated, use user_id instead. UUID 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. |
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.
crypto_module
crypto_module
encrypts and decrypts messages and files. From 7.2.0, you can configure the algorithms it uses.
Each SDK includes two options: legacy 128‑bit encryption and recommended 256‑bit AES‑CBC. For background, see Message Encryption and File Encryption.
If you don't set crypto_module
but set cipher_key
and use_random_initialization_vector
in config, the client uses legacy encryption.
For configuration details, utilities, and examples, see Encryption.
Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
Sample code
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
Reference code
import os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.enums import PNHeartbeatNotificationOptions
from pubnub.pubnub import PubNub
from pubnub.crypto import AesCbcCryptoModule
# Configuration for PubNub instance
pn_configuration = PNConfiguration()
# Set configuration values
pn_configuration.subscribe_key = os.getenv('SUBSCRIBE_KEY', 'demo') # required
pn_configuration.publish_key = os.getenv('PUBLISH_KEY', 'demo') # only required if publishing
pn_configuration.secret_key = os.getenv('SECRET_KEY', 'my_secret_key') # optional
pn_configuration.cipher_key = os.getenv('CIPHER_KEY', 'my_cipher_key') # for encryption/decryption
show all 31 linesInitialization
Add PubNub to your project using one of the procedures defined in the Getting Started guide.
Description
Initialize the PubNub Client API context before calling any APIs. This establishes 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(pn_configuration, custom_request_handler)
Parameter | Description |
---|---|
pn_configuration *Type: PNConfiguration Default: n/a | The configuration object. For more details, refer to Configuration. |
custom_request_handler Type: subclass of BaseRequestHandler Default: HttpxRequestHandler | The optional custom HTTP request handler. For more information, refer to Custom request handler. |
Custom request handler
The optional custom_request_handler
lets you select the HTTP library for requests.
If you omit it, the SDK checks the PUBNUB_REQUEST_HANDLER
environment variable. If the value isn't a subclass of BaseRequestHandler
, the SDK defaults to HttpxRequestHandler
.
Class | Description |
---|---|
HttpxRequestHandler | Python SDK synchronous requests handler based on the httpx HTTP library. |
RequestsRequestHandler | Python SDK synchronous requests handler based on the requests HTTP library. |
Sample code
Initialize the PubNub client API
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, 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.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)
Returns
Returns a PubNub instance for APIs like publish()
, subscribe()
, history()
, and here_now()
.
Other examples
Use a custom request handler
You can set a custom request handler by specifying one of the available request handlers during the initialization of the PubNub client.
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from pubnub.request_handlers.requests_handler import RequestsRequestHandler
pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig, custom_request_handler=RequestsRequestHandler)
Initialize a non-secure client
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, 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.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)
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:
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, 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)
Use a custom user ID
Set a custom user_id
to identify your users.
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, 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.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)
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.
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, 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.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)
Initializing with Access Manager
Requires Access Manager add-on
This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Secure your secret_key
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 Access Manager permissions, the API is initialized with the secret_key
as in the following example:
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, 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.user_id = "my_custom_user_id"
pnconfig.ssl = True
pubnub = PubNub(pnconfig)
Now that the pubnub object is instantiated the client will be able to access the Access Manager functions. The pubnub object will use the secret_key
to sign all Access Manager messages to the PubNub Network.
Event listeners
PubNub SDKs provide several sources for real-time updates:
- The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
- The
Subscription
object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user. - The
SubscriptionsSet
object can receive updates for all objects for which a list of subscription objects was created.
To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see Publish & Subscribe.
Filter expression
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Stream filtering lets a subscriber receive only messages that match a filter. The client sets the filter, and the server applies it to block messages that do not match.
To set or get message 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
.
Sample code
Set filter expression
Required User ID
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, 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