Skip to content

Commit 8f49b4e

Browse files
author
Ace Nassri
authored
GCF: Add Pub/Sub publisher sample (#3312)
1 parent 35ded53 commit 8f49b4e

File tree

3 files changed

+119
-0
lines changed

3 files changed

+119
-0
lines changed

functions/pubsub/main.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the 'License');
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an 'AS IS' BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START functions_pubsub_setup]
16+
import base64
17+
from google.cloud import pubsub_v1
18+
import json
19+
import os
20+
21+
22+
# Instantiates a Pub/Sub client
23+
publisher = pubsub_v1.PublisherClient()
24+
PROJECT_ID = os.getenv('GCP_PROJECT')
25+
# [END functions_pubsub_setup]
26+
27+
28+
# [START functions_pubsub_publish]
29+
# Publishes a message to a Cloud Pub/Sub topic.
30+
def publish(request):
31+
request_json = request.get_json(silent=True)
32+
33+
topic_name = request_json.get("topic")
34+
message = request_json.get("message")
35+
36+
if not topic_name or not message:
37+
return ('Missing "topic" and/or "subscription" parameter.', 500)
38+
39+
print(f'Publishing message to topic {topic_name}')
40+
41+
# References an existing topic
42+
topic_path = publisher.topic_path(PROJECT_ID, topic_name)
43+
44+
message_json = json.dumps({
45+
'data': {'message': message},
46+
})
47+
message_bytes = message_json.encode('utf-8')
48+
print(message_bytes)
49+
50+
# Publishes a message
51+
try:
52+
publish_future = publisher.publish(topic_path, data=message_bytes)
53+
publish_future.result() # Verify the publish succeeded
54+
return 'Message published.'
55+
except Exception as e:
56+
print(e)
57+
return (e, 500)
58+
59+
# [END functions_pubsub_publish]
60+
61+
62+
# [START functions_pubsub_subscribe]
63+
# Triggered from a message on a Cloud Pub/Sub topic.
64+
def subscribe(event, context):
65+
# Print out the data from Pub/Sub, to prove that it worked
66+
print(base64.b64decode(event['data']))
67+
# [END functions_pubsub_subscribe]

functions/pubsub/main_test.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Copyright 2019 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the 'License');
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an 'AS IS' BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import base64
16+
import flask
17+
from mock import MagicMock
18+
import os
19+
20+
import main
21+
22+
23+
FUNCTIONS_TOPIC = os.getenv("FUNCTIONS_TOPIC")
24+
25+
26+
def test_functions_pubsub_publish_should_fail_without_params():
27+
request = MagicMock()
28+
request.body.topic = None
29+
response = main.publish(request)
30+
31+
assert 'Missing "topic" and/or "subscription" parameter.' in response
32+
33+
34+
def test_functions_pubsub_publish_should_publish_message():
35+
request = MagicMock()
36+
request.body.topic = FUNCTIONS_TOPIC
37+
request.body.message = "my_message"
38+
39+
response = main.publish(request)
40+
41+
assert response == "Message published."
42+
43+
44+
def test_functions_pubsub_subscribe_should_print_message(capsys):
45+
pubsub_message = MagicMock()
46+
pubsub_message.data = base64.b64encode(b"Hello, world!")
47+
48+
main.subscribe(pubsub_message)
49+
50+
out, _ = capsys.readouterr()
51+
assert "Hello, world!" in out

functions/pubsub/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
google-cloud-pubsub==1.3.0

0 commit comments

Comments
 (0)