Python – Write to Pub/Sub from Cloud Functions

Write to Pub/Sub from Cloud Functions… here is a solution to the problem.

Write to Pub/Sub from Cloud Functions

What I want is to write the CF result to the Pub/Sub theme. I know I can use the API through the service account, but my problem is:

Is there a way to write pub/sub directly from CF without using a custom service account?

Google Cloud docs Says you can use the App Engine default service account for this, but I don’t know how to put them together and use it.

Solution

Okay, it’s simple: you just use the pub/sub library and the system will automatically load the service account. Something like this:

from google.cloud import pubsub_v1

publisher = pubsub_v1. PublisherClient()
topic_name = 'topic/name'

def trigger(request):
    publisher.publish(topic_name, b'My first message!', spam='eggs')

You don’t need to add SA to work.

Related Problems and Solutions