Skip to main content

Accessing environment variables with a magic module.

Project description

Accessing environment variables with a magic module.

>>> import os
>>> from envcfg.raw.python import CONFIGURE_OPTS
'--enable-shared --enable-universalsdk=/ --with-universal-archs=intel'

It works with many frameworks such as Django and Flask. Then you can store your config in the environment variables instead of framework-specific config files. It is recommended by 12-Factor.


$ pip install python-envcfg

Supported Formats

  • import as config: Import each FOO_* environment variable as string.
  • import as config: Import each FOO_* environment variable as JSON body.
  • import as config: Try to import each FOO_* environment variable as JSON body, if fail then import it as string.

There is an example table:

Environment Variable Python Import Statement Python Variable Value
FOO_NAME=foo 'foo'
FOO_NAME="foo" '"foo"'
FOO_NUM1=42 '42'
FOO_NUM1="42" '"42"'
FOO_NAME=foo ImportError
FOO_NAME="foo" 'foo'
FOO_NUM1=42 42
FOO_NUM1="42" '42'
FOO_NAME=foo 'foo'
FOO_NAME="foo" 'foo'
FOO_NUM1=42 42
FOO_NUM1="42" '42'


Uses with Flask

  1. Defines environment variables with a prefix:

    $ cat .env  # should not checked into VCS
    # values are valid JSON expressions
  2. Creates Flask app and loads config from python-envcfg:

    $ cat
    app = Flask(__name__)
    app.config.from_object('envcfg.json.myapp')  # MYAPP_ -> .myapp
  3. Enters your app with those environment variables:

    $ env $(cat .env | xargs) python

Uses with Django

  1. Creates a django project and moves all sensitive config items into the environment variables:

    $ cat djapp/  # codebase-scope config
    $ cat .env  # environment-scope config, should not checked into VCS
    # values are valid JSON expressions
  2. Adds importing statements in the end of module:

    $ tail -n 2 djapp/
    # importing all config items stored in the environment variables
    from envcfg.json.djapp import *  # noqa
  3. Runs your Django app with environment variables:

    $ env $(cat .env | xargs) python runserver

Uses with Tornado

  1. Defines environment variables with a prefix:

    $ cat .env
    export TORAPP_PORT='8888'
    export TORAPP_MYSQL_HOST='""'
    export TORAPP_MYSQL_DATABASE='"database"'
  2. Creates a Tornado project and loads config:

    $ cat torapp/
    from tornado.web import Application, RequestHandler
    from tornado.ioloop import IOLoop
    from tornado.options import define, options
    from tordb import Connection
    def options_from_object(*args, **kwargs):
        module = __import__(*args, **kwargs)
        for name, value in vars(module).items():
            name = name.lower()
            if name in options._options:
    class IndexHandler(RequestHandler):
        def initialize(self):
            self.db = Connection(options.mysql_host, options.mysql_database)
        def get(self):
            pass  # some database operations with ``self.db``
    application = Application([
        (r'/', IndexHandler),
    define('port', type=int)
    define('mysql_host', type=unicode)
    define('mysql_database', type=unicode)
    options_from_object('envcfg.json.torapp', fromlist=['torapp'])
    if __name__ == '__main__':
  3. Runs your Tornado app:

    $ env $(cat .env | xargs) python

Works on Projects

In development, we can work with per-project environments but no more typing source foo/bar.

I recommend to put your project-specified environment variables in {PROJECT_ROOT}/.env and mark the .env as ignored in your VCS. For example, you can write /.env in .gitignore if you are using Git, and put a .env.example as a copying template for new-cloned projects.

And then, you can use some utility such as honcho or autoenv to apply the .env automatically.

For honcho:

$ echo 'MYPROJECT_DEBUG=true' >> .env
$ echo 'web: python runserver' >> Procfile
$ honcho run python check-debug
$ honcho start web
Starting development server at

For autoenv:

$ echo 'MYPROJECT_DEBUG=true' >> myproject/.env
$ cd myproject
$ python check-debug
$ python runserver
Starting development server at


If you want to report bugs or request features, please create issues on GitHub Issues.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for python-envcfg, version 0.2.0
Filename, size File type Python version Upload date Hashes
Filename, size python_envcfg-0.2.0-py2.py3-none-any.whl (9.0 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size python-envcfg-0.2.0.tar.gz (5.4 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page