Getting started with App Engine (Python 3)

1. Overview

befa7a877ccdd35d.png

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
  • 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 Google Cloud services?

Novice Intermediate Proficient

2. Setup and requirements

Self-paced environment setup

  1. Sign-in to the Google Cloud Console and create a new project or reuse an existing one. If you don't already have a Gmail or Google Workspace account, you must create one.

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • The Project name is the display name for this project's participants. It is a character string not used by Google APIs. You can always update it.
  • The Project ID is unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference your Project ID (typically identified as PROJECT_ID). If you don't like the generated ID, you might generate another random one. Alternatively, you can try your own, and see if it's available. It can't be changed after this step and remains for the duration of the project.
  • For your information, there is a third value, a Project Number, which some APIs use. Learn more about all three of these values in the documentation.
  1. Next, you'll need to enable billing in the Cloud Console to use Cloud resources/APIs. Running through this codelab won't cost much, if anything at all. To shut down resources to avoid incurring billing beyond this tutorial, you can delete the resources you created or delete the project. New Google Cloud users are eligible for the $300 USD 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 853e55310c205094.png.

3c1dabeca90e44e5.png

If this is your first time starting Cloud Shell, you're presented with an intermediate screen describing what it is. If you were presented with an intermediate screen, click Continue.

9c92662c6a846a5c.png

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

9f0e51b578fecce5.png

This virtual machine is loaded with all the development tools needed. It offers a persistent 5 GB 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 a browser.

Once connected to Cloud Shell, you should see that you are authenticated and that the project is 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`
  1. Run the following command in Cloud Shell to confirm that the gcloud command knows about your project:
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].

3. Write the web app

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 with your preferred command line editor (nano, vim, or emacs) or by clicking the Cloud Shell Editor button:

10af7b1a6240e9f4.gif

To directly edit the file with Cloud Shell Editor, use this command:

cloudshell edit main.py

main.py

import flask

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


@app.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)

4. Define the dependencies

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

touch requirements.txt

To edit the file with Cloud Shell Editor, use this command:

cloudshell edit requirements.txt

requirements.txt

# https://pypi.org/project/Flask
Flask==3.0.2

5. Configure the deployment

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.

From the terminal, create and edit the app.yaml file in the root directory of your project:

touch app.yaml

To edit the file with Cloud Shell Editor, use this command:

cloudshell edit app.yaml

app.yaml

runtime: python312

6. Deploy the web app

From the terminal, check the content of your directory:

ls

You should 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
100%
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.

7. Test the web app

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.

8. Update the web app

Modify your web app by changing the hello() function body in your main.py file.

To edit the file with Cloud Shell Editor, use this command:

cloudshell edit main.py

main.py

import flask

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


@app.get("/")
def hello():
    """Return a friendly HTTP greeting."""
    # return "Hello World!\n"  # ← Replace this line
    who = flask.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)

From the terminal, redeploy to update your web app:

gcloud app deploy --quiet

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.

9. Congratulations!

You learned 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.