---
source_url: https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration
title: Configuration API for Python-Asyncio SDK
updated_at: 2026-05-22T09:19:47.275Z
sdk_name: PubNub Python Asyncio SDK
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Configuration API for Python-Asyncio SDK

PubNub Python Asyncio SDK

Install:

```bash
pip install pubnub
```

The Python-Asyncio Software Development Kit (SDK) configuration reference for building real-time applications on PubNub, including basic usage and sample code.

## Configuration

The `PNConfiguration` instance stores user-provided settings that control client behavior. The configuration includes properties for security, connectivity, and subscription features.

### Method(s)

Create a configuration instance using the Python-Asyncio SDK:

```python
pnconfig = PNConfiguration()
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| subscribe_key | String | Yes |  | The Subscribe Key from the Admin Portal. |
| publish_key | String | Optional | `None` | The Publish Key from the Admin Portal (required only for publishing). |
| secret_key | String | Optional | `None` | The `secret_key` (required only for configuring or revealing permissions with Access Manager). |
| cipher_key | String | Optional | `None` | If set, all communications to and from PubNub are encrypted. |
| user_id | String | Yes |  | The User ID used to identify the client. Set a unique value per user or device. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you do not set `user_id`, the client cannot connect. |
| auth_key | String | Optional | `None` | If Access Manager is enabled, the client includes this `auth_key` in restricted requests. |
| ssl | Boolean | Optional | `True` | Use Transport Layer Security (TLS). Set to `True` to enable encrypted transport. |
| connect_timeout | Int | Optional | `5` | Time in seconds to wait before giving up on establishing a connection. |
| subscribe_request_timeout | Int | Optional | `310` | Time in seconds to keep the subscribe loop running before disconnecting. |
| non_subscribe_request_timeout | Int | Optional | `10` | Time in seconds to wait for a server response on non-subscribe operations. |
| filter_expression | String | Optional | `None` | Enables subscribing with a custom filter expression. |
| heartbeat_notification_options | PNHeartbeatNotificationOptions | Optional | `PNHeartbeatNotificationOptions.FAILURES` | Heartbeat notifications. By default, the SDK alerts on failed heartbeats. Other options include all heartbeats or no heartbeats. |
| reconnect_policy | PNReconnectionPolicy | Optional | `PNReconnectionPolicy.EXPONENTIAL (subscribe only)` | Custom reconnection configuration parameters. `PNReconnectionPolicy` is the type of policy to be used. Available values: PNReconnectionPolicy.NONE, PNReconnectionPolicy.LINEAR (see maximum_reconnection_retries and reconnection_interval below), PNReconnectionPolicy.EXPONENTIAL (see maximum_reconnection_retries, reconnection_interval, and maximum_reconnection_interval below) For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle). Set retry limits explicitlyThe Python-Asyncio SDK doesn't enforce upper bounds on maximum_reconnection_retries or maximum_reconnection_interval.Without limits, misconfigured policies may cause excess network traffic, battery drain, or usage spikes. Always choose values suited to your app. |
| maximum_reconnection_retries | int | Optional | `None` | Maximum number of reconnection attempts before the SDK stops retrying. Applies to both `PNReconnectionPolicy.LINEAR` and `PNReconnectionPolicy.EXPONENTIAL`. When `None`, the policy default applies (`10` for LINEAR, `6` for EXPONENTIAL). Set to `-1` for unlimited retries, or `0` to stop without retrying. |
| reconnection_interval | float | Optional | `None` | Delay in seconds between reconnection attempts. For `PNReconnectionPolicy.LINEAR`, sets the fixed retry interval. For `PNReconnectionPolicy.EXPONENTIAL`, sets the minimum backoff delay. When `None`, each policy uses its built-in default. |
| maximum_reconnection_interval | float | Optional | `None` | Maximum delay in seconds between reconnection attempts. Only applicable to `PNReconnectionPolicy.EXPONENTIAL`. When set, the exponential backoff delay never exceeds this value. When `None`, the default maximum from `ExponentialDelay` is used. |
| origin | String | Optional | `ps.pndsn.com` | Custom origin if required. To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| suppress_leave_events | Boolean | Optional | `False` | If `True`, the client does not send presence leave events during unsubscribe. |
| enable_subscribe | Boolean | Optional | `True` | Enable or disable the subscribe loop. When enabled, extra loops are started and must be stopped using `pubnub.stop()`. |
| daemon | Boolean | Optional | `False` | If `True`, spawned threads do not keep the application running after SIGTERM. |
| disable_token_manager | Boolean | Optional | `False` | If `True`, the Token Manager System (TMS) is disabled. Requests are not authorized using tokens even if available. |
| use_random_initialization_vector | Boolean | Optional | `True` | If `True`, a random initialization vector (IV) is used for all requests. If `False`, a fixed IV is used for all requests except file upload. |
| uuid | String | Yes |  | Deprecated. Use `user_id` instead. |

:::warning 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.
:::

### Sample code

:::note 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.
:::

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```python
import os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.enums import PNHeartbeatNotificationOptions

