Collect JSON content in the HTTP request and push it to Cloud Pub/Sub on a specific topic.
Environment variable TOPIC_NAME must be passed and set in the Cloud Function configuration.
| import os | |
| import json | |
| from flask import abort | |
| from google.cloud import pubsub_v1, error_reporting | |
| client = error_reporting.Client(project=os.getenv('GCP_PROJECT')) | |
| publisher = pubsub_v1.PublisherClient() | |
| topic_path = publisher.topic_path(os.getenv('GCP_PROJECT'), os.getenv('TOPIC_NAME')) | |
| def http2pubsub(request): | |
| try: | |
| data = json.dumps(request.get_json()).encode("utf-8") | |
| publisher.publish(topic_path, data) | |
| return f"OK" | |
| except RuntimeError: | |
| client.report_exception() | |
| return abort(500) |
| google-cloud-pubsub | |
| google-cloud-error-reporting | |
| Flask |