Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.
|pypi| |unixbuild| |windowsbuild| |coverage| |contributors| |license| |say_thanks| |ocbackers| |ocsponsors|
django-environ allows you to use
Twelve-factor methodology_ to configure your Django application with environment variables.
|cover|
.. _settings.py:
.. code-block:: python
import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file environ.Env.read_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:[email protected]: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, without django-environ_.
::
_ _ _ | (_) (_) __| |_ __ _ _ __ __ _ ___ ______ ___ _ ____ ___ _ __ ___ _ __ / _` | |/ _` | '_ \ / _` |/ _ \______/ _ \ '_ \ \ / / | '__/ _ \| '_ \ | (_| | | (_| | | | | (_| | (_) | | __/ | | \ V /| | | | (_) | | | | \__,_| |\__,_|_| |_|\__, |\___/ \___|_| |_|\_/ |_|_| \___/|_| |_| _/ | __/ | |__/ |___/
The idea of this package is to unify a lot of packages that make the same stuff: Take a string from
os.environ, parse and cast it to some of useful python typed variables. To do that and to use the
12factor_ approach, some connection strings are expressed as url, so this package can parse it and return a
urllib.parse.ParseResult. These strings from
os.environare loaded from a
.envfile and filled in
os.environwith
setdefaultmethod, to avoid to overwrite the real environ. A similar approach is used in
Two Scoops of Django_ book and explained in
12factor-django_ article.
Using django-environ you can stop to make a lot of unversioned
settings_*.pyto configure your app. See
cookiecutter-django_ for a concrete example on using with a django project.
os.environwith .env file variables
Django-environ officially supports Django 1.11, 2.2 and 3.0.
.. code-block:: bash
$ pip install django-environ
NOTE: No need to add it to INSTALLED_APPS.
Then create a
.envfile:
.. code-block:: bash
DEBUG=on SECRET_KEY=your-secret-key DATABASE_URL=psql://user:[email protected]: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
.envin your
.gitignore(tip: add
.env.examplewith a template of your variables).
Documentation is available at
RTFD_.
.. supportedtypes:
Using unsafe characters in URLs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to use unsafe characters you have to encode with
urllib.parse.encodebefore you set into
.envfile.
.. code-block:: bash
DATABASE_URL=mysql://user:%[email protected]:3306/dbname
See https://perishablepress.com/stop-using-unsafe-characters-in-urls/ for reference.
Smart Casting ~~~~~~~~~~~~~
django-environ has a "Smart-casting" enabled by default, if you don't provide a
casttype, it will be detected from
defaulttype. This could raise side effects (see
#192). To disable it use ``env.smartcaset = False``. New major release will disable it as default.
Multiple redis cache locations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For redis cache,
multiple master/slave or shard locations_ can be configured as follows:
.. code-block:: bash
CACHE_URL='rediscache://master:6379,slave1:6379,slave2:6379/1'
Email settings ~~~~~~~~~~~~~~
In order to set email configuration for django you can use this code:
.. code-block:: python
EMAIL_CONFIG = env.email_url( 'EMAIL_URL', default='smtp://user:[email protected]:25')vars().update(EMAIL_CONFIG)
SQLite urls ~~~~~~~~~~~
SQLite connects to file based databases. The same URL format is used, omitting the hostname, and using the "file" portion as the filename of the database. This has the effect of four slashes being present for an absolute
file path:
sqlite:////full/path/to/your/database/file.sqlite.
Some settings such as Django's
ADMINSmake use of nested lists. You can use something like this to handle similar cases.
.. code-block:: python
# DJANGO_ADMINS=John:[email protected],Jane:[email protected] ADMINS = [x.split(':') for x in env.list('DJANGO_ADMINS')]or use more specific function
from email.utils import getaddresses
DJANGO_ADMINS=Full Name ,[email protected]
ADMINS = getaddresses([env('DJANGO_ADMINS')])
You can set a multiline variable value:
.. code-block:: python
# MULTILINE_TEXT=Hello\\nWorld >>> print env.str('MULTILINE_TEXT', multiline=True) Hello World
You can set a value prefixed by
$to use as a proxy to another variable value:
.. code-block:: python
# BAR=FOO # PROXY=$BAR >>> print env.str('PROXY') FOO
It is possible to have multiple env files and select one using environment variables.
.. code-block:: python
env = environ.Env() env.read_env(env.str('ENV_PATH', '.env'))
Now
ENV_PATH=other-env ./manage.py runserveruses
other-envwhile
./manage.py runserveruses
.env.
::
$ git clone [email protected]:joke2k/django-environ.git $ cd django-environ/ $ python setup.py test
Contributor Friendly_ tag for issues that should be ideal for people who are not very familiar with the codebase yet.
the repository_ on GitHub to start making your changes to the develop branch (or branch off of it).
Authors file_.
This project is licensed under the MIT License - see the
License file_ file for details
See the
Changelog file_ which format is inspired by
Keep a Changelog_.
Authors file_
12factor_
12factor-django_
Two Scoops of Django_
rconradharris_ /
envparse_
kennethreitz_ /
dj-database-url_
migonzalvar_ /
dj-email-url_
ghickman_ /
django-cache-url_
dstufft_ /
dj-search-url_
julianwachholz_ /
dj-config-url_
nickstenning_ /
honcho_
rconradharris_ /
envparse_
Distribute_
modern-package-template_
Thank you to all the people who have already contributed. |occontributorimage|
Thank you to all our backers! |ocbackerimage|
Support this project by becoming a sponsor. Your logo will show up here with a link to your website.
Became sponsor_.
|ocsponsor0| |ocsponsor1| |ocsponsor2|
.. _rconradharris: https://github.com/rconradharris .. _envparse: https://github.com/rconradharris/envparse
.. _jacobian: https://github.com/jacobian .. _dj-database-url: https://github.com/jacobian/dj-database-url
.. _migonzalvar: https://github.com/migonzalvar .. _dj-email-url: https://github.com/migonzalvar/dj-email-url
.. _ghickman: https://github.com/ghickman .. _django-cache-url: https://github.com/ghickman/django-cache-url
.. _julianwachholz: https://github.com/julianwachholz .. _dj-config-url: https://github.com/julianwachholz/dj-config-url
.. _dstufft: https://github.com/dstufft .. _dj-search-url: https://github.com/dstufft/dj-search-url
.. _nickstenning: https://github.com/nickstenning .. _honcho: https://github.com/nickstenning/honcho
.. _12factor: http://www.12factor.net/ .. _
Twelve-factor methodology: http://www.12factor.net/ .. _12factor-django: http://www.wellfireinteractive.com/blog/easier-12-factor-django/ .. _
Two Scoops of Django: http://twoscoopspress.org/
.. _Distribute: http://pypi.python.org/pypi/distribute .. _
modern-package-template: http://pypi.python.org/pypi/modern-package-template
.. _cookiecutter-django: https://github.com/pydanny/cookiecutter-django
.. |pypi| image:: https://img.shields.io/pypi/v/django-environ.svg?style=flat-square :target: https://pypi.python.org/pypi/django-environ :alt: Latest version released on PyPi
.. |coverage| image:: https://img.shields.io/coveralls/joke2k/django-environ/master.svg?style=flat-square :target: https://coveralls.io/r/joke2k/django-environ?branch=master :alt: Test coverage
.. |unix_build| image:: https://img.shields.io/travis/joke2k/django-environ/master.svg?style=flat-square&logo=travis :target: http://travis-ci.org/joke2k/django-environ :alt: Build status of the master branch on Mac/Linux
.. |windows_build| image:: https://img.shields.io/appveyor/ci/joke2k/django-environ.svg?style=flat-square&logo=windows :target: https://ci.appveyor.com/project/joke2k/django-environ :alt: Build status of the master branch on Windows
.. |contributors| image:: https://img.shields.io/github/contributors/joke2k/django-environ.svg?style=flat-square :target: https://github.com/joke2k/django-environ/graphs/contributors
.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square :target: https://raw.githubusercontent.com/joke2k/django-environ/master/LICENSE.txt :alt: Package license
.. |say_thanks| image:: https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg?style=flat-square :target: https://saythanks.io/to/joke2k :alt: Say Thanks!
.. |cover| image:: https://farm2.staticflickr.com/1745/4258003675135f76a92feh.jpg :alt: Photo by Singkham from Pexels
.. _
License file: https://github.com/joke2k/django-environ/blob/develop/LICENSE.txt .. _
Changelog file: https://github.com/joke2k/django-environ/blob/develop/CHANGELOG.rst .. _
Authors file: https://github.com/joke2k/django-environ/blob/develop/AUTHORS.rst .. _
Contributor Friendly: https://github.com/joke2k/django-environ/issues?direction=desc&labels=contributor-friendly&page=1&sort=updated&state=open .. _
the repository: https://github.com/joke2k/django-environ
.. |ocbackers| image:: https://opencollective.com/django-environ/backers/badge.svg :target: https://opencollective.com/django-environ :alt: Backers on Open Collective .. |ocsponsors| image:: https://opencollective.com/django-environ/sponsors/badge.svg :target: https://opencollective.com/django-environ :alt: Sponsors on Open Collective
.. |ocbackerimage| image:: https://opencollective.com/django-environ/backers.svg?width=890 :target: https://opencollective.com/django-environ :alt: Backers on Open Collective .. |occontributorimage| image:: https://opencollective.com/django-environ/contributors.svg?width=890&button=false :target: https://opencollective.com/django-environ :alt: Repo Contributors
.. _
Became sponsor: https://opencollective.com/django-environ#sponsor
.. |ocsponsor0| image:: https://opencollective.com/django-environ/sponsor/0/avatar.svg :target: https://opencollective.com/django-environ/sponsor/0/website :alt: Sponsor .. |ocsponsor1| image:: https://opencollective.com/django-environ/sponsor/1/avatar.svg :target: https://opencollective.com/django-environ/sponsor/1/website :alt: Sponsor .. |ocsponsor2| image:: https://opencollective.com/django-environ/sponsor/2/avatar.svg :target: https://opencollective.com/django-environ/sponsor/2/website :alt: Sponsor