Subscribe API for Python SDK

The Subscribe API lets a PubNub client for Python receive messages and events in real time. You create a subscription for one SDK entity, or a subscription set for several, add an event listener, and then subscribe.

For the concepts behind publishing and subscribing, see Connection management, Subscriptions, and Publish messages. The methods on this page run on the calling thread and return None, so they have no .sync() or .pn_async() call.

Subscribe​

subscribe() starts receiving real-time messages and events for a subscription or subscription set of a PubNub client for Python.

To subscribe, set subscribe_key when you create the PubNub client. See Initialization.

By default, a subscription receives the messages that PubNub publishes after the subscribe request completes.Calling subscribe() starts the subscription but delivers nothing to your code until you add an event listener.

A PubNub client for Python retries failed subscribe requests as set by reconnect_policy. See Configuration.

Subscription scope​

Subscriptions let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:

  • subscription: created from an SDK entity and scoped to that entity, for example a particular channel
  • subscription_set: created from the PubNub client and scoped to the subscriptions that you put in the set

subscription and subscription_set use the same subscribe() method.

timetoken#
Type: Optional[int]
Default: None
The timetoken from which to start returning available cached messages. PubNub provides cached messages on a best-effort basis. The SDK uses the larger of this value and the timetoken that the client already holds.
region#
Type: Optional[str]
Default: None
The region of an earlier subscribe response. The SDK accepts this value and ignores it.

A wildcard channel name such as my_channel.* subscribes the same way. The message event reports the concrete channel in channel and the matching pattern in subscription.

Returns​

subscribe() returns nothing.

Syntax

1subscription.subscribe(timetoken: Optional[int] = None, region: Optional[str] = None) -> None
2subscription_set.subscribe(timetoken: Optional[int] = None, region: Optional[str] = None) -> None

Create a subscription​

subscription() creates a subscription for one SDK entity of a PubNub client for Python. The subscription receives messages and events for only that entity.

Use several subscriptions to handle the message and event types of each channel differently.

with_presence#
Type: bool
Default: None
Whether the subscription delivers presence events for the entity to its listeners. The value True also subscribes to the -pnpres channel of the entity and enables the on_presence handler. None counts as False. For the events and how to receive them, see Presence events.

Syntax

1channel.subscription(with_presence: bool = None) -> PubNubSubscription

Create a subscription set​

subscription_set() creates a subscription set in a PubNub client for Python. The set receives messages and events for all the SDK entities that it contains.

Use a subscription set to handle the message and event types of several channels in the same way.

required
subscriptions required#
Type: List[PubNubSubscription]
Default: no default
The subscriptions that the set contains. Create each one with subscription() on an SDK entity. The set subscribes to the channels and channel groups of its subscriptions.

The method takes subscriptions only. The method has no channels or channel_groups parameter, so it raises TypeError for either keyword.

Syntax

1pubnub.subscription_set(subscriptions: List[PubNubSubscription]) -> PubNubSubscriptionSet

SDK entities​

An SDK entity is a local handle that represents something you can subscribe to in a PubNub client for Python. Creating one performs no network call and needs no matching server-side record.

Every SDK entity has a subscription() method. The client has a creation method for each kind of SDK entity:

Create an SDK channel entity​

channel() returns an SDK channel entity that represents a channel in a PubNub client for Python.

required
channel required#
Type: str
Default: no default
The ID of the channel to subscribe to. See channels.

Syntax

1pubnub.channel(channel: str) -> PubNubChannel

Create an SDK channel group entity​

channel_group() returns an SDK channel group entity that represents a channel group in a PubNub client for Python.

required
channel_group required#
Type: str
Default: no default
The name of the channel group to subscribe to. See channel groups.

Syntax

1pubnub.channel_group(channel_group: str) -> PubNubChannelGroup

Create an SDK channel metadata entity​

channel_metadata() returns an SDK channel metadata entity that represents the App Context metadata of a channel in a PubNub client for Python.

A subscription to this SDK entity delivers its App Context events to the on_channel_metadata handler and to the channel method of a SubscribeCallback listener. See Add listeners.

