Florian Demmer
django-environ
Django Meetup, 2017-11-07
The Twelve-Factor App
III. Config
Store config in the environment
https://12factor.net/config
django-admin startproject myproject
from django.conf import settings
in manage.py and wsgi.py:
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE',
'myproject.settings'
)
run:
DJANGO_SETTINGS_MODULE=myproject.settings.dev ./manage.py runserver
export SECRET_KEY=foobar
$ python3 -c "import os; print(os.environ['SECRET_KEY'])"
foobar
$ export CACHE_URL=redis://localhost:6379/0
$ python -c "
import environ;
env=environ.Env();
print(env.cache())
"
{
'LOCATION': 'redis://localhost:6379/0',
'BACKEND': 'django_redis.cache.RedisCache'
}
$ python -c " import environ; env=environ.Env(); print( env.cache( 'MEMCACHED_URL', default='locmemcache://unique-snowflake') )" { 'LOCATION': 'unique-snowflake', 'BACKEND': 'django...locmem.LocMemCache' }
$ export DATABASE_URL=postgresql://app:password@localhost:5432/app?ATOMIC_REQUESTS=1 $ python -c "import environ; env=environ.Env(); print(env.db())" {'ENGINE': 'django...postgresql_psycopg2', 'HOST': 'localhost', 'ATOMIC_REQUESTS': True, 'USER': 'app', 'OPTIONS': {}, 'PASSWORD': 'password', 'PORT': 5432, 'NAME': 'app'}
$ python -c "import environ; env=environ.Env(); print(env.db(NO_DATABASE_URL))"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File ".../django-environ/environ/environ.py", line 207, in db_url
return self.db_url_config(self.get_value(var, default=default), engine=engine)
File ".../django-environ/environ/environ.py", line 280, in get_value
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
$ export BOOL_=1
$ python -c "import environ; env=environ.Env(); print(env.bool('BOOL_'))"
True
$ export FLOAT_=3,14
$ python -c "import environ; env=environ.Env(); print(env.float('FLOAT_'))"
3.14
$ export LIST_=a,b,c,d,1,2,3
$ python -c "import environ; env=environ.Env(); print(env.list('LIST_'))"
['a', 'b', 'c', 'd', '1', '2', '3']
$ export DICT_=foo=bar,spam=42,ham=3.14
$ python -c "import environ; env=environ.Env(); print(env.dict('DICT_'))"
{'foo': 'bar', 'ham': '3.14', 'spam': '42'}
$ python -c "
import environ;
env=environ.Env();
environ.Env.read_env('.env')
"
https://12factor.net/config
https://django-environ.readthedocs.io/en/latest/
https://github.com/fdemmer/django-environ
my twitter: @fdemmer
slides: https://slides.com/fdemmer