Running Django on the App Engine standard environment

Django apps that run on App Engine standard scale dynamically according to traffic.

This tutorial assumes that you're familiar with Django web development. If you're new to Django development, it's a good idea to work through writing your first Django app before continuing.

While this tutorial demonstrates Django specifically, you can use this deployment process with other Django-based frameworks, such as Wagtail and Django CMS.

This tutorial uses Django 4, which requires at least Python 3.8. App Engine standard supports Python 3.7 and higher, including Python 3.8.

Objectives

In this tutorial, you will:

  • Create and connect a Cloud SQL database.
  • Create and use Secret Manager secret values.
  • Deploy a Django app to App Engine standard.

Costs

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use the pricing calculator.

New Google Cloud users might be eligible for a free trial.

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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud SQL Admin API, Secret Manager, and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. Install the gcloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Cloud SQL Admin API, Secret Manager, and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  11. Install the gcloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. If you haven't already done so, initialize App Engine and select your preferred region:

    gcloud app create
    

Prepare your environment

Clone a sample app

The code for the Django sample app is in the GoogleCloudPlatform/python-docs-samples repository on GitHub.

  1. You can either download the sample as a ZIP file and extract it or clone the repository to your local machine:

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
    
  2. Go to the directory that contains the sample code:

    Linux/macOS

    cd python-docs-samples/appengine/standard_python3/django
    

    Windows

    cd python-docs-samples\appengine\standard_python3\django
    

Confirm your Python setup

This tutorial relies on Python to run the sample application on your machine. The sample code also requires installing dependencies

For more details, refer to the Python development environment guide.

  1. Confirm your Python is at least version 3.8.

     python -V
    

    You should see Python 3.8.0 or higher.

  2. Create a Python virtual environment and install dependencies:

    Linux/macOS

    python -m venv venv
    source venv/bin/activate
    pip install --upgrade pip
    pip install -r requirements.txt
    

    Windows

    python -m venv venv
    venv\scripts\activate
    pip install --upgrade pip
    pip install -r requirements.txt
    

Download Cloud SQL Auth Proxy to connect to Cloud SQL from your local machine

When deployed, your app uses the Cloud SQL Auth Proxy that is built into the App Engine standard environment to communicate with your Cloud SQL instance. However, to test your app locally, you must install and use a local copy of the proxy in your development environment. For more details, refer to the Cloud SQL Auth Proxy guide.

The Cloud SQL Auth Proxy uses the Cloud SQL API to interact with your SQL instance. To do this, it requires application authentication through the gcloud CLI.

  1. Authenticate and acquire credentials for the API:

    gcloud auth application-default login
    
  2. Download and install the Cloud SQL Auth Proxy to your local machine.

    Linux 64-bit

    1. Download the Cloud SQL Auth Proxy:
      curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.3/cloud-sql-proxy.linux.amd64
    2. Make the Cloud SQL Auth Proxy executable:
      chmod +x cloud-sql-proxy

    Linux 32-bit

    1. Download the Cloud SQL Auth Proxy:
      curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.3/cloud-sql-proxy.linux.386
    2. If the curl command is not found, run sudo apt install curl and repeat the download command.
    3. Make the Cloud SQL Auth Proxy executable:
      chmod +x cloud-sql-proxy

    macOS 64-bit

    1. Download the Cloud SQL Auth Proxy:
      curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.3/cloud-sql-proxy.darwin.amd64
    2. Make the Cloud SQL Auth Proxy executable:
      chmod +x cloud-sql-proxy

    Mac M1

    1. Download the Cloud SQL Auth Proxy:
        curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.3/cloud-sql-proxy.darwin.arm64
        
    2. Make the Cloud SQL Auth Proxy executable:
        chmod +x cloud-sql-proxy
        

    Windows 64-bit

    Right-click https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.3/cloud-sql-proxy.x64.exe and select Save Link As to download the Cloud SQL Auth Proxy. Rename the file to cloud-sql-proxy.exe.

    Windows 32-bit

    Right-click https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.3/cloud-sql-proxy.x86.exe and select Save Link As to download the Cloud SQL Auth Proxy. Rename the file to cloud-sql-proxy.exe.

    Cloud SQL Auth Proxy Docker image

    The Cloud SQL Auth Proxy has different container images, such as distroless, alpine, and buster. The default Cloud SQL Auth Proxy container image uses distroless, which contains no shell. If you need a shell or related tools, then download an image based on alpine or buster. For more information, see Cloud SQL Auth Proxy Container Images.

    You can pull the latest image to your local machine using Docker by using the following command:

    docker pull gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.18.3
    

    Other OS

    For other operating systems not included here, you can compile the Cloud SQL Auth Proxy from source.

    You can choose to move the download to somewhere common, such as a location on your PATH, or your home directory. If you choose to do this, when you start the Cloud SQL Auth Proxy later on in the tutorial, remember to reference your chosen location when using cloud-sql-proxy commands.

