Getting started with App Engine (Python 3)

Google App Engine applications are easy to create, easy to maintain, and easy to scale as your traffic and data storage needs change. With App Engine, there are no servers to maintain. You simply upload your application and it's ready to go.

In this codelab, you will learn how to deploy a simple Python web app written with the Flask web framework. Although this sample uses Flask, you can use other web frameworks, including Django, Pyramid, Bottle, and web.py.

This tutorial is adapted from https://cloud.google.com/appengine/docs/standard/python3/quickstart

What you'll learn

  • How to create a simple Python server on Google App Engine.
  • How to update the code without taking the server down.

What you'll need

  • Familiarity using Python 3
  • Familiarity with standard Linux text editors such as vim, emacs, or nano

Survey

How will you use this tutorial?

Read it through only Read it and complete the exercises

How would you rate your experience with Python?

Novice Intermediate Proficient

How would you rate your experience with using Google Cloud services?

Novice Intermediate Proficient

Self-paced environment setup

  1. Sign in to Cloud Console and create a new project or reuse an existing one. (If you don't already have a Gmail or G Suite account, you must create one.)

WvZ4Lcm6k-4AOA_v1j9HE6MO5-TJvI3TlGp4PNpqf_gbPLt9pq3c0ZiMOtT4bZZ1urP6tVOzAsTdpQ9OLYDcvvhpbdHcqqLRoQ7JFy-tCyKyE8gn9BtOwo8T3CLjOoTVL17Czok8-A

RQVrJ6Mj_SCQFipYRkdxqlWmokfg9D05dd5oq8qWaF_ci584t_xHW6M5-8fGR5i5JIUkx2r1G_5Ue630biVrQmSLKf_s2OiU9dnc4PZD1VnWSJf2AzZwzZP8UYiI__zqurLdj_7Qvw

ARsF00OMeFtN4MASqu6GKhjNAf8ANuL29fBrkJ6qnh3DrxdXFAftS-klvH5WNZ8XculywaNSnNZk3WoUP0d5UBQstpHXKgiWGJ3Wox3MVsL5TVhhSWt66U8yBfZBmNRksXds-_6wdA

Remember the project ID, a unique name across all Google Cloud projects (the name above has already been taken and will not work for you, sorry!). It will be referred to later in this codelab as PROJECT_ID.

  1. Next, you'll need to enable billing in Cloud Console in order to use Google Cloud resources.

Running through this codelab shouldn't cost much, if anything at all. Be sure to to follow any instructions in the "Cleaning up" section which advises you how to shut down resources so you don't incur billing beyond this tutorial. New users of Google Cloud are eligible for the $300USD Free Trial program.

Start Cloud Shell

While Google Cloud can be operated remotely from your laptop, in this codelab you will be using Cloud Shell, a command line environment running in the Cloud.

Activate Cloud Shell

  1. From the Cloud Console, click Activate Cloud Shell U3KqmcaywP9RcSjMDokVtfw7D3-7w-bFzhVEwwLx4kib1pcVJyZTc1AiQ5uf0x263MlnH23MO7OUTXsXwDdEjvsQsosC_kmZ4xmoFaVUMdTUeD6817oEW6G_cCw7ZzXSKL1z1L0PHQ.

HMjAm7ml5v7v4KhMG9Bptnp1MUiRh9c4M0K95kDG5vOQNCcMgNcGRqi9Z1JFIUpXzduJkQQai7o4T117GgcAx4VvJtm81L3EMO3tSFdo50BSfSh2uaQzMjP6eSLfgEzKVtwFbvWqig

If you've never started Cloud Shell before, you'll be presented with an intermediate screen (below the fold) describing what it is. If that's the case, click Continue (and you won't ever see it again). Here's what that one-time screen looks like:

oT-m4j50PqHO4zJIeW-_AG7XGlu76LUvukyZtWZBb9HIVZ-3PllJ103_NHIrhalNmfHT-2lCJFYJsFUTcCCdSe58ziWkSlBjbpfyN_O0UtoOyQCSL8DgHkYTFV9Txx_osxLryhtayg

It should only take a few moments to provision and connect to Cloud Shell.

je6hS0p4KcC104UEGhKzzcXCjYPcfIWl9u8JYW9pf4ZrsP7xFLT0Ua2XhbPV__h1fpA0Th4YOCWO5RdUtIH9uFUCCBGiplw-Q-d8PgCwvzPx1Ix6dUNu0NRAU9rFHh0-QKohgkhg5w

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory and runs in Google Cloud, greatly enhancing network performance and authentication. Much, if not all, of your work in this codelab can be done with simply a browser or your Chromebook.

Once connected to Cloud Shell, you should see that you are already authenticated and that the project is already set to your project ID.

  1. Run the following command in Cloud Shell to confirm that you are authenticated:
gcloud auth list

