File Sharing API for PubNub Python SDK
Allows users to upload and share files. You can upload any file of up to 5 MB in size. This feature is commonly used in social apps to share images, or in medical apps to share medical records for patients.
When a file is uploaded on a channel
, it's stored and managed using a storage service, and associated with your key. Subscribers to that channel
receive a file event which contains a file ID
, filename
, and optional description
.
Request execution and return values
You can decide whether to perform the Python SDK operations synchronously or asynchronously.
-
.sync()
returns anEnvelope
object, which has two fields:Envelope.result
, whose type differs for each API, andEnvelope.status
of typePnStatus
.pubnub.publish() \
.channel("myChannel") \
.message("Hello from PubNub Python SDK") \
.sync() -
.pn_async(callback)
returnsNone
and passes the values ofEnvelope.result
andEnvelope.status
to a callback you must define beforehand.def my_callback_function(result, status):
print(f'TT: {result.timetoken}, status: {status.category.name}')
pubnub.publish() \
.channel("myChannel") \
.message("Hello from PubNub Python SDK") \
.pn_async(my_callback_function)
Send file
Upload the file to a specified channel.
This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.
For the last messaging step, send_file
internally calls the publish_file_message
method to publish a message on the channel.
The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.
Method(s)
pubnub.send_file() \
.channel(String) \
.file_name(String) \
.message(Dictionary) \
.should_store(Boolean) \
.ttl(Integer) \
.file_object(Python Object File or bytes) \
.meta(Dictionary) \
.custom_message_type(String)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | String | Yes | Channel for the file. | |
file_name | String | Yes | Name of the file to send. | |
message | Dictionary | Optional | Message which should be sent along with file to specified channel . | |
should_store | Boolean | Optional | True | Whether PubNub published file message should be stored in channel history. |
ttl | Integer | Optional | How long message should be stored in channel's storage. | |
file_object | bytes or Python file object | Yes | Input stream with file content. | |
meta | Dictionary | Optional | Meta data object which can be used with the filtering ability. | |
custom_message_type | String | Optional | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn- . Examples: text , action , poll . |
Deprecated parameter
The cipher_key
parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.
If you pass cipher_key
as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
Basic Usage
- Builder Pattern
- Named Arguments
with open(sample_path, 'rb') as sample_file:
response = pubnub.send_file(channel="ch1",
file_name="sample.gif",
file_object=sample_file,
message="Hey, it's gif not jif",
custom_message_type="file-message") \
.sync()
Returns
The send_file()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNSendFileResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNSendFileResult
Property Name | Type | Description |
---|---|---|
name | String | Name of the uploaded file. |
file_id | String | ID of the uploaded file. |
timestamp | String | The timetoken at which the message was published. |
List channel files
Retrieve list of files uploaded to Channel
.
Method(s)
pubnub.list_files() \
.channel(String)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | String | Yes | Channel to get the list of files. |
Basic Usage
- Builder Pattern
- Named Arguments
file_list_response = pubnub.list_files(channel="ch1").sync()
print(f"Found {len(file_list_response.result.data)} files:")
for file_data in file_list_response.result.data:
print(f" {file_data['name']} with id: {file_data['id']}")
Returns
The list_files()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNGetFilesResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNGetFilesResult
Property Name | Type | Description |
---|---|---|
next | String | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |
prev | String | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. |
count | Int | Number of files returned. |
data | List | List of channel files. |
data
contains the following properties:
Property Name | Type | Description |
---|---|---|
id | Long | Id of the uploaded file. |
name | String | Name of the upload file. |
size | String | Size of the uploaded file. |
created | String | Time of creation. |
Get File Url
Generate URL which can be used to download file from target Channel
.
Method(s)
pubnub.get_file_url() \
.channel(String) \
.file_id(String) \
.file_name(String)
Parameter | Type | Required | Description |
---|---|---|---|
channel | String | Yes | Name of channel to which the file has been uploaded. |
file_name | String | Yes | Name under which the uploaded file is stored. |
file_id | String | Yes | Unique identifier for the file, assigned during upload. |
Basic Usage
- Builder Pattern
- Named Arguments
download_url = pubnub.get_file_url(channel="ch1",
file_id=file_data['id'],
file_data['name']) \
.sync()
print(f' Download url: {download_url.result.file_url}')
Returns
The get_file_url()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNGetFileDownloadURLResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNGetFileDownloadURLResult
Property Name | Type | Description |
---|---|---|
file_url | String | URL to be used to download the requested file. |
Download file
Download file from specified Channel
.
Method(s)
pubnub.download_file() \
.channel(String) \
.file_id(String) \
.file_name(String)
Parameter | Type | Required | Description |
---|---|---|---|
channel | String | Yes | Name of channel to which the file has been uploaded. |
file_name | String | Yes | Name under which the uploaded file is stored. |
file_id | String | Yes | Unique identifier for the file, assigned during upload. |
Deprecated parameter
The cipher_key
parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.
If you pass cipher_key
as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
Basic Usage
- Builder Pattern
- Named Arguments
download_url = pubnub.download_file(channel="ch1",
file_id=file_data['id'],
file_data['name']) \
.sync()
fw = open(f"{os.getcwd()}/{file_data['name']}", 'wb')
fw.write(download_file.result.data)
print(f"File saved as {os.getcwd()}/{file_data['name']}")
Returns
The download_file()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNDownloadFileResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNDownloadFileResult
Property Name | Type | Description |
---|---|---|
data | bytes | Python bytes object. |
Delete file
Delete file from specified Channel
.
Method(s)
pubnub.delete_file() \
.channel(String) \
.file_id(String) \
.file_name(String)
Parameter | Type | Required | Description |
---|---|---|---|
channel | String | Yes | The channel from which to delete the file. |
file_id | String | Yes | Unique identifier of the file to be deleted. |
file_name | String | Yes | Name of the file to be deleted. |
Basic Usage
- Builder Pattern
- Named Arguments
pubnub.delete_file(channel="ch1",
file_id=file_data['id'],
file_data['name']) \
.sync()
print(f"File deleted")
Returns
The download_file()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNDeleteFileResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNDeleteFileResult
Property Name | Type | Description |
---|---|---|
status | Int | Returns a status code. |
Publish file message
Publish the uploaded file message to a specified channel.
This method is called internally by send_file
as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.
This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.
You can call this method when send_file
fails and returns the status.operation === PNPublishFileMessageOperation
error.
In that case, you can use the data from the status
object to try again and use publish_file_message
to manually resend a file message to a channel without repeating the upload step.
Method(s)
pubnub.publish_file_message() \
.channel(String) \
.meta(Dictionary) \
.message(Dictionary) \
.file_id(String) \
.custom_message_type(String) \
.file_name(String) \
.should_store(Boolean) \
.ttl(Integer)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | String | Yes | Name of channel to publish file message. | |
meta | Dictionary | Optional | Meta data object which can be used with the filtering ability. | |
message | Dictionary | Optional | The payload. | |
file_id | String | Yes | Unique identifier of the file. | |
custom_message_type | String | Optional | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn- . Examples: text , action , poll . | |
file_name | String | Yes | Name of the file. | |
should_store | Boolean | Optional | True | Set to False to not store this message in history. By default, messages are stored according to the retention policy you set on your key. |
ttl | Int | Optional | 0 | How long the message should be stored in the channel's history. If not specified, defaults to the key set's retention value. |
Basic Usage
- Builder Pattern
- Named Arguments
# synchronous:
envelope = pubnub.publish_file_message() \
.channel("test_channel") \
.meta({"test": "test"}) \
.message({"test_message": "test"}) \
.custom_message_type("file-message") \
.file_id("fileID") \
.file_name("knights_of_ni.jpg") \
.ttl(22) \
.sync()
# multithreaded asynchronous:
def callback(response, status):
pass
show all 24 linesenvelope = pubnub.publish_file_message(channel="test_channel",
message="Bring me a shrubbery",
file_id="fileID",
file_name="knights_of_ni.jpg",
custom_message_type="file-message",
meta={"nice": True, "expensive": False},
ttl=22) \
.sync()
Returns
The publish_file_message()
operation returns an Envelope
which contains the following fields:
Field | Type | Description |
---|---|---|
result | PNPublishFileMessageResult | A detailed object containing the result of the operation. |
status | PNStatus | A status object with additional information. |
PNPublishFileMessageResult
The publish_file_message()
operation returns a PNPublishFileMessageResult
which contains the following property:
Property Name | Type | Description |
---|---|---|
timestamp | String | The timetoken at which the message was published. |