Publish API for Python SDK
The PubNub Python SDK sends a message to one channel per call with publish() and a small payload that PubNub never stores with signal().
All three calls require the publish key of your keyset, which you pass as publish_key when you create the client. See Initialization.
Each builder method has a keyword argument of the same name. A failed request raises a PubNubException from .sync(). With .pn_async(callback), the callback receives a status where status.is_error() returns True.
Request execution and return values
You can decide whether to perform the Python SDK operations synchronously or asynchronously.
-
.sync()returns anEnvelopeobject, which has two fields:Envelope.result, whose type differs for each API, andEnvelope.statusof typePnStatus.1pubnub.publish() \
2 .channel("myChannel") \
3 .message("Hello from PubNub Python SDK") \
4 .sync() -
.pn_async(callback)returnsNoneand passes the values ofEnvelope.resultandEnvelope.statusto a callback you must define beforehand.1def my_callback_function(result, status):
2 print(f'TT: {result.timetoken}, status: {status.category.name}')
3
4pubnub.publish() \
5 .channel("myChannel") \
6 .message("Hello from PubNub Python SDK") \
7 .pn_async(my_callback_function)
For delivery guarantees, ordering, and the difference between messages and signals, see Publishing messages with PubNub. For payload shapes and metadata in practice, see Send different message types. To receive what you publish, see Subscribe. To fix a failed request, see Troubleshooting.
Publish
publish() sends a message to one channel through a PubNub client for Python and reports the timetoken that PubNub assigned to the message. PubNub delivers the message to the clients that subscribe to the channel.
Publish-processing latency, the time PubNub takes to accept and acknowledge a publish request, is about 0.5 ms within the same region.
#
.sync()raises aPubNubExceptionwith the messagePublish key not configuredwhen the client has nopublish_key.- A client does not need to subscribe to a channel to publish to it.
-
Each call publishes to one channel. To reach several channels, call
publish()once per channel. - By default, a PubNub client for Python does not retry a failed publish, so your application owns the retry.
#
PubNub SDKs connect over TLS 1.2 by default, except the Lua SDK and the unsupported Twisted SDK, where you set ssl to true.
To encrypt the message content, configure crypto_module during initialization. The SDK then encrypts only message and sends channel and meta unencrypted. See crypto_module for the setup and Data security and encryption for background.
#
A message is the basic unit of data flowing through PubNub, and its payload is any JSON-serializable value. String content in a message payload can include any single-byte or multi-byte UTF-8 character. Pass objects as they are. The SDK serializes message and meta, so don't call json.dumps() first. Avoid special classes and functions.
Metadata values must be JSON-serializable. The SDK sends meta only when it is not empty.
#
PubNub supports message sizes up to 2 MB. PubNub default message size limit is 32 KiB, which includes the channel name and any metadata. Contact support or your account manager to request higher message size limits and help on large message design patterns.
PubNub rejects a larger publish. A POST request fails with HTTP status 413 and a GET request fails with HTTP status 414. For all publish limits, see API limits. To calculate the payload size, use the message size calculator.
#
There is no hard publish rate limit for a keyset in good standing. As a best practice, keep publish rates at 10 to 15 messages per second per channel. Faster rates are possible, but a slow subscriber can fall behind the connection's message buffer.
#
You can optionally provide the custom_message_type parameter to add your business-specific label or category to the message, for example text, action, or poll.
A custom message type accepted by the PubNub Publish, Signal, and File Sharing APIs must be a case-sensitive alphanumeric string of 3 to 50 characters. Dashes (-) and underscores (_) are allowed. The value cannot start with a special character or with the reserved prefixes pn_ or pn-.
messagerequired#- The payload to publish. Any JSON-serializable value, such as an object, array, string, or number. The SDK rejects
NonewithMessage missing. Other falsy values such as0,False, and""are valid. channelrequired#- The ID of the one channel to publish to. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with
Channel missing. should_store#- Whether PubNub stores the message in Message Persistence.
truestores it andfalseskips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the Message Persistence setting of the keyset applies. meta#- Metadata that PubNub attaches to the message. Subscribers can use it in message filters.
use_post#- Whether the message travels in the body of an HTTP POST request.
falseputs the message in the URL path of an HTTP GET request. ttl#- The number of hours that Message Persistence keeps the message. When omitted, the retention of the keyset applies. PubNub ignores this value when it does not store the message. The SDK sends
ttlonly when the value is not0. A keyset using Unlimited retention ignores any per-message TTL and stores the message indefinitely. custom_message_type#- A business-specific label for the message, for example
text,action, orpoll. The accepted format is in the Custom message type note for this method.
Sample code
Publish a message to a channel
Returns
publish() returns an Envelope whose result is a PNPublishResult and whose status is a PNStatus.
PNPublishResult
timetoken#- The timetoken that PubNub assigned to the message. PubNub assigns every published message a server-side timetoken: a monotonically increasing 17-digit value precise to 100 nanoseconds (10⁻⁷ s), the number of 100-nanosecond intervals since the Unix epoch. For how to use it, see Publish response and the timetoken.
Other examples
Publish errors
publish() raises a PubNubException when it fails, and the message of the exception names the cause.
Validation errors happen before the SDK sends any request.
| Condition | Result |
|---|---|
channel is omitted or empty | PubNubException with the message Channel missing. |
message is None or omitted | PubNubException with the message Message missing. |
publish_key was not set at initialization | PubNubException with the message Publish key not configured. |
subscribe_key was not set at initialization | PubNubException with the message Subscribe key not configured. |
message or meta is not JSON-serializable | PubNubException with the message Trying to publish not JSON serializable object. |
custom_message_type is not in the accepted format | The SDK does not check the format, so PubNub rejects the request. Read the exception message for the reason. |
The token or auth_key has no write permission on the channel | PubNubException for HTTP status 403, with category PNAccessDeniedCategory in the status. See Access Manager. |
| The message exceeds the size limit | PubNubException for HTTP status 413 over POST or 414 over GET. |
| The network is unreachable | PubNubException with the message Connection Error. |
Examples for Publish
Syntax
1pubnub.publish() \
2 .message(message: Any) \
3 .channel(channel: str) \
4 .should_store(should_store: bool) \
5 .meta(meta: Any) \
6 .use_post(use_post: bool) \
7 .ttl(ttl: int) \
8 .custom_message_type(custom_message_type: str) \
9 .sync() -> PNPublishResultEnvelope
Publish a message to a channel (Builder Pattern)
1envelope = pubnub.publish() \
2 .channel("my_channel") \
3 .message({
4 'name': 'Alex',
5 'online': True
6 }) \
7 .custom_message_type("text-message") \
8 .sync()
Publish a message to a channel (Named Arguments)
1envelope = pubnub.publish(
2 channel="my_channel",
3 message={
4 'name': 'Sam',
5 'online': False
6 },
7 custom_message_type="text-message",
8 meta={'origin': 'docs'}
9).sync()
Publish with metadata
Publish with metadata
Publish with .pn_async() and read the result in a callback.
1def publish_callback(result, status):
2 # handle publish result, status always present, result if successful
3 # status.is_error() to see if error happened
4 if status.is_error():
5 print(f"Publish failed: {status.error_data}")
6 else:
7 print(f"Publish timetoken: {result.timetoken}")
8
9pubnub.publish().channel("my_channel").message(["hello", "there"]) \
10 .meta({'name': 'Alex'}).pn_async(publish_callback)
Store the message and publish with POST
Store the message and publish with POST
Set should_store to choose whether Message Persistence keeps each message, and send the body with use_post.
1stored = pubnub.publish() \
2 .channel("my_channel") \
3 .message({'kept': True}) \
4 .should_store(True) \
5 .use_post(True) \
6 .sync()
7
8not_stored = pubnub.publish() \
9 .channel("my_channel") \
10 .message({'kept': False}) \
11 .should_store(False) \
12 .use_post(True) \
13 .sync()
Signal
signal() sends a signal to the clients that subscribe to one channel, using a PubNub client for Python.
PubNub never stores signals in Message Persistence, regardless of keyset settings. Signal payloads are limited to 64 bytes. A signal cannot trigger mobile push notifications. A signal does not support meta, should_store, ttl, or use_post. The SDK does not encrypt the message of a signal, even when a crypto_module is configured.
PubNub rejects a payload over the limit. The PubNubException carries the HTTP status code and the reason.
signal() fails validation when channel is missing or empty, or when publish_key or subscribe_key is missing. The SDK does not check message. See Publish errors.
messagerequired#- The payload to send. Any JSON-serializable value.
channelrequired#- The ID of the one channel to send the signal to. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with
Channel missing.
Sample code
Signal a message to a channel
Returns
signal() returns an Envelope whose result is a PNSignalResult and whose status is a PNStatus.
PNSignalResult
timetoken#- The timetoken that PubNub assigned to the signal.
Examples for Signal
Syntax
1pubnub.signal() \
2 .message(message: Any) \
3 .channel(channel: str) \
4 .custom_message_type(custom_message_type: str) \
5 .sync() -> SignalResultEnvelope
Signal a message to a channel (Builder Pattern)
1envelope = pubnub.signal() \
2 .channel("my_channel") \
3 .message("typing_on") \
4 .sync()
Signal a message to a channel (Named Arguments)
1signal = pubnub.signal(channel="my_channel", message='hello there', custom_message_type='text-message').sync()
2print(f'signal timetoken: {signal.result.timetoken}')
Fire
fire() sends a message to Functions event handlers and Illuminate through a PubNub client for Python, bypassing subscribers and storage.
The message goes straight to the handlers registered on the target channel and triggers them. Each handler can read the request body. PubNub does not replicate a fired message to subscribers and does not store it in Message Persistence.
messagerequired#- The payload to publish. Any JSON-serializable value, such as an object, array, string, or number. The SDK rejects
NonewithMessage missing. channelrequired#- The ID of the one channel to fire to. The method takes the ID string, not an SDK channel entity. The SDK rejects an empty value with
Channel missing. meta#- Metadata that PubNub attaches to the message. Subscribers can use it in message filters.
use_post#- Whether the message travels in the body of an HTTP POST request.
falseputs the message in the URL path of an HTTP GET request.
Sample code
Fire a message to a channel
Returns
fire() returns an Envelope whose result is a PNFireResult and whose status is a PNStatus.
PNFireResult
timetoken#- The timetoken that PubNub assigned to the fired message.
Other examples
Fire errors
fire() fails validation on the same inputs as publish(): a missing channel, a None message, or a missing publish_key or subscribe_key. See Publish errors.
Examples for Fire
Syntax
1pubnub.fire() \
2 .message(message: Any) \
3 .channel(channel: str) \
4 .meta(meta: Any) \
5 .use_post(use_post: bool) \
6 .sync() -> PNFireResultEnvelope
Fire a message to a channel (Builder Pattern)
1envelope = pubnub.fire() \
2 .channel("my_channel") \
3 .message({'command': 'refresh'}) \
4 .sync()
Fire a message to a channel (Named Arguments)
1fire = pubnub.fire(channel="my_channel", message='hello there').sync()
2print(f'fire timetoken: {fire.result.timetoken}')
Fire a message with POST
Fire a message with POST
1envelope = pubnub.fire() \
2 .channel('my_channel') \
3 .message('hello there') \
4 .use_post(True) \
5 .sync()
6print(f'fire timetoken: {envelope.result.timetoken}')