PythonNativeNativeTwistedTornadoAsyncioPython V4 Storage & Playback API Reference for Realtime Apps

 

These docs are for PubNub 4.0 for Python 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 PubNub Storage and Playback Service provides realtime access to history for all messages published to PubNub. Each published message is timestamped to the nearest 10 nanoseconds, and is stored across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption, ensuring that they are not readable while stored on PubNub's network.

Messages can be stored for a configurable duration or forever, as controlled by the retention policy that is configured on your account. The following options are available: 1 day, 7 days, 1 month, and Forever.


Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-.
This function fetches historical messages of a channel.
It is possible to control how messages are returned and in what order, for example you can:
  • Search for messages starting on the newest end of the timeline (default behavior - reverse = False)
  • Search for messages from the oldest end of the timeline by setting reverse to True.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the count parameter.
 
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
To run History you can use the following method(s) in the Python V4 SDK
  1. Parameter Type Required Defaults Description
    channel String Yes   Specifies channel to return history messages from.
    include_meta Boolean No False Specifies whether or not the message's meta information should be returned.
    reverse Boolean Optional False Setting to True will traverse the time line in reverse starting with the oldest message first.
    include_timetoken Boolean Optional False Whether event dates time tokens should be included in response or not.
    start Int Optional   Time token delimiting the start of time slice (exclusive) to pull messages from.
    end Int Optional   Time token delimiting the end of time slice (inclusive) to pull messages from.
    count Int Optional   Specifies the number of historical messages to return.
 
