Skip to content

Instantly share code, notes, and snippets.

@miticojo
Last active May 23, 2020 18:59
Show Gist options
  • Save miticojo/e74a798bf109e5ad8fbf4cfdcbaaa99f to your computer and use it in GitHub Desktop.
Save miticojo/e74a798bf109e5ad8fbf4cfdcbaaa99f to your computer and use it in GitHub Desktop.
Google Cloud Function push to Pub/Sub with Stackdriver Error Reporting integration

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment