TornadoTornadoTwistedAsyncioNativePythonPython-Tornado V4 Publish & Subscribe API Reference for Realtime Apps

Go to Configuration


 

These docs are for PubNub 4.0 for Python-Tornado V4 which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.0 for Python, PubNub 3.0 for Python-Tornado and PubNub 3.0 for Python-Twisted.

If you have questions about the PubNub for Python SDK, please contact us at support@pubnub.com.

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.
 
The new Jackson parser does not recognize JSONObject. Please use ObjectNode instead.
 
Publish Anytime
It is 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. Message data should not contain special Python-Tornado V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K 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.5KB) 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 please check: https://support.pubnub.com/support/discussions/topics/14000006322

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 cannot 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 (i.e. not concurrently).
  • Check that the return code is success (e.g. [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 e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not 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.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the Python-Tornado V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channelStringYesDestination of message.
    messageObjectYesThe payload.
    should_storeBooleanOptionalaccount defaultStore in history
    metaObjectOptionalNoneMeta data object which can be used with the filtering ability.

Publish a message to a channel:

from pubnub.exceptions import PubNubException

try:
    envelope = yield 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)
 
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.
The publish() operation returns a PNPublishResult which contains the following fields:
FieldTypeDescription
timetokenIntan int representation of the time token when the message was published
  1. envelope = yield 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
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. 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() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the Python-Tornado V4 SDK:
ParameterTypeRequiredDefaultsDescription
channelStringYesDestination of message.
messageObjectYesThe payload.
use_post BooleanOptionalfalseUse POST to publish.
metaObjectOptionalNoneMeta data object which can be used with the filtering ability.

Fire a message to a channel:

envelope = yield pubnub.fire().channel('my_channel').message('hello there').use_post(true).future()
print('fire timetoken: %d' % envelope.result.timetoken)
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribe_key at initialization.
By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.
If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period. This can be achieved by setting setReconnectionPolicy to PNReconnectionPolicy.LINEAR, when initializing the client.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the Python-Tornado V4 SDK:
  1. ParameterTypeRequiredDescription
    channelsString | List | TupleOptionalSubscribe to channels, Either channel or channel_group is required.
    channel_groupsString | List | TupleOptionalSubscribe to channel_groups, Either channel or channel_group is required.
    timetokenIntOptionalPass a timetoken.
    with_presenceCommandOptionalAlso subscribe to related presence information.
Subscribe to a channel:
pubnub.subscribe().channels("my_channel").execute()
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
 

PNMessageResult is returned in the Listeners.

The subscribe() operation returns a PNStatus for messages which contains the following fields:
FieldTypeDescription
category PNStatusCategoryDetails of StatusCategory are here.
is_error BooleanThis is true if an error occurred in the execution of the operation.
error_data PNErrorDataError data of the exception (if Error is true).
status_code intStatus code of the execution.
The subscribe() operation returns a PNMessageResult for messages which contains the following fields:
FieldTypeDescription
messageObjectThe message sent on channel.
subscriptionStringThe channel group or wildcard subscription match (if exists).
channelStringThe channel for which the message belongs.
timetokenIntTimetoken for the message.
user_metadataDictUser metadata.
The subscribe() operation returns a PNPresenceEventResult from presence which contains the following operations:
FieldTypeDescription
eventStringEvents like join, leave, timeout, state-change.
uuidStringuuid for event.
timestampInttimestamp for event.
occupancyIntCurrent occupancy.
subscriptionStringThe channel group or wildcard subscription match (if exists).
channelStringThe channel for which the message belongs.
timetokenInttimetoken of the message.
user_metadataDictUser metadata.
  1. import logging
    import pubnub
    
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub_tornado import PubNubTornado
    from pubnub.pubnub_tornado import SubscribeListener
    
    pubnub.set_stream_logger('pubnub', logging.DEBUG)
    
    pnconfig = PNConfiguration()
    
    pnconfig.subscribe_key = 'demo'
    pnconfig.publish_key = 'demo'
    
    pubnub = PubNubTornado(pnconfig)
    
    pubnub.add_listener(SubscribeListener())
    pubnub.subscribe().channels("my_channel").execute()
  2. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    pubnub.subscribe().channels(["my_channel1", "my_channel2"]).execute()
    
  3. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
    pubnub.subscribe()\
        .channels("my_channel")\
        .with_presence()\
        .execute()
    if envelope.event == 'join':
        envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
        envelope.timestamp # 1345546797
        envelope.occupancy # 2
    
    {
        "action" : "leave",
        "timestamp" : 1345549797,
        "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "occupancy" : 1
    }
    if envelope.event == 'timeout':
        envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
        envelope.timestamp # 1345546797
        envelope.occupancy # 0
    
    if envelope.event == 'state-change':
        envelope.uuid # 76c2c571-9a2b-d074-b4f8-e93e09f49bd
        envelope.timestamp # 1345546797
        envelope.user_metadata # {'is_typing': True}
    
    {
    	"action":"interval",
    	"timestamp":1474396578,
    	"occupancy":2
    }
    

    When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

    • joined
    • left
    • timedout

    For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "joined" : ["uuid2", "uuid3"],
        "timedout" : ["uuid1"]
    }
    

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "here_now_refresh" : true
    }
    
  4. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    pubnub.subscribe().channels("foo.*").execute();
  5. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    from pubnub.pubnub_tornado import PubNubTornado
    from pubnub.pubnub_tornado import SubscribeListener
    
    class MySubscribeListener(SubscribeListener):
        def __init__(self):
            pass
    
        def status(self, pubnub, status):
            if status.category == PNStatusCategory.PNConnectedCategory:
                state = {
                    'field_a': 'awesome',
                    'field_b': 10
                }
                pubnub.ioloop.add_future(
                        pubnub.set_state().channels('my_channel').\
                            channel_groups('awesome_channel_groups').state(state).future()
                    )
            else:
                pass
    
        def message(self, pubnub, message):
            pass
    
        def presence(self, pubnub, presence):
            pass
    
    pubnub = PubNubTornado(pnconfig)
    
    my_listener = MySubscribeListener()
    pubnub.add_listener(my_listener)
    
    pubnub.subscribe().channels("my_channel").execute()
    
  6. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe().channel_groups("awesome_channel_group").execute()
  7. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe().channel_groups(["cg1", "cg2"]).with_presence().execute()
    

