Publish/Subscribe API for PubNub Python-Asyncio SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 30ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
The publish()
function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publish_key
at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to True
during initialization.
ObjectNode
The new Jackson parser does not recognize JSONObject. Please use ObjectNode instead.
Publish Anytime
It's not required to be subscribed to a channel in order to publish to that channel.
Message Data
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data
should not contain special Python classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Don't JSON serialize
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
Message Size
The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
For further details, check Calculating Message Payload Size Before Publish.
Message Publish Rate
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably
There are some best practices to ensure messages are delivered when publishing to a channel:
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (for example,
[1,"Sent","136074940..."]
) - Publish the next message only after receiving a success return code.
- If a failure code is returned (
[0,"blah","<timetoken>"]
), retry the publish. - Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
- Throttle publish bursts in accordance with your app's latency needs, for example, Publish no faster than 5 msgs per second to any one channel.
Method(s)
To Publish a message
you can use the following method(s) in the Python-asyncio SDK:
pubnub.publish() \
.channel(String) \
.message(Object) \
.should_store(Boolean) \
.meta(Dictionary) \
.use_post(Boolean)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | String | Yes | Destination of message . | |
message | Object | Yes | The payload. | |
should_store | Boolean | Optional | account default | Store in history |
meta | Object | Optional | None | Meta data object which can be used with the filtering ability. |
Basic Usage
Publish a message to a channel
from pubnub.exceptions import PubNubException
try:
envelope = await pubnub.publish().channel("my_channel").message({
'name': 'Alex',
'online': True
}).future()
print("publish timetoken: %d" % envelope.result.timetoken)
except PubNubException as e:
handle_exception(e)
Subscribe to the channel
Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
Returns
The publish()
operation returns a PNPublishResult
which contains the following fields:
Field | Type | Description |
---|---|---|
timetoken | Int | an int representation of the timetoken when the message was published |
Other Examples
Publish with metadata
envelope = await pubnub.publish()\
.channel("my_channel")\
.message(["hello", "there"])\
.meta({'name': 'Alex'})\
.future()
# handle publish result, status always present, result if successful
# envelope.status.is_error() to see if error happened
Fire
The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire()
isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the Python-asyncio SDK:
pubnub.fire() \
.channel(String) \
.message(Object) \
.meta(Object) \
.use_post(Boolean)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | String | Yes | Destination of message . | |
message | Object | Yes | The payload. | |
use_post | Boolean | Optional | False | Use POST to publish. |
meta | Object | Optional | None | Meta data object which can be used with the filtering ability. |
Basic Usage
Fire a message to a channel
envelope = await pubnub.fire().channel('my_channel').message('hello there').use_post(True).future()
print('fire timetoken: %d' % envelope.result.timetoken)
Signal
The signal()
function is used to send a signal to all subscribers of a channel.
By default, signals are limited to a message payload size of 64
bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.
Method(s)
To Signal a message
you can use the following method(s) in the Python-asyncio SDK:
pubnub.signal() \
.message(Object) \
.channel(String)
Parameter | Type | Required | Description |
---|---|---|---|
message | Object | Yes | The payload. |
channel | String | Yes | Destination of message . |
Basic Usage
Signal a message to a channel
envelope = await pubnub.signal() \
.channel('some_channel') \
.message('foo') \
.future()
Response
Field | Type | Description |
---|---|---|
timetoken | int | An int representation of the timetoken when Signal was sent. |
Subscribe
The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified entity or set of entities. To subscribe successfully, you must configure the appropriate subscribeKey
at initialization.
Entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific entity:
ChannelRepresentation
ChannelGroupRepresentation
UserMetadataRepresentation
ChannelMetadataRepresentation
A newly subscribed client receives messages after the subscribe()
call completes. You can configure automatic retries to attempt to reconnect automatically and retrieve any available messages if a client gets disconnected.
Subscription scope
Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:
Subscription
, created from an entity with a scope of only that entity (for example, a particular channel)SubscriptionSet
, created from the PubNub client with a global scope (for example, all subscriptions created on a singlepubnub
object ). A subscription set can have one or more subscriptions.
The event listener is a single point through which your app receives all the messages, signals, and events in the entities you subscribed to. For information on adding event listeners, refer to Event listeners.
Create a subscription
An entity-level Subscription
allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscription
s is useful for handling various message/event types differently in each channel.
# entity-based, local-scoped
subscription = pubnub.channel(f'{channel}').subscription(timetoken: Optional[int] = None, region: Optional[str] = None, with_presence: bool = False)
Parameter | Type | Required | Description |
---|---|---|---|
timetoken | int | No | Timetoken from which to return any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service. If the value is not a 17-digit number, the provided value will be ignored. |
region | String | No | The region the message was published in. |
with_presence | bool | No | Whether presence updates for userId should be delivered through the listener streams. |
Create a subscription set
A client-level SubscriptionSet
allows you to receive messages and events for all entities. A single SubscriptionSet
is useful for similarly handling various message/event types in each channel.
# client-based, general-scoped
subscription_set = pubnub.subscription_set(subscriptions: List[PubNubSubscription])
Parameter | Type | Required | Description |
---|---|---|---|
subscriptions | List[PubNubSubscription] | Yes | Channels/Channel group subscriptions. |
Method(s)
Subscription
and SubscriptionSet
use the same subscribe()
method.
Subscribe
To subscribe, you can use the following method in the Python SDK:
subscription.subscribe()
Basic usage
# single channel subscription
channel = pubnub.channel(f'{channel}')
t1_subscription = channel.subscription()
t1_subscription.subscribe()
# multiple channel subscription
channel_1 = pubnub.channel(channel).subscription()
channel_2 = pubnub.channel(f'{channel}.2').subscription(with_presence=True)
channel_x = pubnub.channel(f'{channel}.*').subscription(with_presence=True)
group = pubnub.channel_group('group-test').subscription()
subscription_set = pubnub.subscription_set([channel_1, channel_2, channel_x, group])
set_subscription = subscription_set.subscribe()
Returns
The subscribe()
method doesn't have a return value.
Entities
Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).
Create channels
This method returns a local PubNubChannel
entity.
pubnub.channel(String)
Parameter | Type | Required | Description |
---|---|---|---|
channel | String | Yes | The name of the channel to create a subscription of. |
Basic usage
pubnub.channel(f'{channel1}')
Create channel groups
This method returns a local PubNubChannelGroup
entity.
pubnub.channel_group(String)
Parameter | Type | Required | Description |
---|---|---|---|
channel_group | String | Yes | The name of the channel group to create a subscription of. |
Basic usage
pubnub.channel_group("channelGroupName")
Create channel metadata
This method returns a local PubNubChannelMetadata
entity.
pubnub.channel_metadata(String)
Parameter | Type | Required | Description |
---|---|---|---|
channel_metadata | String | Yes | The String identifier of the channel metadata object to create a subscription of. |
Basic usage
pubnub.channel_metadata("channelMetadata")
Create user metadata
This method returns a local PubNubUserMetadata
entity.
pubnub.user_metadata(String)
Parameter | Type | Required | Description |
---|---|---|---|
user_metadata | String | Yes | The String identifier of the user metadata object to create a subscription of. |
Basic usage
pubnub.userMetadata("user_metadata")
Event listeners
Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.
You can attach listeners to the instances of Subscription
, SubscriptionSet
, and, in the case of the connection status, the PubNub client.
Add listeners
You can implement multiple listeners or register an event-specific listener that receives only a selected type, like message
or file
.
Method(s)
# Add event-specific listeners
# using closure for reusable listener
def on_message(listener):
def message_callback(message):
print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
return message_callback
# without closure
def on_message_action(message_action):
print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n")
def on_presence(listener):
def presence_callback(presence):
print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
show all 75 lines