|
| 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] |
0 commit comments