menu
arrow_back

Google Cloud Pub/Sub: Qwik Start - Python

search favorite_border
Add to favorites
—/100

Checkpoints

arrow_forward

Create a topic

Create a subscription

Google Cloud Pub/Sub: Qwik Start - Python

30 minutes Free

GSP094

Google Cloud Self-Paced Labs

Overview

The Google Cloud Pub/Sub service allows applications to exchange messages reliably, quickly, and asynchronously. To accomplish this, a data producer publishes messages to a Cloud Pub/Sub topic. A subscriber client then creates a subscription to that topic and consumes messages from the subscription. Cloud Pub/Sub persists messages that could not be delivered reliably for up to seven days.

In this lab you will learn how to get started publishing messages with Cloud Pub/Sub using the Python client library.

What you'll do

In this lab, you'll do the following:

  • Learn the basics of Pub/Sub.
  • Create and list a Pub/Sub topic.
  • Create and list a Pub/Sub subscription.
  • Publish messages to a topic.
  • Use a pull subscriber to output individual topic messages.

Setup and Requirements

Setup

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This Qwiklabs hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

What you need

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
  • Time to complete the lab.

Note: If you already have your own personal Google Cloud account or project, do not use it for this lab.

Note: If you are using a Pixelbook, open an Incognito window to run this lab.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is a panel populated with the temporary credentials that you must use for this lab.

    Open Google Console

  2. Copy the username, and then click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Sign in

    Tip: Open the tabs in separate windows, side-by-side.

  3. In the Sign in page, paste the username that you copied from the Connection Details panel. Then copy and paste the password.

    Important: You must use the credentials from the Connection Details panel. Do not use your Qwiklabs credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges).

  4. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

In the Cloud Console, in the top right toolbar, click the Activate Cloud Shell button.

Cloud Shell icon

Click Continue.

cloudshell_continue.png

It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:

Cloud Shell Terminal

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

You can list the active account name with this command:

gcloud auth list

(Output)

Credentialed accounts:
 - <myaccount>@<mydomain>.com (active)

(Example output)

Credentialed accounts:
 - google1623327_student@qwiklabs.net

You can list the project ID with this command:

gcloud config list project

(Output)

[core]
project = <project_ID>

(Example output)

[core]
project = qwiklabs-gcp-44776a13dea667a6

Create a virtual environment

Execute the following command to download and update the packages list.

sudo apt-get update

Python virtual environments are used to isolate package installation from the system.

sudo apt-get install virtualenv
If prompted [Y/n], press Y and then Enter.
virtualenv -p python3 venv

Activate the virtual environment.

source venv/bin/activate

Install the client library

Run the following to install the client library:

pip install --upgrade google-cloud-pubsub

Get the sample code by cloning a GitHub repository:

git clone https://github.com/googleapis/python-pubsub.git

Navigate to the directory:

cd python-pubsub/samples/snippets

Pub/Sub - the Basics

Google Cloud Pub/Sub is an asynchronous global messaging service. There are three terms in Pub/Sub that appear often: topics, publishing, and subscribing.

A topic is a shared string that allows applications to connect with one another through a common thread.

Publishers push (or publish) a message to a Cloud Pub/Sub topic. Subscribers will then make a subscription to that thread, where they will either pull messages from the topic or configure webhooks for push subscriptions. Every subscriber must acknowledge each message within a configurable window of time.

In sum, a publisher creates and sends messages to a topic and a subscriber creates a subscription to a topic to receive messages from it.

Pub/Sub in Google CLoud

Pub/Sub comes preinstalled in the Cloud Shell, so there are no installations or configurations required to get started with this service. In this lab you use Python to create the topic, subscriber, and then view the message. You use a gcloud command to publish the message to the topic.

Create a topic

To publish data to Cloud Pub/Sub you create a topic and then configure a publisher to the topic.

Set the environment variable GOOGLE_CLOUD_PROJECT. You can find your Project ID in the CONNECTION DETAILS:

export GLOBAL_CLOUD_PROJECT=GCP Project ID

publisher.py is a script that demonstrates how to perform basic operations on topics with the Cloud Pub/Sub API. View the content of publisher script:

cat publisher.py
Note: Alternatively, you can use the shell editors that are installed on Cloud Shell, such as nano or vim or use the Cloud Shell code editor to view python-docs-samples/pubsub/cloud-client/publisher.py

For information about the publisher script:

python publisher.py -h

Example Output, do not copy

usage: publisher.py [-h]
                    project
                    {list,create,delete,publish,publish-with-custom-attributes,publish-with-futures,publish-with-error-handler,publish-with-batch-settings}
                    ...

This application demonstrates how to perform basic operations on topics
with the Cloud Pub/Sub API.

For more information, see the README.md under /pubsub and the documentation
at https://cloud.google.com/pubsub/docs.

positional arguments:
  project               Your Google Cloud project ID
  {list,create,delete,publish,publish-with-custom-attributes,publish-with-futures,publish-with-error-handler,publish-with-batch-settings}
    list                Lists all Pub/Sub topics in the given project.
    create              Create a new Pub/Sub topic.
    delete              Deletes an existing Pub/Sub topic.
    publish             Publishes multiple messages to a Pub/Sub topic.
    publish-with-custom-attributes
                        Publishes multiple messages with custom attributes to
                        a Pub/Sub topic.
    publish-with-futures
                        Publishes multiple messages to a Pub/Sub topic and
                        prints their message IDs.
    publish-with-error-handler
                        Publishes multiple messages to a Pub/Sub topic with an
                        error handler.
    publish-with-batch-settings
                        Publishes multiple messages to a Pub/Sub topic with
                        batch settings.