# Configuration for the client instance
pn_configuration = PNConfiguration()

# Set configuration values
pn_configuration.subscribe_key = os.getenv('PUBNUB_SUBSCRIBE_KEY', 'demo')  # required
pn_configuration.publish_key = os.getenv('PUBNUB_PUBLISH_KEY', 'demo')  # only required if publishing
pn_configuration.secret_key = os.getenv('PUBNUB_SECRET_KEY', 'my_secret_key')  # optional
pn_configuration.user_id = os.getenv('PUBNUB_USER_ID', 'my_custom_user_id')  # must be set
pn_configuration.auth_key = os.getenv('PUBNUB_AUTH_KEY', 'my_auth_key')  # optional
pn_configuration.ssl = True
pn_configuration.filter_expression = "such=wow"
pn_configuration.heartbeat_notification_options = PNHeartbeatNotificationOptions.ALL

# Adding the requested parameters
pn_configuration.enable_subscribe = True  # required if you want to subscribe
pn_configuration.enable_presence_heartbeat = True  # automatically sends presence heartbeats for subscribed channels

# The configuration is ready to pass to PubNub
# Simply create a PubNub instance using it:
# pubnub = PubNub(pn_configuration)

print("Configuration set up complete.")
```

## Initialization

Add the SDK to your project, then initialize the client.

### Description

This function initializes the client context. Call it before using any API to establish account-level credentials such as `publish_key` and `subscribe_key`.

### Method(s)

Initialize with the Python-Asyncio SDK:

```python
pubnub = PubNubAsyncio(pn_configuration, custom_event_loop, subscription_manager, *, custom_request_handler)
```

| Parameter | Description |
| --- | --- |
| `pn_configuration` *Type: PNConfiguration | See [Configuration](#configuration) for details. |
| `custom_event_loop`Type: AbstractEventLoop | Use a custom Asyncio event loop instance. |
| `subscription_manager`Type: EventEngineSubscriptionManager | Use standardized workflows for subscribe and presence. |
| `custom_request_handler`Type: subclass of `BaseRequestHandler` | The custom HTTP request handler. For more information, refer to [Custom request handler](#custom-request-handler). Default is `AsyncHttpxRequestHandler`. |

### Environment variables

You can turn on certain features using environment variables with inline declaration:

```bash
PN_ENABLE_EVENT_ENGINE=True PN_MAINTAIN_PRESENCE_STATE=True PUBNUB_ASYNC_REQUEST_HANDLER=AsyncAiohttpRequestHandler python path/to/your/file.py 
```

or by exporting environment variables to your system, and then running the script:

```bash
export PN_ENABLE_EVENT_ENGINE=True
export PN_MAINTAIN_PRESENCE_STATE=True
export PUBNUB_ASYNC_REQUEST_HANDLER=AsyncAiohttpRequestHandler

python path/to/your/file.py
```

| Flag | Description |
| --- | --- |
| `PN_ENABLE_EVENT_ENGINE` | Whether to use the recommended standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which [statuses](https://www.pubnub.com/docs/sdks/asyncio/status-events) it emits. |
| `PN_MAINTAIN_PRESENCE_STATE` | Whether the custom presence state information set using [pubnub.set_state()](https://www.pubnub.com/docs/sdks/asyncio/api-reference/presence#set-state) should be sent every time the SDK sends a subscribe call. |
| `PUBNUB_ASYNC_REQUEST_HANDLER` | The library for sending HTTP requests. |

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

```python
pubnub = PubNub(pn_configuration, custom_request_handler)
```

| Parameter | Description |
| --- | --- |
| `pn_configuration` *Type: [PNConfiguration](#configuration)Default: n/a | The configuration object. For more details, refer to [Configuration](#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). |

#### Custom request handler

The `custom_request_handler` option selects the library used for sending HTTP requests.

If you do not specify this parameter, the Python-Asyncio SDK first checks the value of the `PUBNUB_ASYNC_REQUEST_HANDLER` environment variable. If you do not set the variable or its value is not a subclass of `BaseRequestHandler`, the SDK defaults to `AsyncHttpxRequestHandler`.

| Class | Description |
| --- | --- |
| `AsyncAiohttpRequestHandler` | Python SDK asynchronous requests handler based on the [requests](https://requests.readthedocs.io/en/latest/) HTTP library. |
| `AsyncHttpxRequestHandler` | Python SDK asynchronous requests handler based on the [httpx](https://www.python-httpx.org/) HTTP library. |

### Sample code

#### Initialize the client API

:::note 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.ssl = True
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNubAsyncio(pnconfig)
```

