django-environ with Lists Environment Varibles in .env Files
One minute read
django-environ is the Python package that allows you to use Twelve-factor methodology to configure your Django application with environment variables.
It is very usefull package although there are some missing things in the
documentation like how we use
list as an environment variable?
They got doc for
nested list but not for
One of the main case for using
list would be
Let’s assume we have hosts in our
... ALLOWED_HOSTS = [ "example.com", "awesomedomain.com", "stagingdomain.com", "10.0.0.2", "22.214.171.124", ]
How can we move this hardcoded
list/array to an
.env file and use it with
env.list to your
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
Then add your hosts with comma separated into
.env which located in the root of
your project or a proper location;
Your environment variables file —
.env, can be anything and anywhere
.env.prod, as long as you configure it properly in your
# settings.py import os import environ # Set the project base directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Initiate related env class env = environ.Env() # Take environment variables from .env.dev file environ.Env.read_env(os.path.join(BASE_DIR, '.env.dev') ...