Quickstart for Python in the App Engine Flexible Environment

Region ID

The REGION_ID is an abbreviated code that Google assigns based on the region you select when you create your app. The code does not correspond to a country or province, even though some region IDs may appear similar to commonly used country and province codes. For apps created after February 2020, REGION_ID.r is included in App Engine URLs. For existing apps created before this date, the region ID is optional in the URL.

Learn more about region IDs.

This quickstart shows you how to create a small App Engine app that displays a short message.


For step-by-step guidance on this task directly in Cloud Shell Editor, click Guide me:

Guide me


The following sections take you through the same steps as clicking Guide me.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  4. Enable the Cloud Build API.

    Enable the API

  5. Install and initialize the Cloud SDK.
  6. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  7. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  8. Enable the Cloud Build API.

    Enable the API

  9. Install and initialize the Cloud SDK.

Additional prerequisites

  1. Initialize your App Engine app with your project and choose its region:

    gcloud app create --project=[YOUR_PROJECT_ID]
    

    When prompted, select the region where you want to locate your App Engine application.

  2. Install the following prerequisites:

    • Run the following command to install the gcloud component that includes the App Engine extension for Python:

      gcloud components install app-engine-python
      

  3. Prepare your environment for Python development. It is recommended that you have the latest version of Python, pip, and other related tools installed on your system. For instructions, refer to the Python Development Environment Setup Guide.

App Engine locations

App Engine is regional, which means the infrastructure that runs your apps is located in a specific region, and Google manages it so that it is available redundantly across all of the zones within that region.

Meeting your latency, availability, or durability requirements are primary factors for selecting the region where your apps are run. You can generally select the region nearest to your app's users, but you should consider the locations where App Engine is available as well as the locations of the other Google Cloud products and services that your app uses. Using services across multiple locations can affect your app's latency as well as its pricing.

You cannot change an app's region after you set it.

If you already created an App Engine application, you can view its region by doing one of the following:

This quickstart demonstrates a simple Python app written with the Flask web framework that can be deployed to App Engine. Although this sample uses Flask, you can use any web framework that satisfies the requirements above. Alternative frameworks include Django, Pyramid, Bottle, and web.py.

Download the Hello World app

We've created a simple Hello World app for Python so you can quickly get a feel for deploying an app to the Google Cloud.

  1. Clone the Hello World sample app repository to your local machine.

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples
    

    Alternatively, you can download the sample as a zip file and extract it.

  2. Change to the directory that contains the sample code.

    cd python-docs-samples/appengine/flexible/hello_world
    

Run Hello World on your local machine

To run the Hello World app on your local computer:

Mac OS / Linux

  1. Create an isolated Python environment:
    python3 -m venv env
    source env/bin/activate
  2. If you're not in the directory that contains the sample code, navigate to the directory that contains the hello_world sample code. Then install dependencies:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  3. Run the application:
    python main.py
  4. In your web browser, enter the following address:
    http://localhost:8080

Windows

Use PowerShell to run your Python packages.

  1. Locate your installation of PowerShell.
  2. Right-click on the shortcut to PowerShell and start it as an administrator.
  3. Create an isolated Python environment.
    python -m venv env
    .\env\Scripts\activate
  4. Navigate to your project directory and install dependencies. If you're not in the directory that contains the sample code, navigate to the directory that contains the hello_world sample code. Then, install dependencies:
    cd YOUR_SAMPLE_CODE_DIR
    pip install -r requirements.txt
  5. Run the application:
    python main.py
  6. In your web browser, enter the following address:
    http://localhost:8080

The Hello World message from the sample app displays on the page. In your terminal window, press Ctrl+C to exit the web server.

Deploy and run Hello World on App Engine

To deploy your app to the App Engine flexible environment:

  1. Deploy the Hello World app by running the following command from the hello_world directory:

    gcloud app deploy

    Learn about the optional flags.

    Common gcloud command flags

    • Include the --version flag to specify an ID that uniquely identifies that version of your app, otherwise one is generated for you. Example: --version [YOUR_VERSION_ID]
    • Include the --project flag to specify an alternate Cloud project ID to what you initialized as the default in the gcloud tool. Example: --project [YOUR_PROJECT_ID]

    Example:

    gcloud app deploy --version pre-prod-5 --project my-sample-app

    To learn more about deploying your app from the command line, see Testing and Deploying Your App . For a list of all the command flags, see the gcloud app deploy reference.

  2. Launch your browser to view the app at https://PROJECT_ID.REGION_ID.r.appspot.com

    gcloud app browse
    where PROJECT_ID represents your Google Cloud project ID.

This time, the page that displays the Hello World message is delivered by a web server running on an App Engine instance.

Congratulations! You've deployed your first Python app to App Engine flexible environment!

If you encountered any errors deploying your application, check the troubleshooting tips.

See the following sections for information about cleaning up as well as links to possible next steps that you can take.

Clean up

To avoid incurring charges, you can delete your Cloud project to stop billing for all the resources used within that project.

  1. In the Cloud Console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

What's next

Learn the whole platform

Now that you know what it's like to develop and deploy App Engine apps, you can explore the rest of Google Cloud. You already have the Cloud SDK installed which gives you the tools to interact with products like Cloud SQL, Cloud Storage, Firestore, and more.

For a guided walkthrough that teaches you how to create an app that uses the entire platform, not just App Engine, check out our quickstart on creating the Bookshelf app.

Learn about the App Engine flexible environment

Here are some topics to help continue your learning about App Engine.

Hello World code review

Hello World is the simplest possible App Engine app, as it contains only one service, has only one version, and all of the code is located within the app's root directory. This section describes each of the app files in detail.

main.py

The Hello World app is a basic one-file Flask app.

from flask import Flask


app = Flask(__name__)


@app.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello World!'


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.
    app.run(host='127.0.0.1', port=8080, debug=True)

app.yaml

The app.yaml file describes an app's deployment configuration:

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app

runtime_config:
  python_version: 3

# This sample incurs costs to run on the App Engine flexible environment. 
# The settings below are to reduce costs during testing and are not appropriate
# for production use. For more information, see:
# https://cloud.google.com/appengine/docs/flexible/python/configuring-your-app-with-app-yaml
manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

Here, app.yaml specifies the runtime used by the app, and sets env: flex, specifying that the app uses the flexible environment.

The entrypoint tells App Engine how to start the app. This app uses gunicorn to serve the Python app as an alternative to Flask's development server (used when running locally). The $PORT variable is set by App Engine when it starts the app. For more information about entrypoint, see App startup.

Additionally, the optional runtime_config section sets python_version to use Python 3. If python_version is not specified, then Python 2 is used by default. You can also specify python_version: 2 explicitly.

requirements.txt

requirements.txt and the Python package manager pip are used to declare and install application dependencies. Hello World requires Flask, a web framework, and Gunicorn, a WSGI server.

Flask==2.0.2
gunicorn==20.1.0

requirements.txt defines the libraries that will be installed both locally and when deploying to App Engine.