### Returns

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

### Other examples

#### Use a custom request handler

You can set a custom request handler by specifying one of the available handlers during initialization.

:::note 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio
from pubnub.request_handlers.async_aiohttp import AsyncAiohttpRequestHandler

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.ssl = True
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNubAsyncio(pnconfig)

pubnub = PubNub(pnconfig, custom_request_handler=AsyncAiohttpRequestHandler)
```

#### Initialize a non-secure client

:::note 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.ssl = False
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNubAsyncio(pnconfig)
```

#### Initialize 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 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"

pubnub = PubNubAsyncio(pnconfig)
```

#### Use a custom user ID

Set a custom `user_id` to identify your users.

:::note 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.
:::

```python
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)
```

#### Initialize with SSL enabled

This example demonstrates how to enable Transport Layer Security (TLS) with `ssl`. Initialize the client with `ssl` set to `True`. The API handles encryption for you; subscribe and publish as usual.

:::note 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.ssl = True
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNubAsyncio(pnconfig)
```

#### Initialize with Access Manager

:::note Requires Access Manager add-on
This method requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

:::note 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:

:::note 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio

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 = PubNubAsyncio(pnconfig)
```

Now that the `pubnub` object is instantiated, the client can access the Access Manager functions. The `pubnub` object uses the `secret_key` to sign all Access Manager messages to the PubNub network.

#### Initialize with a custom event loop

:::note 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"

pubnub = PubNubAsyncio(pnconfig, custom_event_loop=my_event_loop)
```

## Event listeners

PubNub SDKs provide several sources for real-time updates:

* The PubNub client can receive updates from all subscriptions, including all channels, channel groups, channel metadata, and users.
* The [Subscription](https://www.pubnub.com/docs/sdks/asyncio/api-reference/publish-and-subscribe#create-a-subscription) object can receive updates only for the object for which it was created: a channel, a channel group, channel metadata, or a user.
* The [SubscriptionsSet](https://www.pubnub.com/docs/sdks/asyncio/api-reference/publish-and-subscribe#create-a-subscription-set) object can receive updates for all objects for which a list of subscription objects was created.

To work with these real-time update sources, PubNub SDKs provide local representations of server entities so that you can subscribe and add listeners on a per-entity basis. For more information, refer to [Publish & Subscribe](https://www.pubnub.com/docs/sdks/asyncio/api-reference/publish-and-subscribe#event-listeners).

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

Stream filtering allows a subscriber to apply a filter to receive only messages that meet the filter conditions. The message filter is set by the subscribing client and applied on the server to prevent unwanted messages from reaching the subscriber.

Use the `filter_expression` property to set or get the message filter. To learn more about filtering, refer to the [Publish Messages](https://www.pubnub.com/docs/general/messages/publish) documentation.

### Method(s)

```python
Set Filter Expression
```

The property accepts a `string`.

```python
Get Filter Expression
```

The property returns a `string`.

### Sample code

#### Set filter expression

:::note 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.
:::

```python
from pubnub.pnconfiguration import PNConfiguration

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

#### Get filter expression

```python
filter = pnconfig.filter_expression
```

## Terms in this document

* **Access Manager** - A cryptographic, token-based permission administrator that allows you to regulate clients' access to PubNub resources, such as channels, channel groups, and user IDs.
* **Listener** - A function or objectthat reacts to events or messages, like new chat messages or connection updates, letting your app respond in real-time.
* **Origin** - The subdomain used to establish a connection to the PubNub network that allows your application's traffic to appear like it's coming from your own domain.
* **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.
* **PubNub** - 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.
* **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.
* **User** - An individual or entity that interacts with a system, application, or service. In PubNub, a user typically refers to someone who sends or receives messages through the platform, identified by a unique user ID or username.
* **User ID** - UTF-8 encoded, unique string of up to 92 characters used to identify a single client (end user, device, or server) that connects to PubNub.