required
channel required#
Type: str
Default: no default
The ID of the channel metadata object to observe. See channel metadata.

Syntax

1pubnub.channel_metadata(channel: str) -> PubNubChannelMetadata

Create an SDK user metadata entity​

user_metadata() returns an SDK user metadata entity that represents the App Context metadata of a user in a PubNub client for Python.

A subscription to this SDK entity delivers its App Context events to the on_user_metadata handler and to the uuid method of a SubscribeCallback listener. See Add listeners.

required
user_id required#
Type: str
Default: no default
The ID of the user metadata object to observe. See user metadata.

Syntax

1pubnub.user_metadata(user_id: str) -> PubNubUserMetadata

Event listeners​

Event listeners are the single point through which your app receives all the messages, signals, and events of a PubNub client for Python.

You can attach listeners to a subscription, a subscription set, and the PubNub client. A listener on the PubNub client receives the events of all its subscriptions. A subscription or subscription set takes handler attributes such as on_message, and the PubNub client takes a SubscribeCallback object. Attach the connection status listener to the PubNub client only. See Add connection status listener.

No built-in event throttling

The PubNub SDK delivers every incoming event to your listener as it arrives. There is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.

To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.

Add listeners​

add_listener() adds an event listener that receives messages and events through a subscription, subscription set, or PubNub client for Python.

You can assign an event-specific handler that receives only one type of event, such as on_message or on_signal. Each assignment replaces the previous handler of that type.

required
on_message#
Type: Callable[[PNMessageResult], None]
Default: no default
Handles published messages.
on_signal#
Type: Callable[[PNSignalMessageResult], None]
Default: no default
Handles signals.
on_presence#
Type: Callable[[PNPresenceEventResult], None]
Default: no default
Handles presence events. A subscription calls it only when you create it with with_presence=True. A subscription set never calls it.
on_message_action#
Type: Callable[[PNMessageActionResult], None]
Default: no default
Handles message action events.
on_channel_metadata#
Type: Callable[[PNChannelMetadataResult], None]
Default: no default
Handles channel metadata events.
on_user_metadata#
Type: Callable[[PNUUIDMetadataResult], None]
Default: no default
Handles user metadata events.
on_membership#
Type: Callable[[PNMembershipResult], None]
Default: no default
Handles membership events.
on_file#
Type: Callable[[PNFileMessageResult], None]
Default: no default
Handles file events.
listener required#
Type: SubscribeCallback
Default: no default
An object whose methods handle each event type. Only pubnub.add_listener() takes it.
property of listener: status#
Type: Callable[[PubNub, PNStatus], None]
Default: no default
Handles connection status changes. Only the PubNub client reports connection status, so you cannot attach this listener to a subscription or subscription set. See Add connection status listener.
property of listener: message#
Type: Callable[[PubNub, PNMessageResult], None]
Default: no default
Handles published messages.
property of listener: signal#
Type: Callable[[PubNub, PNSignalMessageResult], None]
Default: no default
Handles signals.
property of listener: presence#
Type: Callable[[PubNub, PNPresenceEventResult], None]
Default: no default
Handles presence events.
property of listener: message_action#
Type: Callable[[PubNub, PNMessageActionResult], None]
Default: no default
Handles message action events.

SubscribeCallback also declares the methods channel, uuid, membership, and file. A subscription or subscription set delivers the App Context and file events of its channels to the on_channel_metadata, on_user_metadata, on_membership, and on_file handlers, and to the matching methods of a SubscribeCallback listener.

subscription.add_listener() takes a SubscribeCallback object. The SDK calls its methods with the pubnub argument, as it does for pubnub.add_listener().

Returns​

add_listener() returns nothing.

Syntax

