Skip to content

Instantly share code, notes, and snippets.

@visaolive
Created June 8, 2020 00:24
Show Gist options
  • Save visaolive/056cbf29211497037831a3475e61a68f to your computer and use it in GitHub Desktop.
Save visaolive/056cbf29211497037831a3475e61a68f to your computer and use it in GitHub Desktop.
GCPCFOrderPubSub.py
import os
import json
from google.cloud import pubsub_v1
def publish_message(request):
#get JSON from HTTP POST
request_json = request.get_json()
#print request_json
print("publish_message: {}".format(request_json))
g_project_id = os.environ["gcp_project"]
g_topic_id = os.environ["pubsub_topic"]
batch_settings = pubsub_v1.types.BatchSettings(
max_messages=10, # default 100
max_bytes=1024, # default 1 MB
max_latency=1, # default 10 ms
)
try:
# create instance of publisher
publisher = pubsub_v1.PublisherClient(batch_settings)
# define pub/sub project & topic
topic_name = 'projects/{project_id}/topics/{topic}'.format(
project_id=g_project_id,
topic=g_topic_id,
)
# publish message to google pub/sub
# interate through potentially multiple records and send one message per record
for items in request_json["records"]:
msg = json.dumps(items).encode("utf-8")
print("Message: {}".format(msg))
#published = publisher.publish(topic_name, b'', message=msg)
published = publisher.publish(topic_name, msg)
return 'Message Published'
except Exception as error:
print('Publish Message Error: ' + repr(error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment