Code Monkey home page Code Monkey logo

django-environ's Introduction

Django-environ

Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

https://travis-ci.org/joke2k/django-environ.svg?branch=master https://ci.appveyor.com/api/projects/status/o6p7l2o0xoatqcin https://coveralls.io/repos/joke2k/django-environ/badge.png?branch=master https://badge.fury.io/py/django-environ.png https://pypip.in/d/django-environ/badge.png

This module is a merge of:

and inspired by:

This is your settings.py file before you have installed django-environ

import os
SITE_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'database',
        'USER': 'user',
        'PASSWORD': 'githubbedpassword',
        'HOST': '127.0.0.1',
        'PORT': '8458',
    }
    'extra': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(SITE_ROOT, 'database.sqlite')
    }
}

MEDIA_ROOT = os.path.join(SITE_ROOT, 'assets')
MEDIA_URL = 'media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = 'static/'

SECRET_KEY = '...im incredibly still here...'

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': [
            '127.0.0.1:11211', '127.0.0.1:11212', '127.0.0.1:11213',
        ]
    },
    'redis': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': '127.0.0.1:6379:1',
        'OPTIONS': {
            'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
            'PASSWORD': 'redis-githubbed-password',
        }
    }
}

After:

import environ
root = environ.Path(__file__) - 3 # three folder back (/a/b/c/ - 3 = /)
env = environ.Env(DEBUG=(bool, False),) # set default values and casting
environ.Env.read_env() # reading .env file

SITE_ROOT = root()

DEBUG = env('DEBUG') # False if not in os.environ
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': env.db(), # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
    'extra': env.db('SQLITE_URL', default='sqlite:////tmp/my-tmp-sqlite.db')
}

public_root = root.path('public/')

MEDIA_ROOT = public_root('media')
MEDIA_URL = 'media/'
STATIC_ROOT = public_root('static')
STATIC_URL = 'static/'

SECRET_KEY = env('SECRET_KEY') # Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ

CACHES = {
    'default': env.cache(),
    'redis': env.cache('REDIS_URL')
}

You can also pass read_env() an explicit path to the .env file. Create a .env file:

DEBUG=on
# DJANGO_SETTINGS_MODULE=myapp.settings.dev
SECRET_KEY=your-secret-key
DATABASE_URL=psql://urser:[email protected]:8458/database
# SQLITE_URL=sqlite:///my-local-sqlite.db
CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213
REDIS_URL=rediscache://127.0.0.1:6379:1?client_class=redis_cache.client.DefaultClient&password=redis-un-githubbed-password

How to install

$ pip install django-environ

How to use

There are only classes, Env and Path

>>> import environ
>>> env = environ.Env(
        DEBUG=(bool, False),
    )
>>> env('DEBUG')
False
>>> env('DEBUG', default=True)
True

>>> open('.myenv', 'a').write('DEBUG=on')
>>> environ.Env.read_env('.myenv') # or env.read_env('.myenv')
>>> env('DEBUG')
True

>>> open('.myenv', 'a').write('\nINT_VAR=1010')
>>> env.int('INT_VAR'), env.str('INT_VAR')
1010, '1010'

>>> open('.myenv', 'a').write('\nDATABASE_URL=sqlite:///my-local-sqlite.db')
>>> env.read_env('.myenv')
>>> env.db()
{'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'my-local-sqlite.db', 'HOST': '', 'USER': '', 'PASSWORD': '', 'PORT': ''}

>>> root = env.path('/home/myproject/')
>>> root('static')
'/home/myproject/static'

Supported Types

  • str
  • bool
  • int
  • float
  • json
  • list (FOO=a,b,c)
  • dict (BAR=key=val,foo=bar)
  • url
  • path (environ.Path)
  • db_url
    • PostgreSQL: postgres://, pgsql://, psql:// or postgresql://
    • PostGIS: postgis://
    • MySQL: mysql:// or mysql2://
    • MySQL for GeoDjango: mysqlgis://
    • SQLITE: sqlite://
    • SQLITE with SPATIALITE for GeoDjango: spatialite://
    • LDAP: ldap://
  • cache_url
    • Database: dbcache://
    • Dummy: dummycache://
    • File: filecache://
    • Memory: locmemcache://
    • Memcached: memcache://
    • Python memory: pymemcache://
    • Redis: rediscache://
  • search_url
    • ElasticSearch: elasticsearch://
    • Solr: solr://
    • Whoosh: whoosh://
    • Simple cache: simple://
  • email_url
    • SMTP: smtp://
    • SMTPS: smtps://
    • Console mail: consolemail://
    • File mail: filemail://
    • LocMem mail: memorymail://
    • Dummy mail: dummymail://

Tests

$ git clone [email protected]:joke2k/django-environ.git
$ cd django-environ/
$ python setup.py test

Changelog

=== 0.3.1 (2014-09-03)
  • Add LDAP url support for database (django-ldapdb)
  • Fix psql/pgsql url

=== 0.3 (2014-06-03) ===

  • Add cache url support
  • Add email url support
  • Add search url support
  • Rewriting README.rst

=== 0.2.1 (2013-04-19) ===

  • environ/environ.py: Env.__call__ now uses Env.get_value instance method

=== 0.2 (2013-04-16) ===

  • environ/environ.py, environ/test.py, environ/test_env.txt: add advanced float parsing (comma and dot symbols to separate thousands and decimals)
  • README.rst, docs/index.rst: fix TYPO in documentation

=== 0.1 (2013-04-02) ===

  • initial release

Credits

django-environ's People

Contributors

cmheisel avatar jamesdoherty avatar joke2k avatar karabijavad avatar mcilvena avatar rockingrolli avatar theskumar avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.