1subscription.on_message: Callable[[PNMessageResult], None]
2subscription.on_signal: Callable[[PNSignalMessageResult], None]
3subscription.on_presence: Callable[[PNPresenceEventResult], None]
4subscription.on_message_action: Callable[[PNMessageActionResult], None]
5subscription.on_channel_metadata: Callable[[PNChannelMetadataResult], None]
6subscription.on_user_metadata: Callable[[PNUUIDMetadataResult], None]
7subscription.on_membership: Callable[[PNMembershipResult], None]
8subscription.on_file: Callable[[PNFileMessageResult], None]
9subscription_set.on_message: Callable[[PNMessageResult], None]
10subscription_set.on_signal: Callable[[PNSignalMessageResult], None]
11subscription_set.on_message_action: Callable[[PNMessageActionResult], None]
12pubnub.add_listener(listener: SubscribeCallback) -> None

Add connection status listener​

add_listener() adds a listener that reports the connection status of a PubNub client for Python.

Only the PubNub client reports connection status, so you cannot attach this listener to a subscription or subscription set.
required
listener required#
Type: SubscribeCallback
Default: no default
An object whose status() method the SDK calls each time the connection status changes.
property of listener: status required#
Type: Callable[[PubNub, PNStatus], None]
Default: no default
The handler that receives the client and the status object described under Returns.

Returns​

The handler receives a PNStatus object. Call status.is_error() to check for an error. For the list of status categories, see SDK statuses.

category#
Type: PNStatusCategory
The status category, for example PNConnectedCategory.
operation#
Type: PNOperationType
The operation that reported the status.
error#
Type: bool
Whether the operation failed.
error_data#
Type: PNErrorData
The details of the error.
status_code#
Type: int
The HTTP status code of the request.
affected_channels#
Type: List[str]
The channels that the status change affects.
affected_groups#
Type: List[str]
The channel groups that the status change affects.

Syntax

1pubnub.add_listener(listener: SubscribeCallback) -> None

Remove listener​

remove_listener() removes an event listener from a PubNub client for Python, so the listener stops receiving events.

The SDK identifies a listener by object, so pass the same object that you passed to add_listener(). Removing an object that you never added raises ValueError.
required
listener required#
Type: SubscribeCallback
Default: no default
The listener object to remove. Pass the object that you passed to add_listener().

Returns​

remove_listener() returns nothing.

Syntax

1pubnub.remove_listener(listener: SubscribeCallback) -> None

Unsubscribe​

unsubscribe() stops a subscription or subscription set of a PubNub client for Python from receiving real-time updates.

A channel stays subscribed while another active subscription or subscription set of the same PubNub client still uses it. If the set subscribed a subscription, unsubscribe() on that subscription doesn't stop the channel.

Subscription sets stay subscribed

subscription_set.unsubscribe() doesn't stop the channels of the set. The SDK sends no unsubscribe request for channels that a set subscribed, so the set keeps receiving messages (pubnub/models/subscription.py:162-182). To stop those channels, call the not recommended unsubscribe() builder with the channel names.

unsubscribe() takes no parameters.

Returns​

unsubscribe() returns nothing. The SDK sends a leave request, and its result reaches the status method of the listeners on the PubNub client.

Syntax

1subscription.unsubscribe() -> None
2subscription_set.unsubscribe() -> None

Unsubscribe all​

unsubscribe_all() unsubscribes every subscription and subscription set of a PubNub client for Python at once.

Only the PubNub client has this method, not a subscription or subscription set.
The client can't subscribe again

After unsubscribe_all(), the SDK can't register new subscriptions on the same PubNub client. The next subscribe() raises TypeError because the method replaces the internal registry with lists (pubnub/models/subscription.py:263-271). Create a new PubNub client to subscribe again.

unsubscribe_all() takes no parameters.

Returns​

unsubscribe_all() returns nothing.

Syntax

1pubnub.unsubscribe_all() -> None

pubnub.subscribe() and pubnub.unsubscribe() of the PubNub Python SDK start and stop subscriptions without a subscription object. Their use is not recommended, and subscriptions replace them.

The builders pubnub.subscribe() and pubnub.unsubscribe() take channels and channel_groups. New apps use Subscribe and Unsubscribe with subscriptions instead. The pubnub.unsubscribe_all() method is the same current method in both styles. See Unsubscribe all. The reference for apps that still use the builders is Subscribe API: not recommended methods for Python SDK.

Was this page useful?

Last updated on