Environment variables are dynamic values which can be used by the processes or applications running on the server. One of the advantages in using them is that you can isolate specific values from your codebase and consequently avoid storing them in a (potentially insecure) place.

They come in the form of Key-Value pairs and the Control Panel provides a nice and nifty way to define them. (See below for how to use them in local projects.)

Using the Control Panel

Let's assume your Django application requires you to provide a secret Facebook Token. The following steps will describe how you'd setup the variable for the test and the live server environment.

  1. Select your project from the overview page on the Control Panel
  2. On the left menu, choose "Environment Variables"
  3. Define in the designated areas your variables for the test and/or live environment, as shown on the screenshot below.
  4. Hit save to apply all changes

Accessing environment variables in code

A typical use for environment variables is to use them to provide a Django setting that you don't wish to hard-code in your project.

To access the environment variable in your Python code, you could use something like this:  

import os
my_variable = os.environ.get('my_environment_variable')

It's important to note that if your variable represents anything other than a string, you will need to interpret the variable appropriately, as os.environ.get will only return a string.

You can also use env()  (from the getenv  package), which will parse the variable as Python code.

Common environment variables/settings

Divio Cloud automatically converts a number of environment variables into key Django settings, interpreting their type correctly so that you don't need to do extra work on them. Some of these are:

  • BASE_DIR
  • CACHE_URL
  • DATABASE_URL
  • DATA_ROOT
  • DEBUG
  • DISABLE_TEMPLATE_CACHE
  • ENABLE_SYNCING
  • ROOT_URLCONF
  • SECRET_KEY
  • SECURE_SSL_REDIRECT
  • SECURE_REDIRECT_EXEMPT
  • SECURE_HSTS_SECONDS
  • SESSION_COOKIE_SECURE
  • SECURE_PROXY_SSL_HEADER
  • SESSION_COOKIE_HTTPONLY
  • SECURE_CONTENT_TYPE_NOSNIFF
  • SECURE_BROWSER_XSS_FILTER

Setting environment variables locally

You may need to set some variables locally. For this purpose, your project contains a .env-local file. Provide variables in the format:

DEBUG=True
STAGE=local
DATABASE_URL=postgres://postgres@postgres:5432/db
Did this answer your question?