Platform.sh User Documentation

Configure Django for Platform.sh

Sign up for Upsun

Get your free trial by clicking the link below.

Get your Upsun free trial

You now have a project running on Platform.sh. In many ways, a project is just a collection of tools around a Git repository. Just like a Git repository, a project has branches, called environments. Each environment can then be activated. Active environments are built and deployed, giving you a fully isolated running site for each active environment.

Once an environment is activated, your app is deployed through a cluster of containers. You can configure these containers in three ways, each corresponding to a YAML file:

  • Configure apps in a .platform.app.yaml file. This controls the configuration of the container where your app lives.
  • Add services in a .platform/services.yaml file. This controls what additional services are created to support your app, such as databases or search servers. Each environment has its own independent copy of each service. If you’re not using any services, you don’t need this file.
  • Define routes in a .platform/routes.yaml file. This controls how incoming requests are routed to your app or apps. It also controls the built-in HTTP cache. If you’re only using the single default route, you don’t need this file.

Start by creating empty versions of each of these files in your repository:

# Create empty Platform.sh  configuration files
mkdir -p .platform && touch .platform/services.yaml && touch .platform/routes.yaml && touch .platform.app.yaml

Now that you’ve added these files to your project, configure each one for Django in the following sections. Each section covers basic configuration options and presents a complete example with comments on why Django requires those values.

Configure apps in .platform.app.yaml Anchor to this heading

Your app configuration in a .platform.app.yaml file is allows you to configure nearly any aspect of your app. For all of the options, see a complete reference. The following example shows a complete configuration with comments to explain the various settings.

The examples vary based on whether you use Pip, Pipenv, or Poetry to manage dependencies.

#########################
# Django 4 using pip
##########################
# Container configuration.

# Complete list of all available properties: https://docs.platform.sh/create-apps/app-reference.html

# A unique name for the app. Must be lowercase alphanumeric characters. Changing the name destroys data associated
# with the app.
name: 'app'

# The runtime the application uses.
# Complete list of available runtimes: https://docs.platform.sh/create-apps/app-reference.html#types
type: 'python:3.10'

# The relationships of the application with services or other applications.
# The left-hand side is the name of the relationship as it will be exposed
# to the application in the PLATFORM_RELATIONSHIPS variable. The right-hand
# side is in the form `<service name>:<endpoint name>`.
# More information: https://docs.platform.sh/create-apps/app-reference.html#relationships
relationships:
  database: "db:postgresql"

# The size of the persistent disk of the application (in MB). Minimum value is 128.
disk: 512

# Mounts define directories that are writable after the build is complete. If set as a local source, disk property is required.
# More information: https://docs.platform.sh/create-apps/app-reference.html#mounts
mounts:
  'logs':
    source: local
    source_path: logs

# The web key configures the web server running in front of your app.
# More information: https://docs.platform.sh/create-apps/app-reference.html#web
web:
  # Commands are run once after deployment to start the application process.
  # More information: https://docs.platform.sh/create-apps/app-reference.html#web-commands
  commands:
    # The command to launch your app. If it terminates, it’s restarted immediately.
    start: "gunicorn -w 4 -b unix:$SOCKET myapp.wsgi:application"

  # More information: https://docs.platform.sh/configuration/app-containers.html#upstream
  upstream:
    # Whether your app should speak to the webserver via TCP or Unix socket. Defaults to tcp
    # More information: https://docs.platform.sh/create-apps/app-reference.html#where-to-listen
    socket_family: unix

  # Each key in locations is a path on your site with a leading /.
  # More information: https://docs.platform.sh/create-apps/app-reference.html#locations
  locations:
    "/":
      # Whether to forward disallowed and missing resources from this location to the app. A string is a path
      # with a leading / to the controller, such as /index.php.
      passthru: true
    "/static":
      # The directory to serve static assets for this location relative to the app’s root directory. Must be an
      # actual directory inside the root directory.
      root: "static"
      # The number of seconds whitelisted (static) content should be cached.
      expires: 1h
      # Whether to allow serving files which don’t match a rule.
      allow: true

# Hooks allow you to customize your code/environment as the project moves through the build and deploy stages
# More information: https://docs.platform.sh/create-apps/app-reference.html#hooks
hooks:
  # The build hook is run after any build flavor.
  # More information: https://docs.platform.sh/create-apps/hooks/hooks-comparison.html#build-hook
  build: |
    set -eu

    # Download the latest version of pip
    python3.10 -m pip install --upgrade pip

    # Install dependencies
    pip install -r requirements.txt

    # Collect static assets
    python manage.py collectstatic    

  # The deploy hook is run after the app container has been started, but before it has started accepting requests.
  # More information: https://docs.platform.sh/create-apps/hooks/hooks-comparison.html#deploy-hook
  deploy: python manage.py migrate