Command output

 Credentialed Accounts
ACTIVE  ACCOUNT
*       <my_account>@<my_domain.com>

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
gcloud config list project

Command output

[core]
project = <PROJECT_ID>

If it is not, you can set it with this command:

gcloud config set project <PROJECT_ID>

Command output

Updated property [core/project].

After Cloud Shell launches, you can use the command line to invoke the Cloud SDK gcloud command or other tools available on the virtual machine instance. You can use your $HOME directory in persistent disk storage to store files across projects and between Cloud Shell sessions. Your $HOME directory is private to you and cannot be accessed by other users.

Let's get started by creating a new folder in your $HOME directory for the application:

mkdir ~/helloworld
cd ~/helloworld

Create a file named main.py:

touch main.py

Edit the file using your preferred command line editor (nano, vim, or emacs) or opening the editor in the top right side:

e22501ac54642dc0.png

main.py

from flask import Flask

# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
app = Flask(__name__)


@app.route("/", methods=["GET"])
def hello():
    """ Return a friendly HTTP greeting. """
    return "Hello World!\n"


if __name__ == "__main__":
    # Used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    app.run(host="localhost", port=8080, debug=True)

To specify the dependencies of your web app, create a requirements.txt file in the root directory of your project with the exact version of Flask to use:

touch requirements.txt

requirements.txt

Flask==1.1.2

To deploy your web app to App Engine, you need an app.yaml file. This configuration file defines your web app's settings for App Engine.

Create and edit the app.yaml file in the root directory of your project:

touch app.yaml

app.yaml

runtime: python38

Check the content of your directory:

ls

You must have the 3 following files:

app.yaml  main.py  requirements.txt

Deploy your web app with the following command:

gcloud app deploy

The first time, you need to choose a deployment region:

Please choose the region where you want your App Engine application
located:

 [1] asia-east2
...
 [7] australia-southeast1
 [8] europe-west
 [9] europe-west2
...
 [12] northamerica-northeast1
 [13] southamerica-east1
...
 [19] us-west4
...
Please enter your numeric choice:

Confirm to launch the deployment:

Creating App Engine application in project [PROJECT_ID] and region [REGION]....done.
Services to deploy:

descriptor:      [~/helloworld/app.yaml]
source:          [~/helloworld]
target project:  [PROJECT_ID]
target service:  [default]
target version:  [YYYYMMDDtHHMMSS]
target url:      [https://PROJECT_ID.REGION_ID.r.appspot.com]

Do you want to continue (Y/n)?

Your app gets deployed:

Beginning deployment of service [default]...
Created .gcloudignore file. See `gcloud topic gcloudignore` for details.
╔════════════════════════════════════════════
╠═ Uploading 3 files to Google Cloud Storage 
╚════════════════════════════════════════════
File upload done.
Updating service [default]...done.
Setting traffic split for service [default]...done.
Deployed service [default] to [https://PROJECT_ID.REGION_ID.r.appspot.com]

Your web app is now ready to respond to HTTP requests on https://PROJECT_ID.REGION_ID.r.appspot.com.

Your web app is ready to respond to HTTP requests on https://PROJECT_ID.REGION_ID.r.appspot.com.

First, retrieve your web app hostname with the gcloud app describe command:

APPENGINE_HOSTNAME=$(gcloud app describe --format "value(defaultHostname)")

Test your web app with this simple HTTP GET request:

curl https://$APPENGINE_HOSTNAME

You should get the following answer:

Hello World!

Summary

In the previous steps, you set up a simple Python web app, ran, and deployed the application on App Engine.

Modify your web app by changing 3 lines (the import line and the hello function) in your main.py file:

main.py

from flask import Flask, request

# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
app = Flask(__name__)


@app.route("/", methods=["GET"])
def hello():
    """ Return a friendly HTTP greeting. """
    who = request.args.get("who", "World")
    return f"Hello {who}!\n"


if __name__ == "__main__":
    # Used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    app.run(host="localhost", port=8080, debug=True)

Update your web app by deploying again:

gcloud app deploy

The new version of your app gets deployed:

Beginning deployment of service [default]...
╔════════════════════════════════════════════
╠═ Uploading 1 file to Google Cloud Storage 
╚════════════════════════════════════════════
...
Deployed service [default] to [https://PROJECT_ID.REGION_ID.r.appspot.com]

Test the new version of your web app, exactly as you did previously:

curl https://$APPENGINE_HOSTNAME

You should get the same answer:

Hello World!

Test it with the optional parameter:

curl https://$APPENGINE_HOSTNAME?who=Universe

You should get the following answer:

Hello Universe!

Summary

In this step, you updated and redeployed your web app without any service interruption.

You learned how to write your first App Engine web application in Python!

Learn more

License

This work is licensed under a Creative Commons Attribution 2.0 Generic License.