Fork me on GitHub

Python Configurations Done Right

If you're building web applications then I hope that you're following the Twelve-Factor App approach. If so you will be storing your config in the environment and for most of you that means in environment variables.

This approach has a few benefits over storing them in yaml, ini, json, etc. Firstly, it stops you from commiting sensitive information into version control - which it kind of feels weird even saying you should be using if you're not. Secondly, it allows your configuration to vary substantially across deployments - something it will inevitably have the tendency to do.

Now if you're following this approach then the question inevitably arises as to how you're going to execute the app with a given configuration when you run it from the command-line. The following is a simple solution invented with some help from my colleagues at (EDIT: Jon pointed out to me we were doing something similiar at SHIFT) - just write a simple shell script for every environment you deploy to like so:

For those who don't know $* is simply the ARGLIST - the list of arguments passed into the application. The usage will make more sense once you see it in action below.

Now we just need to hook our application into a simple system for reading these environment variables. This would look something like the following:

Finally, we can grab environment variables and begin using them in our application.

Then when it comes time to run your application simply prepend the shell script.