# Information on the app's source code and operations that can be run on it.
# More information: https://docs.platform.sh/create-apps/app-reference.html#source
source:
  ######################################################################################################################
  ##                                                                                                                  ##
  ## This source operation is part of the Platform.sh process of updating and maintaining our collection of           ##
  ## templates. For more information see https://docs.platform.sh/create-apps/source-operations.html and              ##
  ## https://github.com/platformsh/source-operations                                                                  ##
  ##                                                                                                                  ##
  ##                  YOU CAN SAFELY DELETE THIS COMMENT AND THE LINES BENEATH IT                                     ##
  ##                                                                                                                  ##
  ######################################################################################################################
  operations:
    auto-update:
      command: |
        # Upgrade pip
        python3.10 -m pip install --upgrade pip

        # Upgrade Poetry.
        ./install-poetry.sh
        export PATH="/app/.local/bin:$PATH"
        poetry update --lock

        # Upgrade pip
        poetry export -f requirements.txt > requirements.txt

        # Upgrade Pipenv.
        pip install pipenv
        pipenv update

        git add Pipfile.lock poetry.lock requirements.txt
        git commit --allow-empty -m "Dependency updates."        
#      command: |
#        curl -fsS https://raw.githubusercontent.com/platformsh/source-operations/main/setup.sh | { bash /dev/fd/3 sop-autoupdate; } 3<&0
#########################
# Django4 using pipenv
##########################
# Container configuration.

# Complete list of all available properties: https://docs.platform.sh/create-apps/app-reference.html

# A unique name for the app. Must be lowercase alphanumeric characters. Changing the name destroys data associated
# with the app.
name: 'app'

# The runtime the application uses.
# Complete list of available runtimes: https://docs.platform.sh/create-apps/app-reference.html#types
type: 'python:3.10'

# The relationships of the application with services or other applications.
# The left-hand side is the name of the relationship as it will be exposed
# to the application in the PLATFORM_RELATIONSHIPS variable. The right-hand
# side is in the form `<service name>:<endpoint name>`.
# More information: https://docs.platform.sh/create-apps/app-reference.html#relationships
relationships:
  database: "db:postgresql"

# The size of the persistent disk of the application (in MB). Minimum value is 128.
disk: 512

# Mounts define directories that are writable after the build is complete. If set as a local source, disk property is required.
# More information: https://docs.platform.sh/create-apps/app-reference.html#mounts
mounts:
  'logs':
    source: local
    source_path: logs
  '.cache':
    source: local
    source_path: cache

# The web key configures the web server running in front of your app.
# More information: https://docs.platform.sh/create-apps/app-reference.html#web
web:
  # Commands are run once after deployment to start the application process.
  # More information: https://docs.platform.sh/create-apps/app-reference.html#web-commands
  commands:
    # The command to launch your app. If it terminates, it’s restarted immediately.
    start: "pipenv run gunicorn -w 4 -b unix:$SOCKET myapp.wsgi:application"

  # More information: https://docs.platform.sh/configuration/app-containers.html#upstream
  upstream:
    # Whether your app should speak to the webserver via TCP or Unix socket. Defaults to tcp
    # More information: https://docs.platform.sh/create-apps/app-reference.html#where-to-listen
    socket_family: unix

  # Each key in locations is a path on your site with a leading /.
  # More information: https://docs.platform.sh/create-apps/app-reference.html#locations
  locations:
    "/":
      # Whether to forward disallowed and missing resources from this location to the app. A string is a path
      # with a leading / to the controller, such as /index.php.
      passthru: true
    "/static":
      # The directory to serve static assets for this location relative to the app’s root directory. Must be an
      # actual directory inside the root directory.
      root: "static"
      # The number of seconds whitelisted (static) content should be cached.
      expires: 1h
      # Whether to allow serving files which don’t match a rule.
      allow: true

# Installs global dependencies as part of the build process. They’re independent of your app’s dependencies and
# are available in the PATH during the build process and in the runtime environment. They’re installed before
# the build hook runs using a package manager for the language.
# More information: https://docs.platform.sh/create-apps/app-reference.html#dependencies
dependencies:
  python3:
    pipenv: '2022.9.4'