When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the Python-Tornado V4 SDK
  1. ParameterTypeRequiredDescription
    channelsString | List | TupleOptionalSubscribe to channels, Either channel or channel_group is required.
    channel_groupsString | List | TupleOptionalSubscribe to channel_groups, Either channel or channel_group is required
Unsubscribe from a channel:
pubnub.unsubscribe().channels("my_channel").execute()
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
The output below demonstrates the response to a successful call:
if envelope.event == 'leave':
    envelope.uuid # 175c2c67-b2a9-470d-8f4b-1db94f90e39e
    envelope.timestamp # 1345546797
    envelope.occupancy # 2
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.unsubscribe().channels(["my_channel1", "my_channel2"]).execute();
    {
    	"action" : "leave"
    }
    
  2. pubnub.unsubscribe().channels_groups(["my_group1", "my_group2").execute()
    {
    	"action": "leave"
    }
    
Unsubscribe from all channels and all channel groups
pubnub.unsubscribe_all();
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNOperationType, PNStatusCategory

class MySubscribeCallback(SubscribeCallback):
    def status(self, pubnub, status):
        pass
        # The status object returned is always related to subscribe but could contain
        # information about subscribe, heartbeat, or errors
        # use the operationType to switch on different options
        if status.operation == PNOperationType.PNSubscribeOperation \
                or status.operation == PNOperationType.PNUnsubscribeOperation:
            if status.category == PNStatusCategory.PNConnectedCategory:
                pass
                # This is expected for a subscribe, this means there is no error or issue whatsoever
            elif status.category == PNStatusCategory.PNReconnectedCategory:
                pass
                # This usually occurs if subscribe temporarily fails but reconnects. This means
                # there was an error but there is no longer any issue
            elif status.category == PNStatusCategory.PNDisconnectedCategory:
                pass
                # This is the expected category for an unsubscribe. This means there
                # was no error in unsubscribing from everything
            elif status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
                pass
                # This is usually an issue with the internet connection, this is an error, handle
                # appropriately retry will be called automatically
            elif status.category == PNStatusCategory.PNAccessDeniedCategory:
                pass
                # This means that PAM does not allow this client to subscribe to this
                # channel and channel group configuration. This is another explicit error
            else:
                pass
                # This is usually an issue with the internet connection, this is an error, handle appropriately
                # retry will be called automatically
        elif status.operation == PNOperationType.PNSubscribeOperation:
            # Heartbeat operations can in fact have errors, so it is important to check first for an error.
            # For more information on how to configure heartbeat notifications through the status
            # PNObjectEventListener callback, consult <link to the PNCONFIGURATION heartbeart config>
            if status.is_error():
                pass
                # There was an error with the heartbeat operation, handle here
            else:
                pass
                # Heartbeat operation was successful
        else:
            pass
            # Encountered unknown status type

    def presence(self, pubnub, presence):
        pass  # handle incoming presence data

    def message(self, pubnub, message):
        pass  # handle incoming messages


pubnub.add_listener(MySubscribeCallback())
my_listener = MySubscribeCallback()

pubnub.add_listener(my_listener)

# some time later
pubnub.remove_listener(my_listener)
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory

class HandleDisconnectsCallback(SubscribeCallback):
    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
            # internet got lost, do some magic and call reconnect when ready
            pubnub.reconnect()
        elif status.category == PNStatusCategory.PNTimeoutCategory:
            # do some magic and call reconnect when ready
            pubnub.reconnect()
        else:
            logger.debug(status)

    def presence(self, pubnub, presence):
        pass

    def message(self, pubnub, message):
        pass

disconnect_listener = HandleDisconnectsCallback()

pubnub.add_listener(disconnect_listener)
CategoryDescription
PNTimeoutCategoryProcessing has failed because of request time out.
PNBadRequestCategoryPubNub API server was unable to parse your request correctly.
PNNetworkIssuesCategory
A subscribe event experienced an exception when running.
PNReconnectedCategory
SDK was able to reconnect to PubNub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNCancelledCategoryRequest was cancelled by user.
PNUnknownCategoryNo specific category was assigned to the request.
 
SubscribeListener should not be used with high-performance sections of your app.

Go to Presence