Create backing services

This tutorial uses several Google Cloud services to provide the database, media storage, and secret storage that support the deployed Django project. These services are deployed in a specific region. For efficiency between services, all services should be deployed in the same region. For more information about the closest region to you, see Products available by region.

This tutorial uses the integrated static asset hosting mechanisms in App Engine standard.

Set up a Cloud SQL for PostgreSQL instance

Django officially supports multiple relational databases, but offers the most support for PostgreSQL. PostgreSQL is supported by Cloud SQL, so this tutorial chooses to use that type of database.

The following section describes the creation of a PostgreSQL instance, database, and database user for the app.

  1. Create the PostgreSQL instance:

    Console

    1. In the Google Cloud console, go to the Cloud SQL Instances page.

      Go to the Cloud SQL Instances page

    2. Click Create Instance.

    3. Click Choose PostgreSQL.

    4. For SQL Edition, choose "Enterprise".

    5. For Edition Preset, choose "Sandbox".

    6. In the Instance ID field, enter INSTANCE_NAME.

    7. Enter a password for the postgres user.

    8. Keep the default values for the other fields.

    9. Click Create Instance.

    It takes a few minutes for the instance to be ready for use.

    gcloud

    • Create the PostgreSQL instance:

      gcloud sql instances create INSTANCE_NAME \
          --project PROJECT_ID \
          --database-version POSTGRES_16 \
          --tier db-n1-standard-2 \
          --region REGION
      

    Replace the following:

    • INSTANCE_NAME: the Cloud SQL instance name
    • PROJECT_ID: the Google Cloud project ID
    • REGION: the Google Cloud region

    It takes a few minutes to create the instance and for it to be ready for use.

  2. Within the created instance, create a database:

    Console

    1. Within your instance page, go to the Databases tab.
    2. Click Create database.
    3. In the Database Name dialog, enter DATABASE_NAME.
    4. Click Create.

    gcloud

    • Create the database within the recently created instance:

      gcloud sql databases create DATABASE_NAME \
          --instance INSTANCE_NAME
      

      Replace DATABASE_NAME with a name for the database inside the instance.

  3. Create a database user:

    Console

    1. Within your instance page, go to the Users tab.
    2. Click Add User Account.
    3. In the Choose how to authenticate dialog under "Built-in Authentication":
    4. Enter the username DATABASE_USERNAME.
    5. Enter the password DATABASE_PASSWORD
    6. Click Add.

    gcloud

    • Create the user within the recently created instance:

      gcloud sql users create DATABASE_USERNAME \
          --instance INSTANCE_NAME \
          --password DATABASE_PASSWORD
      

      Replace PASSWORD with a secure password.

Store secret values in Secret Manager

Now that the backing services are configured, Django needs information about these services. Instead of putting these values directly into the Django source code, this tutorial uses Secret Manager to store this information securely.

Create Django environment file as a Secret Manager secret

You store the settings required to start Django in a secured env file. The sample app uses the Secret Manager API to retrieve the secret value, and the django-environ package to load the values into the Django environment. The secret is configured to be accessible by App Engine standard.

  1. Create a file called .env, defining the database connection string, the media bucket name, and a new SECRET_KEY value:

    echo DATABASE_URL=postgres://DATABASE_USERNAME:DATABASE_PASSWORD@//cloudsql/PROJECT_ID:REGION:INSTANCE_NAME/DATABASE_NAME > .env
    echo GS_BUCKET_NAME=PROJECT_ID_MEDIA_BUCKET >> .env
    echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env
    
  2. Store the secret in Secret Manager:

    Console

    1. In the Google Cloud console, go to the Secret Manager page.

      Go to the Secret Manager page

    2. Click Create secret

    3. In the Name field, enter django_settings.

    4. In the Secret value dialog, paste the contents of your .env file.

    5. Click Create secret.

    6. Delete the local file to prevent local setting overrides.

    gcloud

    1. Create a new secret, django_settings, with the value of the .env file:

      gcloud secrets create django_settings --data-file .env
      
    2. Delete the local file to prevent local setting overrides:

      rm .env
      
  3. Configure access to the secret:

    Console

  4. Click the Permissions tab.

  5. Click Grant access.

  6. In the New Members field, enter PROJECT_ID@appspot.gserviceaccount.com, and then press Enter.

  7. In the Role drop-down menu, select Secret Manager Secret Accessor.

  8. Click Save.