# Hooks allow you to customize your code/environment as the project moves through the build and deploy stages
# More information: https://docs.platform.sh/create-apps/app-reference.html#hooks
hooks:
  # The build hook is run after any build flavor.
  # More information: https://docs.platform.sh/create-apps/hooks/hooks-comparison.html#build-hook
  build: |
    set -eu

    # Download the latest version of pip
    python3.10 -m pip install --upgrade pip

    # Install dependencies
    pipenv install --deploy

    # Collect static assets
    pipenv run python manage.py collectstatic    

  # The deploy hook is run after the app container has been started, but before it has started accepting requests.
  # More information: https://docs.platform.sh/create-apps/hooks/hooks-comparison.html#deploy-hook
  deploy: pipenv run python manage.py migrate

# Information on the app's source code and operations that can be run on it.
# More information: https://docs.platform.sh/create-apps/app-reference.html#source
source:
  ######################################################################################################################
  ##                                                                                                                  ##
  ## This source operation is part of the Platform.sh process of updating and maintaining our collection of           ##
  ## templates. For more information see https://docs.platform.sh/create-apps/source-operations.html and              ##
  ## https://github.com/platformsh/source-operations                                                                  ##
  ##                                                                                                                  ##
  ##                  YOU CAN SAFELY DELETE THIS COMMENT AND THE LINES BENEATH IT                                     ##
  ##                                                                                                                  ##
  ######################################################################################################################
  operations:
    auto-update:
      command: |
        curl -fsS https://raw.githubusercontent.com/platformsh/source-operations/main/setup.sh | { bash /dev/fd/3 sop-autoupdate; } 3<&0        
#########################
# Django4 using Poetry
##########################
# Container configuration.

# Complete list of all available properties: https://docs.platform.sh/create-apps/app-reference.html

# A unique name for the app. Must be lowercase alphanumeric characters. Changing the name destroys data associated
# with the app.
name: 'app'

# The runtime the application uses.
# Complete list of available runtimes: https://docs.platform.sh/create-apps/app-reference.html#types
type: 'python:3.10'

# The relationships of the application with services or other applications.
# The left-hand side is the name of the relationship as it will be exposed
# to the application in the PLATFORM_RELATIONSHIPS variable. The right-hand
# side is in the form `<service name>:<endpoint name>`.
# More information: https://docs.platform.sh/create-apps/app-reference.html#relationships
relationships:
  database: "db:postgresql"

# The size of the persistent disk of the application (in MB). Minimum value is 128.
disk: 512

# Mounts define directories that are writable after the build is complete. If set as a local source, disk property is required.
# More information: https://docs.platform.sh/create-apps/app-reference.html#mounts
mounts:
  'logs':
    source: local
    source_path: logs

# The web key configures the web server running in front of your app.
# More information: https://docs.platform.sh/create-apps/app-reference.html#web
web:
  # Commands are run once after deployment to start the application process.
  # More information: https://docs.platform.sh/create-apps/app-reference.html#web-commands
  commands:
    # The command to launch your app. If it terminates, it’s restarted immediately.
    start: "poetry run gunicorn -w 4 -b unix:$SOCKET myapp.wsgi:application"

  # More information: https://docs.platform.sh/configuration/app-containers.html#upstream
  upstream:
    # Whether your app should speak to the webserver via TCP or Unix socket. Defaults to tcp
    # More information: https://docs.platform.sh/create-apps/app-reference.html#where-to-listen
    socket_family: unix

      # Each key in locations is a path on your site with a leading /.
    # More information: https://docs.platform.sh/create-apps/app-reference.html#locations
  locations:
    "/":
      # Whether to forward disallowed and missing resources from this location to the app. A string is a path
      # with a leading / to the controller, such as /index.php.
      passthru: true
    "/static":
      # The directory to serve static assets for this location relative to the app’s root directory. Must be an
      # actual directory inside the root directory.
      root: "static"
      # The number of seconds whitelisted (static) content should be cached.
      expires: 1h
      # Whether to allow serving files which don’t match a rule.
      allow: true

# Variables to control the environment. More information: https://docs.platform.sh/create-apps/app-reference.html#variables
variables:
  env:
    POETRY_VIRTUALENVS_IN_PROJECT: true
    POETRY_VIRTUALENVS_CREATE: false

# Hooks allow you to customize your code/environment as the project moves through the build and deploy stages
# More information: https://docs.platform.sh/create-apps/app-reference.html#hooks
hooks:
  # The build hook is run after any build flavor.
  # More information: https://docs.platform.sh/create-apps/hooks/hooks-comparison.html#build-hook
  build: |
    set -eu

    # Download the latest version of pip
    python3.10 -m pip install --upgrade pip

    # Install and configure Poetry
    #   NOTE: There is a matching export PATH=... in `.environment`, which allows the use of Poetry
    #     in the deploy hook, start command, and during SSH sessions. Make sure to include in your
    #     own projects.
    export PIP_USER=false
    curl -sSL https://install.python-poetry.org | python3 - --version $POETRY_VERSION
    export PATH="/app/.local/bin:$PATH"
    export PIP_USER=true

    # Install dependencies
    poetry install

    # Collect static assets
    poetry run python manage.py collectstatic    

  # The deploy hook is run after the app container has been started, but before it has started accepting requests.
  # More information: https://docs.platform.sh/create-apps/hooks/hooks-comparison.html#deploy-hook
  deploy: poetry run python manage.py migrate

