File Sharing API for Python SDK
The PubNub Python SDK uploads, lists, downloads, and deletes files on channels with File Sharing, and send_file() publishes a file message that announces each upload.
File Sharing must be enabled for the keyset in the Admin Portal. A file can be up to 5 MB. When Access Manager (v2/v3) is enabled, file operations need channel permissions. For how File Sharing works, retention, and permissions, see Files.
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)
A failed request raises a PubNubException from .sync(). The methods list_files(), get_file_url(), and delete_file() accept their parameters as keyword arguments or through builder methods of the same name. The methods send_file(), download_file(), and publish_file_message() take no arguments, so set their parameters through builder methods.
Send file
send_file() uploads a file to a channel through a PubNub client for Python, then publishes a file message that announces the upload.
send_file() requests an upload URL from PubNub, uploads the file to the storage service, and publishes the file message with the file ID and name. For the publish step, see Publish file message.
Subscribers to the channel receive a file event with the file ID, the file name, and the optional message that came with the upload. The Python SDK does not deliver file events to listeners, so read the file message with fetch_messages() from Message Persistence instead.
To encrypt files, set cipher_key on PNConfiguration. The SDK then encrypts the file content with the configured crypto module, or with the legacy module if you set none. It also encrypts the file message, which holds message, the file ID, and the file name. The SDK sends channel and meta unencrypted.
channelrequired#- ID of the channel to upload the file to. A request without a channel fails validation with the message
Channel missing. file_namerequired#- Name of the file to upload, which PubNub stores it under. A request without a file name fails validation with the message
File name is missing.. file_objectrequired#- Content to upload, as a binary file object opened for reading or as
bytes. A request without content fails validation with the messageFile object is missing.. message#- Message that travels with the file, such as a caption. Subscribers receive it in the file event.
should_store#- Whether PubNub stores the file message in Message Persistence.
truestores it andfalseskips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sendsstore=0, so PubNub does not store the file message. ttl#- The number of hours that Message Persistence keeps the file message. When omitted, the SDK sends
0, and the retention of the keyset applies. PubNub ignores this value when it does not store the message. meta#- Metadata that PubNub attaches to the file message. Subscribers can use it in message filters.
custom_message_type#- A business-specific label for the message, for example
text,action, orpoll.
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-.
The deprecated cipher_key builder method is documented in Deprecated cipher_key parameter.
Memory usage for large files
The SDK doesn't cap upload size. Your keyset's file size limit is 5 MB by default and can differ. The method send_file() reads the entire file into memory to encrypt and upload it, so memory use grows with file size.
Enforce your keyset's configured limit in your own upload path before calling send_file().
Sample code
Returns
send_file() returns an Envelope whose result is a PNSendFileResult and whose status is a PNStatus.
PNSendFileResult
Other examples
Examples for Send file
Syntax
1pubnub.send_file() \
2 .channel(channel: str) \
3 .file_name(file_name: str) \
4 .file_object(file_object: Union[BinaryIO, bytes]) \
5 .message(message: Any) \
6 .should_store(should_store: bool) \
7 .ttl(ttl: int) \
8 .meta(meta: Any) \
9 .custom_message_type(custom_message_type: str) \
10 .sync() -> Envelope
Basic usage
The sample reads the file from file_path, the path of the file to upload.
1with open("sample.gif", "rb") as sample_file:
2 response = pubnub.send_file() \
3 .channel("ch1") \
4 .file_name("sample.gif") \
5 .message({"test_message": "test"}) \
6 .should_store(True) \
7 .file_object(sample_file) \
8 .sync()
9print("File sent successfully. File ID:", response.result.file_id)
Send file with a custom message type
Send file with a custom message type
1with open("sample.gif", "rb") as sample_file:
2 response_2 = pubnub.send_file() \
3 .channel("ch1") \
4 .file_name("sample.gif") \
5 .message("Hey, it's gif not jif") \
6 .custom_message_type("file-message") \
7 .should_store(True) \
8 .file_object(sample_file) \
9 .sync()
10print("File sent successfully. File ID:", response_2.result.file_id)
Send file with push notification
Send file with push notification
Trigger push notifications when sharing files
To send mobile push notifications when sharing a file, include pn_apns (for iOS) and/or pn_fcm (for Android) payloads in the message parameter of the send_file method.
When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.
1message = {
2 "text": "Check out this file!",
3 "pn_apns": {
4 "aps": {
5 "alert": {"title": "New File", "body": "A file was shared"}
6 },
7 "pn_push": [{
8 "targets": [{"topic": "com.yourapp.bundleid", "environment": "production"}],
9 "version": "v2"
10 }]
11 },
12 "pn_fcm": {
13 "notification": {"title": "New File", "body": "A file was shared"}
14 }
15}
show all 18 linesFor more details on push notification payload structure, see the iOS Push and Android Push documentation.
To prevent the sender from receiving their own push notification, add their device token to excluded_devices in the pn_push targets.
List channel files
list_files() returns the files that File Sharing stores for a channel, using a PubNub client for Python.
channelrequired#- ID of the channel to list the files of. A request without a channel fails validation with the message
Channel missing. limit#- Number of files to return in one call. A single list-files call returns up to 100 files for a channel.
next#- Token from the
nextvalue of the previous response, which continues the list where that response ended.
Sample code
Returns
list_files() returns an Envelope whose result is a PNGetFilesResult and whose status is a PNStatus.
PNGetFilesResult
Each dict in data holds these keys:
| Key | Type | Description |
|---|---|---|
id | str | ID of the file, which PubNub assigned at upload. |
name | str | Name of the file, as PubNub stores it. |
size | int | Size of the file in bytes. |
created | str | Time at which PubNub stored the file, as an ISO 8601 string. |
Examples for List channel files
Syntax
1pubnub.list_files(
2 channel: str,
3 *,
4 limit: int = None,
5 next: str = None
6) -> ListFiles
Basic usage (Builder Pattern)
1file_list_response = pubnub.list_files().channel("ch1").sync()
2print(f"Found {len(file_list_response.result.data)} files:")
3
4for file_data in file_list_response.result.data:
5 print(f" {file_data['name']} with id: {file_data['id']}")
Basic usage (Named Arguments)
1page_1 = pubnub.list_files(channel="ch1", limit=1).sync()
2page_2 = pubnub.list_files(channel="ch1", limit=1, next=page_1.result.next).sync()
Get file URL
get_file_url() requests the download URL of a file on a channel from PubNub, using a PubNub client for Python.
The URL points to the file as PubNub stores it, so a file that the sender encrypted stays encrypted.
channelrequired#- ID of the channel that holds the file. A request without a channel fails validation with the message
Channel missing. file_namerequired#- Name of the file to build the URL for, as PubNub stores it. A request without a file name fails validation with the message
File name is missing.. file_idrequired#- ID of the file to build the URL for, which PubNub assigned at upload. A request without a file ID fails validation with the message
File id is missing..
Sample code
The sample reads id and name from file_data, an entry of the data list that list_files() returns.
Returns
get_file_url() returns an Envelope whose result is a PNGetFileDownloadURLResult and whose status is a PNStatus.
PNGetFileDownloadURLResult
file_url#- URL from which to download the requested file.
Examples for Get file URL
Syntax
1pubnub.get_file_url(
2 channel: str,
3 file_name: str,
4 file_id: str
5) -> GetFileDownloadUrl
Basic usage (Builder Pattern)
1download_url = pubnub.get_file_url() \
2 .channel("ch1") \
3 .file_id(file_data['id']) \
4 .file_name(file_data['name']) \
5 .sync()
6
7print(f' Download url: {download_url.result.file_url}')
Basic usage (Named Arguments)
1download_url = pubnub.get_file_url(channel="ch1",
2 file_id=file_data['id'],
3 file_name=file_data['name']) \
4 .sync()
5
6print(f' Download url: {download_url.result.file_url}')
Download file
download_file() downloads a file from a channel through a PubNub client for Python.
With cipher_key set on PNConfiguration, the SDK decrypts the file content with the configured crypto module, or with the legacy module if you set none.
channelrequired#- ID of the channel to download the file from. A request without a channel fails validation with the message
Channel missing. file_namerequired#- Name of the file to download, as PubNub stores it. A request without a file name fails validation with the message
File name is missing.. file_idrequired#- ID of the file to download, which PubNub assigned at upload. A request without a file ID fails validation with the message
File id is missing..
The deprecated cipher_key builder method is documented in Deprecated cipher_key parameter.
Sample code
Returns
download_file() returns an Envelope whose result is a PNDownloadFileResult and whose status is a PNStatus.
PNDownloadFileResult
data#- Content of the downloaded file.
Examples for Download file
Syntax
1pubnub.download_file() \
2 .channel(channel: str) \
3 .file_name(file_name: str) \
4 .file_id(file_id: str) \
5 .sync() -> Envelope
Basic usage
The sample reads id and name from file_data, an entry of the data list that list_files() returns, and writes the file to save_path.
1download_file = pubnub.download_file() \
2 .channel("ch1") \
3 .file_id(file_data['id']) \
4 .file_name(file_data['name']) \
5 .sync()
6
7save_path = file_data['name']
8with open(save_path, 'wb') as fw:
9 fw.write(download_file.result.data)
10
11print(f"File saved as {save_path}")
Delete file
delete_file() deletes a file from a channel through a PubNub client for Python.
channelrequired#- ID of the channel to delete the file from. A request without a channel fails validation with the message
Channel missing. file_namerequired#- Name of the file to delete, as PubNub stores it. A request without a file name fails validation with the message
File name is missing.. file_idrequired#- ID of the file to delete, which PubNub assigned at upload. A request without a file ID fails validation with the message
File id is missing..
Sample code
The sample reads id and name from file_data, an entry of the data list that list_files() returns.
Returns
delete_file() returns an Envelope whose result is a PNDeleteFileResult and whose status is a PNStatus.
PNDeleteFileResult
status#- Status that PubNub returns for the deletion. The value
200means success.
Examples for Delete file
Syntax
1pubnub.delete_file(
2 channel: str,
3 file_name: str,
4 file_id: str
5) -> DeleteFile
Basic usage (Builder Pattern)
1envelope = pubnub.delete_file() \
2 .channel("ch1") \
3 .file_id(file_data['id']) \
4 .file_name(file_data['name']) \
5 .sync()
6
7print("File deleted")
Basic usage (Named Arguments)
1envelope = pubnub.delete_file(channel="ch1",
2 file_id=file_data['id'],
3 file_name=file_data['name']) \
4 .sync()
5
6print("File deleted")
Publish file message
publish_file_message() publishes a file message for a file that PubNub already stores, using a PubNub client for Python.
publish_file_message() when the upload succeeded but the publish step of send_file() failed, to publish the file message without uploading the file again.channelrequired#- ID of the channel to publish the file message to. A request without a channel fails validation with the message
Channel missing. file_idrequired#- ID of the uploaded file, which PubNub assigned at upload. A request without a file ID fails validation with the message
File id is missing.. file_namerequired#- Name of the uploaded file, as PubNub stores it. A request without a file name fails validation with the message
File name is missing.. message#- Message to publish with the file. Subscribers receive it in the file event.
should_store#- Whether PubNub stores the file message in Message Persistence.
truestores it andfalseskips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sendsstore=0, so PubNub does not store the file message. ttl#- The number of hours that Message Persistence keeps the file message. When omitted, the SDK sends
0, and the retention of the keyset applies. PubNub ignores this value when it does not store the message. meta#- Metadata that PubNub attaches to the file message. Subscribers can use it in message filters.
custom_message_type#- A business-specific label for the file message, for example
text,action, orpoll.
The deprecated cipher_key builder method is documented in Deprecated cipher_key parameter.
Sample code
Returns
publish_file_message() returns an Envelope whose result is a PNPublishFileMessageResult and whose status is a PNStatus.
PNPublishFileMessageResult
timestamp#- Timetoken at which PubNub published the file message.
Other examples
Examples for Publish file message
Syntax
1pubnub.publish_file_message() \
2 .channel(channel: str) \
3 .file_id(file_id: str) \
4 .file_name(file_name: str) \
5 .message(message: Any) \
6 .should_store(should_store: bool) \
7 .ttl(ttl: int) \
8 .meta(meta: Any) \
9 .custom_message_type(custom_message_type: str) \
10 .sync() -> Envelope
Basic usage
The sample reads file_id and file_name from the result of an earlier send_file() call.
1envelope = pubnub.publish_file_message() \
2 .channel("ch1") \
3 .meta({"test": "test"}) \
4 .message({"test_message": "test"}) \
5 .custom_message_type("file-message") \
6 .file_id(file_id) \
7 .file_name(file_name) \
8 .should_store(True) \
9 .ttl(22) \
10 .sync()
Publish a file message with a callback
Publish a file message with a callback
1def callback(response, status):
2 results.append((response, status))
3
4pubnub.publish_file_message() \
5 .channel("ch1") \
6 .message("Bring me a shrubbery") \
7 .file_id(file_id) \
8 .file_name(file_name) \
9 .should_store(True) \
10 .pn_async(callback)
Deprecated cipher_key parameter
The cipher_key builder method of send_file(), publish_file_message(), and download_file() is deprecated in the PubNub Python SDK and issues a warning. The cipher key in the client configuration replaces it.
The reference for apps that still call cipher_key, with the replacement, is File Sharing API: deprecated cipher_key parameter for Python SDK. New apps set cipher_key on PNConfiguration and, to use 256-bit AES-CBC, a crypto_module.