Package: python-environ
Django-environdjango-environallows you to useTwelve-factor methodologyto configure your Django application with environment variables.importenvironenv=environ.Env(# set casting, default valueDEBUG=(bool,False))# reading .env fileenviron.Env.read_env()# False if not in os.environDEBUG=env('DEBUG')# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environSECRET_KEY=env('SECRET_KEY')# Parse database connection url strings like psql://user:pass@127.0.0.1:8458/dbDATABASES={# 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 thesimilar code, sans django-environ._ _                                              _
    | (_)                                            (_)
  __| |_  __ _ _ __   __ _  ___ ______ ___ _ ____   ___ _ __ ___  _ __
 / _` | |/ _` | '_ \ / _` |/ _ \______/ _ \ '_ \ \ / / | '__/ _ \| '_ \
| (_| | | (_| | | | | (_| | (_) |    |  __/ | | \ V /| | | | (_) | | | |
 \__,_| |\__,_|_| |_|\__, |\___/      \___|_| |_|\_/ |_|_|  \___/|_| |_|
     _/ |             __/ |
    |__/             |___/The idea of this package is to unify a lot of packages that make the same stuff:
Take a string fromos.environ, parse and cast it to some of useful python typed variables.
To do that and to use the12factorapproach, some connection strings are expressed as url,
so this package can parse it and return aurllib.parse.ParseResult.
These strings fromos.environare loaded from a.envfile and filled inos.environwithsetdefaultmethod,
to avoid to overwrite the real environ.
A similar approach is used inTwo Scoops of Djangobook and explained in12factor-djangoarticle.Using django-environ you can stop to make a lot of unversionedsettings_*.pyto configure your app.
Seecookiecutter-djangofor a concrete example on using with a django project.Feature SupportFast and easy multi environment for deployFillos.environwith .env file variablesVariables casting (seesupported_typesbelow)Url variables exploded to django specific package settingsDjango-environ officially supports Django 1.8 ~ 2.0.Installation$pipinstalldjango-environNOTE: No need to add it to INSTALLED_APPS.Then create a.envfile:DEBUG=onSECRET_KEY=your-secret-keyDATABASE_URL=psql://user:un-githubbedpassword@127.0.0.1:8458/databaseSQLITE_URL=sqlite:///my-local-sqlite.dbCACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213REDIS_URL=rediscache://127.0.0.1:6379/1?client_class=django_redis.client.DefaultClient&password=ungithubbed-secretAnd use it withsettings.pyabove.
Don’t forget to add.envin your.gitignore(tip: add.env.examplewith a template of your variables).DocumentationDocumentation is available atRTFD.Supported typesstrboolintfloatjsonlist (FOO=a,b,c)tuple (FOO=(a,b,c))dict (BAR=key=val,foo=bar) #environ.Env(BAR=(dict, {}))dict (BAR=key=val;foo=1.1;baz=True) #environ.Env(BAR=(dict(value=unicode, cast=dict(foo=float,baz=bool)), {}))urlpath (environ.Path)db_urlPostgreSQL: postgres://, pgsql://, psql:// or postgresql://PostGIS: postgis://MySQL: mysql:// or mysql2://MySQL for GeoDjango: mysqlgis://Mysql Connector Python from Oracle: mysql-connector://SQLITE: sqlite://SQLITE with SPATIALITE for GeoDjango: spatialite://Oracle: oracle://MSSQL: mssql://PyODBC: pyodbc://Redshift: redshift://LDAP:ldap://cache_urlDatabase: dbcache://Dummy: dummycache://File: filecache://Memory: locmemcache://Memcached: memcache://Python memory: pymemcache://Redis: rediscache://, redis://, or rediss://search_urlElasticSearch: elasticsearch://Solr: solr://Whoosh: whoosh://Xapian: xapian://Simple cache: simple://email_urlSMTP: smtp://SMTP+SSL: smtp+ssl://SMTP+TLS: smtp+tls://Console mail: consolemail://File mail: filemail://LocMem mail: memorymail://Dummy mail: dummymail://TipsUsing unsafe characters in URLsIn order to use unsafe characters you have to encode withurllib.parse.encodebefore you set into.envfile.DATABASE_URL=mysql://user:%23password@127.0.0.1:3306/dbnameSeehttps://perishablepress.com/stop-using-unsafe-characters-in-urls/for reference.Smart Castingdjango-environ has a “Smart-casting” enabled by default, if you don’t provide acasttype, it will be detected fromdefaulttype.
This could raise side effects (see#192).
To disable it useenv.smart_caset = False.
New major release will disable it as default.Multiple redis cache locationsFor redis cache,multiple master/slave or shard locationscan be configured as follows:CACHE_URL='rediscache://master:6379,slave1:6379,slave2:6379/1'Email settingsIn order to set email configuration for django you can use this code:EMAIL_CONFIG=env.email_url('EMAIL_URL',default='smtp://user:password@localhost:25')vars().update(EMAIL_CONFIG)SQLite urlsSQLite 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 absolutefile path:sqlite:////full/path/to/your/database/file.sqlite.Nested listsSome settings such as Django’sADMINSmake use of nested lists. You can use something like this to handle similar cases.# DJANGO_ADMINS=John:john@admin.com,Jane:jane@admin.comADMINS=[x.split(':')forxinenv.list('DJANGO_ADMINS')]# or use more specific functionfromemail.utilsimportgetaddresses# DJANGO_ADMINS=Full Name <email-with-name@example.com>,anotheremailwithoutname@example.comADMINS=getaddresses([env('DJANGO_ADMINS')])Multiline valueYou can set a multiline variable value:# MULTILINE_TEXT=Hello\\nWorld>>>printenv.str('MULTILINE_TEXT',multiline=True)HelloWorldProxy valueYou can set a value prefixed by$to use as a proxy to another variable value:# BAR=FOO# PROXY=$BAR>>>printenv.str('PROXY')FOOMultiple env filesIt is possible to have multiple env files and select one using environment variables.env=environ.Env()env.read_env(env.str('ENV_PATH','.env'))NowENV_PATH=other-env./manage.py runserverusesother-envwhile./manage.py runserveruses.env.Tests$ git clone git@github.com:joke2k/django-environ.git
$ cd django-environ/
$ python setup.py testHow to ContributeCheck for open issues or open a fresh issue to start a discussion around a feature idea or a bug. There is aContributor Friendlytag for issues that should be ideal for people who are not very familiar with the codebase yet.Forkthe repositoryon GitHub to start making your changes to thedevelopbranch (or branch off of it).Write a test which shows that the bug was fixed or that the feature works as expected.Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself toAuthors file.LicenseThis project is licensed under the MIT License - see theLicense filefile for detailsChangelogSee theChangelog filewhich format isinspiredbyKeep a Changelog.CreditsSeeAuthors file12factor12factor-djangoTwo Scoops of Djangorconradharris/envparsemigonzalvar/dj-email-urlghickman/django-cache-urldstufft/dj-search-urljulianwachholz/dj-config-urlnickstenning/honchorconradharris/envparseDistributemodern-package-templateContributorsThank you to all the people who have already contributed.BackersThank you to all our backers!SponsorsSupport this project by becoming a sponsor. Your logo will show up here with a link to your website.Became sponsor.