docs: https://django-environ.readthedocs.io/en/latest/
Django-environ officially supports Django 1.8 ~ 2.0.
Installation:
代码语言:javascript复制$ pip install django-environ
NOTE: No need to add it to INSTALLED_APPS.
Then create a .env
file to project path:
DEBUG=True
SECRET_KEY=your-secret-key
DATABASE_URL=psql://urser:un-githubbedpassword@127.0.0.1:8458/database
SQLITE_URL=sqlite:///my-local-sqlite.db
CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213
REDIS_URL=rediscache://127.0.0.1:6379/1?client_class=django_redis.client.DefaultClient&password=ungithubbed-secret
And use it with settings.py above. Don’t forget to add .env
in your .gitignore
(tip: add .env.example
with a template of your variables).
import environ
# initialize env
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env(".env")
# False if not in os.environ
DEBUG = env('DEBUG')
# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# Parse database connection url strings like psql://user:pass@127.0.0.1:8458/db
DATABASES = {
# read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found
'default': env.db(),
# read os.environ['SQLITE_URL']
'extra': env.db('SQLITE_URL', default='sqlite:////tmp/my-tmp-sqlite.db')
}
CACHES = {
# read os.environ['CACHE_URL'] and raises ImproperlyConfigured exception if not found
'default': env.cache(),
# read os.environ['REDIS_URL']
'redis': env.cache('REDIS_URL')
}
See the similar code, sans django-environ.