Project Analyst at NIC.br, M.Sc. in Computer Science at IME-USP, Computer Engineer graduated at UFSCar
89 stories
·
8 followers

June 28, 2014

1 Share

Only 3 days left to join the new kickstarter!

Read the whole story
ayharano
3746 days ago
reply
São Caetano do Sul, SP, Brasil
Share this story
Delete

Own It – DORK TOWER 21.04.14

2 Shares

Super Own It Fun Hour

Read the whole story
ayharano
3817 days ago
reply
São Caetano do Sul, SP, Brasil
luizirber
3817 days ago
reply
Davis, CA
Share this story
Delete

The Problem With Being Clever Online – DORK TOWER 10.03.14

1 Share

Super Witty Very Very Witty Fun Hour

Read the whole story
ayharano
3862 days ago
reply
São Caetano do Sul, SP, Brasil
Share this story
Delete

Python Decouple 2.2: Strict separation of settings from code

1 Share

Decouple helps you to organize your settings so that you can change parameters without having to redeploy your app.

It also makes easy for you to:

  1. store parameters on ini or .env files;
  2. define comprehensive default values;
  3. properly convert values to the correct data type;
  4. have only one configuration module to rule all your instances.

It was originally designed for Django, but became an independent generic tool for separating settings from code.

Test Status
Code Helth
Latest PyPI version
Number of PyPI downloads

Why?

Web framework’s settings stores many different kinds of parameters:

  • Locale and i18n;
  • Middlewares and Installed Apps;
  • Resource handles to the database, Memcached, and other backing services;
  • Credentials to external services such as Amazon S3 or Twitter;
  • Per-deploy values such as the canonical hostname for the instance.

The first 2 are project settings the last 3 are instance settings.

You should be able to change instance settings without redeploying your app.

Why not just use environment variables?

Envvars works, but since os.environ only returns strings, it’s tricky.

Let’s say you have an envvar DEBUG=False. If you run:

if os.environ['DEBUG']:
    print True
else:
    print False

It will print True, because os.environ['DEBUG'] returns the string "False". Since it’s a non-empty string, it will be evaluated as True.

Decouple provides a solution that doesn’t look like a workaround: config('DEBUG', cast=bool).

Install

pip install python-decouple

Usage

On your settings.py.

  1. Import the config object:
    from decouple import config
  2. Retrieve the configuration parameters:
    SECRET_KEY = config('SECRET_KEY')
    DEBUG = config('DEBUG', default=False, cast=bool)
    EMAIL_HOST = config('EMAIL_HOST', default='localhost')
    EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)

Where the settings data are stored?

Decouple supports both .ini and .env files.

Ini file

Simply create a settings.ini next to your configuration module in the form:

[settings]
DEBUG=True
TEMPLATE_DEBUG=%(DEBUG)s
SECRET_KEY=ARANDOMSECRETKEY
DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase
PERCENTILE=90%%

Note: Since ConfigParser supports string interpolation, to represent the character % you need to escape it as %%.

Env file

Simply create a .env text file on your repository’s root directory in the form:

DEBUG=True
TEMPLATE_DEBUG=True
SECRET_KEY=ARANDOMSECRETKEY
DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase
PERCENTILE=90%

Example: How do I use it with Django?

Given that I have a .env file at my repository root directory, here is a snippet of my settings.py.

I also recommend using unipath and dj-datatabase-url.

# coding: utf-8
from decouple import config
from unipath import Path
from dj_database_url import parse as db_url
 
BASE_DIR = Path(__file__).parent
 
DEBUG = config('DEBUG', default=False, cast=bool)
TEMPLATE_DEBUG = DEBUG
 
DATABASES = {
    'default': config(
        'DATABASE_URL',
        default='sqlite:///' + BASE_DIR.child('db.sqlite3'),
        cast=db_url
    )
}
 
TIME_ZONE = 'America/Sao_Paulo'
USE_L10N = True
USE_TZ = True
 
SECRET_KEY = config('SECRET_KEY')
 
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='')
EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')
EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=False, cast=bool)
 
# ...

Atention with undefined parameters

On the above example, all configuration parameters except SECRET_KEY = config('SECRET_KEY') have a default value to fallback if it does not exist on the .env file.

If SECRET_KEY is not present on the .env, decouple will raise an UndefinedValueError.

This fail fast policy helps you avoid chasing misbehaviors when you eventually forget a parameter.

How it works?

Decouple is made of 5 classes:

  • Config

    Coordinates all the configuration retrieval.

  • RepositoryIni

    Can read values from ini files.

  • RepositoryEnv

    Can read .env files and when a parameter does not exist there,
    it tries to find it on os.environ.

    This process does not change nor add any environment variables.

  • RepositoryShell

    Can only read values from os.environ.

  • AutoConfig

    Detects which configuration repository you’re using.

    It recursively searches up your configuration module path looking for a
    settings.ini or a .env file.

The config object is an instance of AutoConfig to improve decouple‘s usage.

License

The MIT License (MIT)

Copyright (c) 2013 Henrique Bastos <henrique at bastos dot net>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Read the whole story
ayharano
3874 days ago
reply
São Caetano do Sul, SP, Brasil
Share this story
Delete

The Farmer's Riddle

3 Shares





Read the whole story
ayharano
3906 days ago
reply
São Caetano do Sul, SP, Brasil
luizirber
3907 days ago
reply
Davis, CA
Share this story
Delete

subfield

1 Comment and 13 Shares
nontrivial_subfield
Read the whole story
ayharano
3977 days ago
reply
São Caetano do Sul, SP, Brasil
Share this story
Delete
1 public comment
Michdevilish
3978 days ago
reply
Etc!
Canada
gmuslera
3977 days ago
It look so much like http://xkcd.com/435/
Next Page of Stories