Using the reverse parameter:
Messages are always returned sorted in ascending time direction from Storage/History regardless of reverse. The reverse direction matters when you have more than 100 (or count, if it's set) messages in the time interval, in which case reverse determines the end of the time interval from which it should start retrieving the messages.
Retrieve the last 100 messages on a channel:
envelope = pubnub.history().channel("history_channel").count(100).sync()
The history() operation returns a PNHistoryResult which contains the following fields:
MethodTypeDescription
messages
List
List of messages of type PNHistoryItemResult. See PNHistoryItemResult for more details.
start_timetoken
Int
Start timetoken.
end_timetoken
Int
End timetoken.
MethodTypeDescription
timetoken
Int
Timetoken of the message.
entry
Object
Message.
  1. envelope = pubnub.history().channel("my_channel").count(3).reverse(True).sync()
    
    {
        end_timetoken: 13406746729185766,
        start_timetoken: 13406746780720711,
        messages: [{
            crypto: None,
            entry: 'Pub1',
            timetoken: None
        },{
            crypto: None,
            entry: 'Pub2',
            timetoken: None
        },{
            crypto: None,
            entry: 'Pub2',
            timetoken: None
        }]
    }
  2. pubnub.history()\
        .channel("my_channel")\
        .start(13847168620721752)\
        .reverse(true)\
        .sync()
    {
        end_timetoken: 13406746729185766,
        start_timetoken: 13406746780720711,
        messages: [{
            crypto: None,
            entry: 'Pub4',
            timetoken: None
        },{
            crypto: None,
            entry: 'Pub5',
            timetoken: None
        },{
            crypto: None,
            entry: 'Pub6',
            timetoken: None
        }]
    }
  3. pubnub.history()\
        .channel("my_channel")\
        .count(100)\
        .start(-1)\
        .end(13847168819178600)\
        .reverse(True)\
        .sync()
    {
        end_timetoken: 13406746729185766,
        start_timetoken: 13406746780720711,
        messages: [{
            crypto: None,
            entry: 'Pub4',
            timetoken: None
        },{
            crypto: None,
            entry: 'Pub5',
            timetoken: None
        },{
            crypto: None,
            entry: 'Pub6',
            timetoken: None
        }]
    }
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token as the argument.
    def get_all_messages(start_tt):
        def history_callback(result, status):
            msgs = result.messages
            start = result.start_timetoken
            end = result.end_timetoken
            count = len(msgs)
    
            if count > 0:
                print("%d" % count)
                print("start %d" % start)
                print("end %d" % end)
    
            if count == 100:
                get_all_messages(start)
    
        pubnub.history()\
            .channel('history_channel')\
            .count(100)\
            .start(start_tt)\
            .pn_async(history_callback)
    
    
    get_all_messages(14759343456292767)
  5. pubnub.history()\
        .channel("my_channel")\
        .count(100)\
        .include_tometoken()
        .sync()

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-.

This function fetches historical messages from multiple channels. The includeMessageActions or includeActions flag also allows you to fetch message actions along with the messages.

It's possible to control how messages are returned and in what order. For example, you can:

  • Search for messages starting on the newest end of the timeline.
  • Search for messages from the oldest end of the timeline.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Retrieve a specific (maximum) number of messages using the count parameter.

Batch history returns up to 100 messages on a single channel, or 25 per channel on a maximum of 500 channels. Use the start and end timestamps to page through the next batch of messages.

Start and End parameter usage clarity

If you specify only the start parameter (without end), you will receive messages that are older than the start timetoken.

If you specify only the end parameter (without start), you will receive messages from that end timetoken and newer.

Specify values for both start and end parameters to retrieve messages between those timetokens (inclusive of the end value).

Keep in mind that you will still receive a maximum of 100 messages (or 25, for multiple channels) even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken are necessary to page through the full set of results if more messages meet the timetoken values.

To run Fetch History, you can use the following method(s) in the Python V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channelsList<string>Yesn/aSpecifies the channels for which to return history
    startIntNon/aTimetoken delimiting the exclusive start of the time slice from which to pull messages
    endIntNon/aTimetoken delimiting the inclusive end of the time slice from which to pull messages
    maximum_per_channelIntNo25 or 100Specifies the number of historical messages to return. If include_message_actions is True, 25 is the default (and maximum) value; otherwise, default and maximum is 100 for a single channel, or 25 for multiple channels.
    include_message_actionsBooleanNoFalseSet to True to retrieve history messages with their associated message actions. If you include message actions, the fetch_messages() method is limited to one channel only.
    include_metaBooleanNoFalseWhether to include message metadata within response or not
Retrieve the last message on a channel:
def my_fetch_messages_callback(envelope, status):
    if not status.is_error():
        # Messages successfully retrieved from the specified channel.

        print("Fetch Messages Result:\n")
        for message in envelope.channels["my_channel"]:
            print("Message: %s" % message.message)
            print("Meta: %s" % message.meta)
            print("Timetoken: %s" % message.timetoken)

            for action_type in message.actions:
                print("\nMessage Action type: " + action_type)
                for action_value in message.actions[action_type]:
                    print("Message Action value: %s" % action_value)
                    for action in message.actions[action_type][action_value]:
                        print("Message Action timetoken: %s" % action['actionTimetoken'])
                        print("Message Action uuid: %s" % action['uuid'])

            print("")
    else:
        # Handle fetch messages error.
        pass

pubnub.fetch_messages()\
    .channels(["my_channel"])\
    .maximum_per_channel(25)\
    .include_message_actions(True)\
    .include_meta(True)\
    .pn_async(my_fetch_messages_callback)

The response is of the type PNFetchMessagesResult.

MethodTypeDescription
channelsDict

Dictionary of PNFetchMessageItem

start_timetokenInt

Start timetoken

end_timetokenInt

End timetoken

PNFetchMessageItem is defined as follows:

MethodTypeDescription
messageStringThe message
metaAny

Meta value

timetokenInt

Timetoken of the message

actionsList

A 3-dimensional List of message actions, grouped by action type and value


Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-.
Removes the messages from the history of a specific channel.
 
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Admin Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the Python V4 SDK.
  1. ParameterTypeRequiredDefaultsDescription
    channelStringYesSpecifies channels to delete messages from.
    startIntOptionalTime token delimiting the start of time slice (inclusive) to delete messages from.
    endIntOptionalTime token delimiting the end of time slice (exclusive) to delete messages from.
envelope = PubNub(pnconf).delete_messages() \
    .channel("my-ch") \
    .start(123) \
    .end(456) \
    .sync()

  1. To delete a specific message, pass the publish timetoken (received from a successful publish) in the End parameter and timetoken +/- 1 in the Start parameter. e.g. if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.
    envelope = PubNub(pnconf).delete_messages() \
        .channel("my-ch") \
        .start(15526611838554310) \
        .end(15526611838554309) \
        .sync()

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-.
Returns the number of messages published on one or more channels since a given time. The count returned is the number of messages in history with a timetoken value greater than or equal to than the passed value in the channel_timetokensparameter.
 For keys with unlimited message retention enabled, this method considers only messages published in the last 7 days.
You can use the following method(s) in the Python V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channel StringYesThe channels to fetch the message count. Single channel or multiple channels, separated by comma are accepted.
    channel_timetokens ListYesnullA list of timetokens ordered the same way as channels. Timetokens can be str or int type.
envelope = pn.message_counts().channel('unique_1').channel_timetokens([15510391957007182]).sync()
print(envelope.result.channels['unique_1'])
  1. envelope = pn.message_counts().channel('unique_1,unique_100').channel_timetokens([15510391957007182, 15510391957007184]).sync()
    print(envelope.result.channels)