Package: django-envsettings
One-stop shop for configuring 12-factor Django appsSimple API for getting settings from environment variables.Supports wide variety of email, cache and database backends.Easily customisable and extensible.One line auto-config for many Heroku add-ons.Basic SettingsIn your Django project’ssettings.py:importenvsettingsSECRET_KEY=envsettings.get('DJANGO_SECRET_KEY','development_key_not_a_secret')# Accepts the strings "True" and "False"DEBUG=envsettings.get_bool('DJANGO_DEBUG',default=True)FILE_UPLOAD_MAX_MEMORY_SIZE=envsettings.get_int('MAX_UPLOAD_SIZE',default=2621440)Email SettingsBecause of the way Django’s email settings work, this requires a bit of a hack withlocals():importenvsettingslocals().update(envsettings.email.get('MAIL_URL',default='file:///dev/stdout'))This setsEMAIL_BACKENDand whatever other values are needed to
configure the selected backend.Example URLsStandard SMTP backend:# SMTP without TLSsmtp://username:password@host.example.com:25# SMTP with TLSsmtps://username:password@host.example.com:587Special Django backends for use in development:# Console backendfile:///dev/stdout# Dummy packendfile:///dev/null# File-based backendfile:///path/to/output/dirProprietary backends (each requires the appropriate package installed):# Requires `django-mailgun`mailgun://api:api_key@my-sending-domain.com# Requires `sendgrid-django`sendgrid://username:password@sendgrid.com# Requires `djrill`mandrill://:api_key@mandrillapp.commandrill://subaccount_name:api_key@mandrillapp.com# Requires `django-ses-backend`ses://access_key_id:access_key@us-east-1ses://access_key_id:access_key@email.eu-west-1.amazonaws.com# Requires `django-postmark`postmark://api:api_key@postmarkapp.comHeroku Auto-ConfigPassauto_config=Truelike so:locals().update(envsettings.email.get(default='file:///dev/stdout',auto_config=True))This will automatically detect and configure any of the following Heroku email add-ons:Mailgun,Sendgrid,Mandrill,Postmark.So, for instance, you can configure your app to send email via Mailgun simply by running:herokuaddons:addmailgun:starterBy default it will use each provider’s SMTP endpoint, however if it detects that
the appropriate backend is installed (see list above) it will configure Django to
use the HTTP endpoint which will be faster.Cache SettingsimportenvsettingsCACHES={'default':envsettings.cache.get('CACHE_URL','locmem://')}Example URLsDjango backends for use in development:# Local memorylocmem://# Local memory with prefixlocmem://some-prefix# File basedfile:///path/to/cache/directory# Dummy cachefile:///dev/nullRedis (requiresdjango-redispackage):# Basic Redis configurationredis://example.com:6379# With passwordredis://:secret@example.com:6379# Specifying database numberredis://example.com:6379/3# Using UNIX socketredis:///path/to/socket# Using UNIX socket with password and database numberredis://:secret@/path/to/socket:3To use Memcached you need one of the following packages installed:django_pylibmc,django_bmemcached,pylibmc,mecachedOnlydjango_pylibmcanddjango_bmemcachdsupport authentication and the memcached
binary protocol, so if you want to use either of these featues you’ll need one of those
packages.# Basic Memcached configurationmemcached://example.com:11211# Multiple serversmemcached://example.com:11211,another.com:11211,onemore.com:11211# With authenticationmemcached://username:password@example.com# Using the binary protocolmemcached-binary://example.com:11211Heroku Auto-ConfigPassauto_config=Truelike so:CACHES={'default':envsettings.cache.get(default='locmen://',auto_config=True)}This will automatically detect and configure any of the following Heroku cache add-ons:Memcachier,MemcachedCloud,RedisToGo,RedisCloud,OpenRedis,RedisGreen.Customising & ExtendingDjango EnvSettings is designed to be easily extensible by subclassing one of the existing
settings providers:CacheSettings,EmailSettings, orDatabaseSettings.Changing default configurationObviously you can modify the configuration dictionary after it’s returned fromenvsettings.
However you can also set default values for each backend, while letting the environment determine
which backend to use. For example:envsettings.database.CONFIG['postgres']['OPTIONS']={'isolation_level':psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE}Supporting new backendsTo add a new backend, subclass the appropriate settings class.
You will then need to add a key to theCONFIGdictionary which maps
the URL scheme you want to use for your backend to the default config
for that backend. You will also need to add a method namedhandle_<URL_SCHEME>_urlwhich will be passed the output fromurlparseand the
default config. The method should use the values from the parsed URL to update the
config appropriately.For example:importenvsettingsclassCacheSettings(envsettings.CacheSettings):CONFIG=dict(envsettings.CacheSettings.CONFIG,**{'my-proto':{'BACKEND':'my_cache_backend.MyCacheBackend'}})defhandle_my_proto_url(self,parsed_url,config):config['HOST']=parsed_url.hostnameor'localhost'config['PORT']=parsed_url.portor9000config['USERNAME']=parsed_url.usernameconfig['PASSWORD']=parsed_url.passwordreturnconfigcachesettings=CacheSettings()CACHES={'default':cachesettings.get('CACHE_URL')}Supporting new auto configuration optionsTo add a new auto-configuration provider, subclass the appropriate settings class and add a method
namedauto_config_<PROVIDER_NAME>. This will be passed a dictionary of environment
variables and should return either an appropriate configuration URL, or None.The auto config methods are tried in lexical order, so if you want to force a method
to be tried first you could call itauto_config_00_my_provider, or something like
that.Here’s an example:importenvsettingsclassCacheSettings(envsettings.CacheSettings):defauto_config_my_redis(self,env):try:host=env['MY_REDIS_HOST']password=env['MY_REDIS_PASSWORD']exceptKeyError:returnNoneelse:return'redis://:{password}@{host}'.format(host=host,password=password)cachesettings=CacheSettings()CACHES={'default':cachesettings.get('CACHE_URL',auto_config=True)}CompatibilityTested on Python2.7,3.3,3.4andPyPy,
with Django versions1.4—1.7Issues & ContributingRaise an issue on theGitHub projector
feel free to nudge@_EvansDon Twitter.LicenseMIT Licensed