Building a Python application

Stay organized with collections Save and categorize content based on your preferences.

Buildpacks support language-idiomatic configuration through environment variables.

Specifying the Python Version

By default the Python Runtime buildpack uses the latest stable version of the Python interpreter. If your application requires a specific version, you can specify one by including a .python-version file in your application's root directory.

3.9.9

Using GOOGLE_PYTHON_VERSION

It is also possible to specify the Python version via the GOOGLE_PYTHON_VERSION environment variable. If both configurations are set, the GOOGLE_PYTHON_VERSION value takes precedence over the .python-version file. By default, when both the .python-version file and GOOGLE_PYTHON_VERSION environment variable are not specified, then the latest LTS version of Python is used.

To configure the buildpack to use Python 3.10 when deploying your app:

pack build sample-python --builder=gcr.io/buildpacks/builder \
  --env GOOGLE_PYTHON_VERSION="3.10.x"

Specifying dependencies with pip

The Python buildpack supports managing application dependencies using pip. Your application dependencies should be declared in a requirements.txt file the root directory.

The requirements.txt file contains one line per package. Each line contains the package name, and optionally, the requested version. For more details, see the requirements.txt reference.

The following is an example requirements.txt file:

requests==2.20.0
numpy

Configuring pip

It is possible to configure the behavior of pip using environment variables:

pack build sample-python --builder=gcr.io/buildpacks/builder \
  --env PIP_DEFAULT_TIMEOUT='60'

Private dependencies from Artifact Registry

An Artifact Registry Python repository can host private dependencies for your Python function. When building an application on Cloud Build, the Python buildpack will automatically generate Artifact Registry credentials for the Cloud Build service account. You only need to include the Artifact Registry URL in your requirements.txt without generating additional credentials. For example:

--extra-index-url REPOSITORY_URL
sampleapp
Flask==0.10.1
google-cloud-storage

Application entrypoint

The Python buildpack does not generate a default container entry-point for your application. You can configure your application's start command by including a Procfile in the root directory:

web: gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

Alternatively, you can use the GOOGLE_ENTRYPOINT environment variable:

pack build sample-python \
  --builder gcr.io/buildpacks/builder
  --env "GOOGLE_ENTRYPOINT='gunicorn --bind :$PORT main:app'"

Environment Variables

The Python buildpack supports the following environment variables to customize your container

PIP_<key>

See pip documentation.

Example: PIP_DEFAULT_TIMEOUT=60 sets --default-timeout=60 for pip commands.