# Information on the app's source code and operations that can be run on it.
# More information: https://docs.platform.sh/create-apps/app-reference.html#source
source:
  # The path where the app code lives. Defaults to the directory of the .platform.app.yaml file. Useful for multi-app setups.
  root:

  ######################################################################################################################
  ##                                                                                                                  ##
  ## This source operation is part of the Platform.sh process of updating and maintaining our collection of           ##
  ## templates. For more information see https://docs.platform.sh/create-apps/source-operations.html and              ##
  ## https://github.com/platformsh/source-operations                                                                  ##
  ##                                                                                                                  ##
  ##                  YOU CAN SAFELY DELETE THIS COMMENT AND THE LINES BENEATH IT                                     ##
  ##                                                                                                                  ##
  ######################################################################################################################
  operations:
    auto-update:
      command: |
        curl -fsS https://raw.githubusercontent.com/platformsh/source-operations/main/setup.sh | { bash /dev/fd/3 sop-autoupdate; } 3<&0        

How to start your app Anchor to this heading

Each of these examples includes a command to start your app under web.commands.start. It uses the Gunicorn WSGI server and Unix sockets.

.platform.app.yaml
web:
    upstream:
        socket_family: unix
    commands:
        start: "gunicorn -w 4 -b unix:$SOCKET myapp.wsgi:application"
.platform.app.yaml
web:
    upstream:
        socket_family: unix
    commands:
        start: "pipenv run gunicorn -w 4 -b unix:$SOCKET myapp.wsgi:application"
.platform.app.yaml
web:
    upstream:
        socket_family: unix
    commands:
        start: "poetry run gunicorn -w 4 -b unix:$SOCKET myapp.wsgi:application"

To use this server, update the command to replace the WSGI application Gunicorn calls. The example uses a myapp/wsgi.py file with a callable application.

To use a different web server, change this start command. For examples of how to do so, see more about Python web servers.

Add services in .platform/services.yaml Anchor to this heading

You can add the managed services you need for you app to run in the .platform/services.yaml file. You pick the major version of the service and security and minor updates are applied automatically, so you always get the newest version when you deploy. You should always try any upgrades on a development branch before pushing to production.

You can add other services if desired, such as Solr or Elasticsearch. You need to configure Django to use those services once they’re enabled.

Each service entry has a name (db in the example) and a type that specifies the service and version to use. Services that store persistent data have a disk key, to specify the amount of storage.

Below is an example configuration to make PostgreSQL available for your Django application.

.platform/services.yaml
# The services of the project.
#
# Each service listed will be deployed
# to power your Platform.sh project.
# More information: https://docs.platform.sh/add-services.html
# Full list of available services: https://docs.platform.sh/add-services.html#available-services
db:
  type: postgresql:12
  disk: 1024

Define routes Anchor to this heading

All HTTP requests sent to your app are controlled through the routing and caching you define in a .platform/routes.yaml file.

The two most important options are the main route and its caching rules. A route can have a placeholder of {default}, which is replaced by your domain name in production and environment-specific names for your preview environments. The main route has an upstream, which is the name of the app container to forward requests to.

You can enable HTTP cache. The router includes a basic HTTP cache. By default, HTTP caches includes all cookies in the cache key. So any cookies that you have bust the cache. The cookies key allows you to select which cookies should matter for the cache.

You can also set up routes as HTTP redirects. In the following example, all requests to www.{default} are redirected to the equivalent URL without www. HTTP requests are automatically redirected to HTTPS.

If you don’t include a .platform/routes.yaml file, a single default route is used. This is equivalent to the following:

.platform/routes.yaml
https://{default}/:
  type: upstream
  upstream: <APP_NAME>:http

Where <APP_NAME> is the name you’ve defined in your app configuration.

The following example presents a complete definition of a main route for a Django app:

.platform/routes.yaml
# The routes of the project.
#
# Each route describes how an incoming URL is going
# to be processed by Platform.sh.
# More information: https://docs.platform.sh/define-routes.html
"https://{default}/":
  type: upstream
  upstream: "app:http"

# A basic redirect definition
# More information: https://docs.platform.sh/define-routes.html#basic-redirect-definition
"https://www.{default}/":
  type: redirect
  to: "https://{default}/"

Is this page helpful?