optional arguments:
  -h, --help            show this help message and exit

Run the publisher script to create Pub/Sub Topic:

python publisher.py $GLOBAL_CLOUD_PROJECT create MyTopic

Example Output, do not copy

Topic created: name: "projects/qwiklabs-gcp-fe27729bc161fb22/topics/MyTopic"

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully created a Cloud Pub/Sub topic, you will see an assessment score.

Create a topic.

This command returns a list of all Pub/Sub topics in a given project:

python publisher.py $GLOBAL_CLOUD_PROJECT list

Example Output, do not copy

name: "projects/qwiklabs-gcp-fe27729bc161fb22/topics/MyTopic"

You can also view the topic you just made in the Cloud Console.

Navigate to Navigation menu > Pub/Sub > Topics.

29f5381c6ffbb8ca.png

You should see MyTopic.

badf10f6700c3fc8.png

Create a subscription

Create a Pub/Sub subscription for topic with subscriber.py script:

python subscriber.py $GLOBAL_CLOUD_PROJECT create MyTopic MySub

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully created a Cloud Pub/Sub subscription, you will see an assessment score.

Create a subscription.

This command returns a list of subscribers in given project:

python subscriber.py $GLOBAL_CLOUD_PROJECT list-in-project

You'll see only one subscription because you've made only one subscription.

Example output (do not copy)

projects/qwiklabs-gcp-7877af129f04d8b3/subscriptions/MySub

Check out the subscription you just made in the console. In the left pane, click Subscriptions. You should see the subscription name and other details.

2866f66f3030244d.png

For information about the subscriber script:

python subscriber.py -h

Output, do not copy

usage: subscriber.py [-h]
                     project
                     {list_in_topic,list_in_project,create,create-push,delete,update,receive,receive-custom-attributes,receive-flow-control,receive-synchronously,listen_for_errors}
                     ...

This application demonstrates how to perform basic operations on
subscriptions with the Cloud Pub/Sub API.

For more information, see the README.md under /pubsub and the documentation
at https://cloud.google.com/pubsub/docs.

positional arguments:
  project               Your Google Cloud project ID
  {list_in_topic,list_in_project,create,create-push,delete,update,receive,receive-custom-attributes,receive-flow-control,receive-synchronously,listen_for_errors}
    list_in_topic       Lists all subscriptions for a given topic.
    list_in_project     Lists all subscriptions in the current project.
    create              Create a new pull subscription on the given topic.
    create-push         Create a new push subscription on the given topic.
    delete              Deletes an existing Pub/Sub topic.
    update              Updates an existing Pub/Sub subscription's push
                        endpoint URL. Note that certain properties of a
                        subscription, such as its topic, are not modifiable.
    receive             Receives messages from a pull subscription.
    receive-custom-attributes
                        Receives messages from a pull subscription.
    receive-flow-control
                        Receives messages from a pull subscription with flow
                        control.
    receive-synchronously
                        Pulling messages synchronously.
    listen_for_errors   Receives messages and catches errors from a pull
                        subscription.

optional arguments:
  -h, --help            show this help message and exit

Publish messages

Now that you've set up MyTopic (the topic), a subscription to MyTopic (MySub), see if you can use gcloud commands to publish a message to MyTopic.

Publish the message "Hello" to MyTopic:

gcloud pubsub topics publish MyTopic --message "Hello"

Publish a few more messages to MyTopic—run the following commands (replacing <YOUR NAME> with your name and <FOOD> with a food you like to eat):

gcloud pubsub topics publish MyTopic --message "Publisher's name is <YOUR NAME>"
gcloud pubsub topics publish MyTopic --message "Publisher likes to eat <FOOD>"
gcloud pubsub topics publish MyTopic --message "Publisher thinks Pub/Sub is awesome"

View messages

Now that you've published messages to MyTopic, pull and view the messages using MySub.

Use MySub to pull the message from MyTopic:

python subscriber.py $GLOBAL_CLOUD_PROJECT receive MySub

Example output (do not copy)

Listening for messages on projects/qwiklabs-gcp-7877af129f04d8b3/subscriptions/MySub
Received message: Message {
  data: 'Publisher thinks Pub/Sub is awesome'
  attributes: {}
}
Received message: Message {
  data: 'Hello'
  attributes: {}
}
Received message: Message {
  data: "Publisher's name is Harry"
  attributes: {}
}
Received message: Message {
  data: 'Publisher likes to eat cheese'
  attributes: {}
}

Click Ctrl+c to stop listening.

Test your Understanding

Below are multiple-choice questions to reinforce your understanding of this lab's concepts. Answer them to the best of your abilities.

Congratulations!

You used the Python created a Pub/Sub topic, published to the topic, created a subscription, then used the subscription to pull data from the topic.

Take your next lab

The Qwik Start labs are a fun way to start your journey. Try other Qwik Start labs like Container Registry Qwik Start or Cloud Pub/Sub Qwik Start.

Next Steps /Learn More

Google Cloud Training & Certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated July 10, 2020
Lab Last Tested July 10, 2020

Copyright 2020 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.