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.
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 channelsubscription_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#- 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#- 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.
Sample code
Returns
subscribe() returns nothing.
Other examples
Examples for Subscribe
Syntax
1subscription.subscribe(timetoken: Optional[int] = None, region: Optional[str] = None) -> None
2subscription_set.subscribe(timetoken: Optional[int] = None, region: Optional[str] = None) -> None
Basic usage
1# single channel subscription
2channel = pubnub.channel("my_channel")
3t1_subscription = channel.subscription()
4t1_subscription.subscribe()
Subscribe a subscription set
Subscribe a subscription set
The set subscribes to every channel and channel group of its subscriptions with one call.
1channel = "my_channel"
2
3# multiple channel subscription
4channel_1 = pubnub.channel(channel).subscription()
5channel_2 = pubnub.channel(f'{channel}.2').subscription(with_presence=True)
6channel_x = pubnub.channel(f'{channel}.*').subscription(with_presence=True)
7
8group = pubnub.channel_group("group-test").subscription()
9
10subscription_set = pubnub.subscription_set([channel_1, channel_2, channel_x, group])
11
12subscription_set.subscribe()
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#- Whether the subscription delivers presence events for the entity to its listeners. The value
Truealso subscribes to the-pnpreschannel of the entity and enables theon_presencehandler.Nonecounts asFalse. For the events and how to receive them, see Presence events.
Sample code
Examples for Create a subscription
Syntax
1channel.subscription(with_presence: bool = None) -> PubNubSubscription
Basic usage
1def on_presence(listener):
2 def presence_callback(presence):
3 print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
4 f"{presence.subscription or presence.channel}\033[0m")
5 return presence_callback
6
7subscription = pubnub.channel("my_channel").subscription(with_presence=True)
8subscription.on_presence = on_presence('presence_listener')
9
10subscription.subscribe()
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.
subscriptionsrequired#- 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.
Sample code
Examples for Create a subscription set
Syntax
1pubnub.subscription_set(subscriptions: List[PubNubSubscription]) -> PubNubSubscriptionSet
Basic usage
1channel = "my_channel"
2
3# multiple channel subscription
4channel_1 = pubnub.channel(channel).subscription()
5channel_2 = pubnub.channel(f'{channel}.2').subscription(with_presence=True)
6channel_x = pubnub.channel(f'{channel}.*').subscription(with_presence=True)
7
8group = pubnub.channel_group("group-test").subscription()
9
10subscription_set = pubnub.subscription_set([channel_1, channel_2, channel_x, group])
11
12subscription_set.subscribe()
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.
Sample code
Examples for Create an SDK channel entity
Syntax
1pubnub.channel(channel: str) -> PubNubChannel
Basic usage
1channel = pubnub.channel("my_channel")
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.
channel_grouprequired#- The name of the channel group to subscribe to. See channel groups.
Sample code
Examples for Create an SDK channel group entity
Syntax
1pubnub.channel_group(channel_group: str) -> PubNubChannelGroup
Basic usage
1channel_group = pubnub.channel_group("channelGroupName")
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.
channelrequired#- The ID of the channel metadata object to observe. See channel metadata.
Sample code
Examples for Create an SDK channel metadata entity
Syntax
1pubnub.channel_metadata(channel: str) -> PubNubChannelMetadata
Basic usage
1channel_metadata = pubnub.channel_metadata("channelMetadata")
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.
user_idrequired#- The ID of the user metadata object to observe. See user metadata.
Sample code
Examples for Create an SDK user metadata entity
Syntax
1pubnub.user_metadata(user_id: str) -> PubNubUserMetadata
Basic usage
1user_metadata = pubnub.user_metadata("user_metadata")
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.
on_message#- Handles published messages.
on_signal#- Handles signals.
on_presence#- 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#- Handles message action events.
on_channel_metadata#- Handles channel metadata events.
on_user_metadata#- Handles user metadata events.
on_membership#- Handles membership events.
on_file#- Handles file events.
listenerrequired#- An object whose methods handle each event type. Only
pubnub.add_listener()takes it. - property of listener:
status# - 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# - Handles published messages.
- property of listener:
signal# - Handles signals.
- property of listener:
presence# - Handles presence events.
- property of listener:
message_action# - 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().
Sample code
Returns
add_listener() returns nothing.
Other examples
Examples for Add listeners
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
Basic usage
1subscription = pubnub.channel("my_channel").subscription()
2
3# using closure for reusable listener
4def on_message(listener):
5 def message_callback(message):
6 print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
7 return message_callback
8
9# without closure
10def on_message_action(message_action):
11 print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n")
12
13def on_signal(listener):
14 def signal_callback(signal):
15 print(f"\033[0;36mSignal received on: {listener}: \n{signal.publisher} says: \t{signal.message}\033[0m")
show all 22 lines1from pubnub.callbacks import SubscribeCallback
2
3# add generic listener
4class PrintListener(SubscribeCallback):
5 def status(self, _, status):
6 print(f'\033[92mPrintListener.status:\n{status.category.name}\033[0m')
7
8 def message(self, _, message):
9 print(f'\033[94mPrintListener.message:\n{message.message}\033[0m')
10
11 def presence(self, _, presence):
12 print(f'PrintListener.presence:\n{presence.uuid} {presence.event}s '
13 f'{presence.subscription or presence.channel}\033[0m')
14
15 def signal(self, _, signal):
show all 38 linesHandle messages of a subscription set
Handle messages of a subscription set
1def on_message(listener):
2 def message_callback(message):
3 print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
4 return message_callback
5
6subscription_set = pubnub.subscription_set([
7 pubnub.channel("my_channel").subscription(),
8 pubnub.channel("my_channel_2").subscription(),
9 pubnub.channel_group("cg_1").subscription()
10])
11subscription_set.on_message = on_message('set_listener')
12
13subscription_set.subscribe()
Handle presence events of a subscription
Handle presence events of a subscription
1def on_presence(listener):
2 def presence_callback(presence):
3 print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
4 f"{presence.subscription or presence.channel}\033[0m")
5 return presence_callback
6
7subscription = pubnub.channel("my_channel").subscription(with_presence=True)
8subscription.on_presence = on_presence('presence_listener')
9
10subscription.subscribe()
Add connection status listener
add_listener() adds a listener that reports the connection status of a PubNub client for Python.
Sample code
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#- The status category, for example
PNConnectedCategory. operation#- The operation that reported the status.
error#- Whether the operation failed.
error_data#- The details of the error.
status_code#- The HTTP status code of the request.
affected_channels#- The channels that the status change affects.
affected_groups#- The channel groups that the status change affects.
Examples for Add connection status listener
Syntax
1pubnub.add_listener(listener: SubscribeCallback) -> None
Basic usage
1from pubnub.pubnub import SubscribeListener
2
3class PrintListener(SubscribeListener):
4 def status(self, pubnub, status):
5 print(f'Status:\n{status.__dict__}')
6
7 def message(self, pubnub, message):
8 pass
9
10 def presence(self, pubnub, presence):
11 pass
12
13listener = PrintListener()
14pubnub.add_listener(listener)
Remove listener
remove_listener() removes an event listener from a PubNub client for Python, so the listener stops receiving events.
add_listener(). Removing an object that you never added raises ValueError.listenerrequired#- The listener object to remove. Pass the object that you passed to
add_listener().
Sample code
Returns
remove_listener() returns nothing.
Examples for Remove listener
Syntax
1pubnub.remove_listener(listener: SubscribeCallback) -> None
Basic usage
1my_listener = MySubscribeCallback()
2
3pubnub.add_listener(my_listener)
4
5# some time later
6pubnub.remove_listener(my_listener)
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.
Sample code
Returns
unsubscribe() returns nothing. The SDK sends a leave request, and its result reaches the status method of the listeners on the PubNub client.
Examples for Unsubscribe
Syntax
1subscription.unsubscribe() -> None
2subscription_set.unsubscribe() -> None
Basic usage
1# single channel subscription
2channel = pubnub.channel("my_channel")
3t1_subscription = channel.subscription()
4t1_subscription.subscribe()
5t1_subscription.unsubscribe()
Unsubscribe all
unsubscribe_all() unsubscribes every subscription and subscription set of a PubNub client for Python at once.
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.
Sample code
Returns
unsubscribe_all() returns nothing.
Examples for Unsubscribe all
Syntax
1pubnub.unsubscribe_all() -> None
Basic usage
1pubnub.unsubscribe_all()
Not recommended subscribe methods
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.