pythongoogle-cloud-pubsub

How to publish messages to GCP pub/sub topic with attributes as variables in python


In this python sample code, I want to make "origin" and "username" as variables.

The C++ code has an example but for python there is no specific example

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)

for n in range(1, 10):
    data_str = f"Message number {n}"
    # Data must be a bytestring
    data = data_str.encode("utf-8")
    # Add two attributes, origin and username, to the message
    future = publisher.publish(
        topic_path, data, origin="python-sample", username="gcp"
    )
    print(future.result())

print(f"Published messages with custom attributes to {topic_path}.")

Solution

  • See the API documentation publish

    Try:

    attrs = {
        "origin":"foo",
        "username":"bar",
    }
    future = publisher.publish(
        topic=topic_path,
        data=data,
        **attrs,
    )
    print(future.result())