Publish API for Python-Asyncio SDK
The PubNub Python-Asyncio 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.
A builder sends its request when you await its future(). A request that fails, or fails validation, does not raise an exception. future() resolves with a PubNubAsyncioException whose result is None and whose status holds the error. Call is_error() on the awaited value before you read result.
Each builder method has a keyword argument of the same name.
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-Asyncio 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.
#
- A client without a
publish_keygets an error envelope with the messagePublish key not configured. - 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-Asyncio 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. A `None` value fails validation with the message
Message 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. An empty value fails validation with the message
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() resolves with an AsyncioEnvelope 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
A failed publish() does not raise. The awaited value is a PubNubAsyncioException with result set to None. Call is_error() on it, and read the cause from its status.
The SDK checks the inputs before it sends any request, and a failed check is reported the same way.
| Condition | Result |
|---|---|
channel is omitted or empty | Error status with the message Channel missing. |
message is None or omitted | Error status with the message Message missing. |
publish_key was not set at initialization | Error status with the message Publish key not configured. |
subscribe_key was not set at initialization | Error status with the message Subscribe key not configured. |
message or meta is not JSON-serializable | Error status 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 status for the reason. |
The token or auth_key has no write permission on the channel | Error status for HTTP status 403, with category PNAccessDeniedCategory. See Access Manager. |
| The message exceeds the size limit | Error status for HTTP status 413 over POST or 414 over GET. |
| The network is unreachable | Error status with the message Connection Error. |
Examples for Publish
Syntax
1await pubnub.publish(
2 message: Any,
3 channel: str,
4 should_store: bool,
5 meta: Any,
6 use_post: bool,
7 ttl: int,
8 custom_message_type: str
9).future() -> AsyncioEnvelope
Publish a message to a channel (Builder Pattern)
1envelope = await pubnub.publish() \
2 .channel("my_channel") \
3 .message({
4 'name': 'Alex',
5 'online': True
6 }) \
7 .custom_message_type("text-message") \
8 .future()
9if envelope.is_error():
10 print(f"Error: {envelope.status.error_data}")
Publish a message to a channel (Named Arguments)
1envelope = await 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).future()
10if envelope.is_error():
11 print(f"Error: {envelope.status.error_data}")
Publish with metadata
Publish with metadata
Publish with meta and check the status of the envelope.
1envelope = await pubnub.publish()\
2 .channel("my_channel")\
3 .message(["hello", "there"])\
4 .meta({'name': 'Alex'})\
5 .future()
6# handle publish result, status always present, result if successful
7# envelope.status.is_error() to see if error happened
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 = await pubnub.publish() \
2 .channel("my_channel") \
3 .message({'kept': True}) \
4 .should_store(True) \
5 .use_post(True) \
6 .future()
7if stored.is_error():
8 print(f"Error: {stored.status.error_data}")
9
10not_stored = await pubnub.publish() \
11 .channel("my_channel") \
12 .message({'kept': False}) \
13 .should_store(False) \
14 .use_post(True) \
15 .future()
show all 17 linesSignal
signal() sends a signal to the clients that subscribe to one channel, using a PubNub client for Python-Asyncio.
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 error status 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. An empty value fails validation with the message
Channel missing.
Sample code
Returns
signal() resolves with an AsyncioEnvelope 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
1await pubnub.signal(
2 message: Any,
3 channel: str,
4 custom_message_type: str
5).future() -> AsyncioEnvelope
Signal a message to a channel
Signal a message to a channel
1envelope = await pubnub.signal() \
2 .channel("my_channel") \
3 .message("typing_on") \
4 .future()
5if envelope.is_error():
6 print(f"Error: {envelope.status.error_data}")
Fire
fire() sends a message to Functions event handlers and Illuminate through a PubNub client for Python-Asyncio, 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. A `None` value fails validation with the message
Message missing. channelrequired#- The ID of the one channel to fire to. The method takes the ID string, not an SDK channel entity. An empty value fails validation with the message
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
Returns
fire() resolves with an AsyncioEnvelope 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
1await pubnub.fire(
2 message: Any,
3 channel: str,
4 meta: Any,
5 use_post: bool
6).future() -> AsyncioEnvelope
Fire a message to a channel
Fire a message to a channel
1envelope = await pubnub.fire() \
2 .channel("my_channel") \
3 .message({'command': 'refresh'}) \
4 .future()
5if envelope.is_error():
6 print(f"Error: {envelope.status.error_data}")
Fire a message with POST
Fire a message with POST
1envelope = await pubnub.fire().channel('my_channel').message('hello there').use_post(True).future()
2if envelope.is_error():
3 print(f"Error: {envelope.status.error_data}")
4else:
5 print('fire timetoken: %d' % envelope.result.timetoken)