Skip to content

Commit c8bf260

Browse files
author
Sebastian Molenda
authored
Docs/examples (#192)
* Example for fetching messages * sync examples
1 parent fd04298 commit c8bf260

File tree

7 files changed

+211
-0
lines changed

7 files changed

+211
-0
lines changed

.github/workflows/run-tests.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ jobs:
2323
runs-on:
2424
group: Default
2525
strategy:
26+
max-parallel: 1
2627
fail-fast: true
2728
matrix:
2829
python: [3.8.18, 3.9.18, 3.10.13, 3.11.6]

examples/DEVELOPER.md

Whitespace-only changes.

examples/fetch_history.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from pubnub.pnconfiguration import PNConfiguration
2+
from pubnub.pubnub import PubNub
3+
4+
5+
# Fetch historical messages
6+
def fetch_history(pubnub: PubNub, channel_name: str, fetch_count: int):
7+
envelope = pubnub.history() \
8+
.channel(channel_name) \
9+
.include_meta(True) \
10+
.reverse(False) \
11+
.include_timetoken(True) \
12+
.count(fetch_count) \
13+
.sync()
14+
15+
# Process and print messages
16+
if envelope.status.is_error():
17+
print("Error fetching history:", envelope.status.error_data.information)
18+
else:
19+
for message in envelope.result.messages:
20+
print(f"Message: {message.entry}, Timetoken: {message.timetoken}")
21+
22+
23+
def populate_messages(pubnub: PubNub, channel_name: str, message_count: int):
24+
for i in range(message_count):
25+
pubnub.publish().channel(channel_name).message(f'demo message #{i + 1}').sync()
26+
27+
28+
def get_input_number(message: str, range_min: int, range_max: int):
29+
while True:
30+
try:
31+
num = int(input(f"{message} [{range_min}-{range_max}]: "))
32+
if range_min <= range_max <= 150:
33+
return num
34+
else:
35+
print(f"Invalid input. Please enter a number between {range_min} and {range_max}.")
36+
except ValueError:
37+
print("Invalid input. Please enter a valid integer.")
38+
39+
40+
if __name__ == "__main__":
41+
message_count = 0
42+
channel_name = 'example_fetch_history'
43+
44+
# Initialize PubNub configuration
45+
pnconfig = PNConfiguration()
46+
pnconfig.subscribe_key = "demo"
47+
pnconfig.publish_key = "demo"
48+
pnconfig.user_id = "demo"
49+
50+
# Initialize PubNub
51+
pubnub = PubNub(pnconfig)
52+
53+
# Get validated int input between 0 and 150
54+
message_count = get_input_number("How many messages to populate?", 0, 150)
55+
56+
populate_messages(pubnub, channel_name, message_count)
57+
58+
fetch_count = get_input_number("How many messages to fetch?", 0, 100)
59+
60+
# Call the function to fetch and print history
61+
fetch_history(pubnub, channel_name, fetch_count)

examples/metadata.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import os
2+
3+
from pubnub.models.consumer.entities.user import User
4+
from pubnub.pnconfiguration import PNConfiguration
5+
from pubnub.pubnub import PubNub
6+
7+
config = PNConfiguration()
8+
config.subscribe_key = os.getenv('PN_KEY_SUBSCRIBE')
9+
config.publish_key = os.getenv('PN_KEY_PUBLISH')
10+
config.user_id = 'example'
11+
12+
pubnub = PubNub(config)
13+
14+
pubnub.set_uuid_metadata().uuid('john').set_name('John Lorem').sync()
15+
pubnub.set_uuid_metadata().uuid('jim').set_name('Jim Ipsum').sync()
16+
17+
john_metadata = pubnub.get_all_uuid_metadata().filter("name LIKE 'John*'").sync()
18+
19+
if john_metadata.status.is_error():
20+
print(f"Error fetching UUID metadata: {john_metadata.status.error_message}")
21+
else:
22+
for uuid_data in john_metadata.result.data:
23+
print(f"UUID: {uuid_data['id']}, Name: {uuid_data['name']}")
24+
25+
pubnub.set_channel_metadata().channel('generalfailure').set_name('General Failure').sync()
26+
pubnub.set_channel_metadata().channel('majormistake').set_name('Major Mistake').sync()
27+
28+
general_metadata = pubnub.get_all_channel_metadata() \
29+
.filter("name LIKE '*general*' && updated >= '2023-01-01T00:00:00Z'") \
30+
.sync()
31+
32+
if general_metadata.status.is_error():
33+
print(f"Error fetching channel metadata: {general_metadata.status.__dict__}")
34+
else:
35+
for channel in general_metadata.result.data:
36+
print(f"Channel ID: {channel['id']}, Name: {channel['name']}, Updated: {channel['updated']}")
37+
38+
pubnub.set_channel_members().channel('example').uuids([User('user123'), User('user124')]).sync()
39+
40+
memberships = pubnub.get_memberships() \
41+
.uuid("user123") \
42+
.filter("!(channel.id == 'Channel-001')") \
43+
.sync()
44+
45+
if memberships.status.is_error():
46+
print(f"Error fetching memberships: {memberships.status}")
47+
else:
48+
print(memberships.__dict__)
49+
for membership in memberships.result.data:
50+
print(f"Channel ID: {membership['channel']['id']}")
51+
52+
53+
members = pubnub.get_channel_members() \
54+
.channel("specialEvents") \
55+
.filter("uuid.updated < '2023-01-01T00:00:00Z'") \
56+
.sync()
57+
58+
print(members.result)
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import os
2+
3+
4+
from pubnub.pubnub import PubNub
5+
from pubnub.pnconfiguration import PNConfiguration
6+
7+
8+
config = PNConfiguration()
9+
config.publish_key = os.environ.get('PUBLISH_KEY', 'demo')
10+
config.subscribe_request_timeout = 10
11+
config.subscribe_key = os.environ.get('PUBLISH_KEY', 'demo')
12+
config.enable_subscribe = False
13+
config.user_id = 'example'
14+
15+
channel = 'file-channel'
16+
pubnub = PubNub(config)
17+
sample_path = f"{os.getcwd()}/examples/native_sync/sample.gif"
18+
19+
with open(sample_path, 'rb') as sample_file:
20+
response = pubnub.send_file() \
21+
.channel(channel) \
22+
.file_name("sample.gif") \
23+
.message({"test_message": "test"}) \
24+
.file_object(sample_file) \
25+
.sync()
26+
27+
print(f"Sent file: {response.result.name} with id: {response.result.file_id},"
28+
f" at timestamp: {response.result.timestamp}")
29+
30+
file_list_response = pubnub.list_files().channel(channel).sync()
31+
print(f"Found {len(file_list_response.result.data)} files:")
32+
33+
for file_data in file_list_response.result.data:
34+
print(f" {file_data['name']} with id: {file_data['id']}")
35+
ext = file_data['name'].replace('sample', '')
36+
37+
download_url = pubnub.get_file_url() \
38+
.channel(channel) \
39+
.file_id(file_data['id']) \
40+
.file_name(file_data['name']) \
41+
.sync()
42+
print(f' Download url: {download_url.result.file_url}')
43+
44+
download_file = pubnub.download_file() \
45+
.channel(channel) \
46+
.file_id(file_data['id']) \
47+
.file_name(file_data['name']) \
48+
.sync()
49+
50+
fw = open(f"{os.getcwd()}/examples/native_sync/out-{file_data['id']}{ext}", 'wb')
51+
fw.write(download_file.result.data)
52+
print(f" file saved as {os.getcwd()}/examples/native_sync/out-{file_data['id']}{ext}\n")
53+
54+
pubnub.delete_file() \
55+
.channel(channel) \
56+
.file_id(file_data['id']) \
57+
.file_name(file_data['name']) \
58+
.sync()
59+
print(' File deleted from storage')
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from os import getenv
2+
from pprint import pprint
3+
from time import sleep
4+
5+
from pubnub.pnconfiguration import PNConfiguration
6+
from pubnub.pubnub import PubNub
7+
8+
9+
channel = 'example'
10+
11+
config = config = PNConfiguration()
12+
config.publish_key = getenv('PUBLISH_KEY')
13+
config.subscribe_key = getenv('SUBSCRIBE_KEY')
14+
config.secret_key = getenv('SECRET_KEY')
15+
config.cipher_key = getenv('CIPHER_KEY')
16+
config.user_id = 'example'
17+
18+
pn = PubNub(config)
19+
20+
# let's build some message history
21+
22+
pn.publish().channel(channel).message('message zero zero').sync()
23+
pn.publish().channel(channel).message('message zero one').sync()
24+
pn.publish().channel(channel).message('message one zero').sync()
25+
pn.publish().channel(channel).message('message one one').sync()
26+
27+
# give some time to store messages
28+
sleep(3)
29+
30+
# fetching messages
31+
messages = pn.fetch_messages().channels(channel).sync()
32+
pprint([message.__dict__ for message in messages.result.channels[channel]])

examples/native_sync/sample.gif

1.23 KB
Loading

0 commit comments

Comments
 (0)