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

What you'll need

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 Platform services?

Novice Intermediate Proficient

Self-paced environment setup

If you don't already have a Google Account (Gmail or Google Apps), you must create one. Sign-in to Google Cloud Platform console (console.cloud.google.com) and create a new project:

Screenshot from 2016-02-10 12:45:26.png

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.

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

Running through this codelab shouldn't cost you more than a few dollars, but it could be more if you decide to use more resources or if you leave them running (see "cleanup" section at the end of this document).

New users of Google Cloud Platform are eligible for a $300 free trial.

Start Cloud Shell

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

Activate Google Cloud Shell

From the GCP Console click the Cloud Shell icon on the top right toolbar:

Then click "Start Cloud Shell":

It should only take a few moments to provision and connect to the environment:

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on the Google Cloud, greatly enhancing network performance and authentication. Much, if not all, of your work in this lab can be done with simply a browser or your Google 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.

Run the following command in Cloud Shell to confirm that you are authenticated:

gcloud auth list

Command output

Credentialed accounts:
 - <myaccount>@<mydomain>.com (active)
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

Using one of your preferred command line editors (nano, vim, or emacs), create a file named main.py:

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__":
    # This is 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="127.0.0.1", port=8080, debug=True)

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

requirements.txt

Flask==1.0.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.

To configure your web app for deployment to App Engine, create an app.yaml file in the root directory of your project:

app.yaml

runtime: python37

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    (supports standard and flexible)
...
 [5] australia-southeast1 (supports standard and flexible)
 [6] europe-west   (supports standard and flexible)
...
 [10] northamerica-northeast1 (supports standard and flexible)
...
 [14] us-east4      (supports standard and flexible)
...
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.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.appspot.com]

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

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

Test your web app with this simple HTTP GET request:

curl https://PROJECT_ID.appspot.com

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__':
    # This is 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='127.0.0.1', 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.appspot.com]

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

curl https://PROJECT_ID.appspot.com

You should get the same answer:

Hello World!

Test it with the optional parameter:

curl https://PROJECT_ID.appspot.com?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.