Convert Figma logo to code with AI

joke2k logodjango-environ

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

2,995
318
2,995
87

Top Related Projects

Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards and optional settings files.

Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.

Strict separation of config from code.

A helper for organizing Django project settings by relying on well established programming patterns.

Dynamic Django settings.

:honey_pot: A fake Django admin login screen page.

Quick Overview

Django-environ is a Python package that allows you to configure your Django application using environment variables. It simplifies the process of managing different configurations for development, testing, and production environments by utilizing a .env file to store sensitive information and configuration settings.

Pros

  • Enhances security by keeping sensitive information out of version control
  • Simplifies configuration management across different environments
  • Integrates seamlessly with Django settings
  • Supports various data types and casting for environment variables

Cons

  • Requires additional setup and management of .env files
  • May introduce complexity for smaller projects
  • Potential for misconfiguration if .env files are not properly managed
  • Limited to Django projects, not suitable for other Python frameworks

Code Examples

  1. Basic usage in Django settings:
import environ

env = environ.Env()
environ.Env.read_env()

SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool('DEBUG', default=False)
DATABASES = {
    'default': env.db(),
}
  1. Casting environment variables:
import environ

env = environ.Env(
    DEBUG=(bool, False),
    TIMEOUT=(int, 60),
    ALLOWED_HOSTS=(list, [])
)

DEBUG = env('DEBUG')
TIMEOUT = env('TIMEOUT')
ALLOWED_HOSTS = env('ALLOWED_HOSTS')
  1. Using URL parsing:
import environ

env = environ.Env()

REDIS_URL = env.url('REDIS_URL')
print(REDIS_URL.hostname)
print(REDIS_URL.port)
print(REDIS_URL.password)

Getting Started

  1. Install django-environ:

    pip install django-environ
    
  2. Create a .env file in your project root:

    DEBUG=True
    SECRET_KEY=your-secret-key
    DATABASE_URL=postgres://user:password@localhost/dbname
    
  3. In your Django settings file:

    import environ
    
    env = environ.Env()
    environ.Env.read_env()
    
    DEBUG = env.bool('DEBUG', default=False)
    SECRET_KEY = env('SECRET_KEY')
    DATABASES = {
        'default': env.db(),
    }
    
  4. Use environment variables in your Django settings as needed.

Competitor Comparisons

Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards and optional settings files.

Pros of django-split-settings

  • Allows for more granular organization of settings files
  • Provides better separation of concerns for different environments
  • Easier to manage complex configurations across multiple files

Cons of django-split-settings

  • Requires more initial setup and file management
  • May introduce complexity for smaller projects
  • Less integrated with environment variables out of the box

Code Comparison

django-split-settings:

from split_settings.tools import optional, include

include(
    'base.py',
    'local.py',
    optional('production.py')
)

django-environ:

import environ

env = environ.Env()
environ.Env.read_env()

DEBUG = env.bool('DEBUG', default=False)
SECRET_KEY = env('SECRET_KEY')

django-split-settings focuses on splitting configuration files, while django-environ emphasizes environment variable management. django-split-settings offers more flexibility in organizing settings, but django-environ provides a more straightforward approach to handling environment-specific variables. The choice between the two depends on project complexity and team preferences for configuration management.

Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.

Pros of python-dotenv

  • Language-agnostic: Can be used with any Python project, not limited to Django
  • Simpler setup: Doesn't require Django settings configuration
  • Supports multiple .env file locations and names

Cons of python-dotenv

  • Less feature-rich: Lacks some advanced features like type casting and URL parsing
  • No built-in Django integration: Requires manual setup for Django projects
  • Limited variable expansion: Doesn't support referencing other environment variables

Code Comparison

python-dotenv:

from dotenv import load_dotenv
load_dotenv()
import os
database_url = os.getenv("DATABASE_URL")

django-environ:

import environ
env = environ.Env()
environ.Env.read_env()
database_url = env.db()

Both libraries aim to simplify environment variable management, but django-environ is more tightly integrated with Django and offers additional features. python-dotenv is more versatile and can be used in various Python projects, while django-environ is tailored specifically for Django applications. The choice between the two depends on the project requirements and the developer's preference for simplicity versus advanced features.

Strict separation of config from code.

Pros of python-decouple

  • Simpler and more lightweight, focusing solely on configuration management
  • Can be used in non-Django projects more easily
  • Provides a clear separation between settings and code

Cons of python-decouple

  • Less feature-rich compared to django-environ
  • Doesn't provide as many parsing options for different data types
  • May require additional setup for complex configurations

Code Comparison

python-decouple:

from decouple import config

DEBUG = config('DEBUG', default=False, cast=bool)
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)

django-environ:

import environ

env = environ.Env()
DEBUG = env.bool('DEBUG', default=False)
EMAIL_HOST = env('EMAIL_HOST', default='localhost')
EMAIL_PORT = env.int('EMAIL_PORT', default=25)

Both libraries aim to simplify configuration management and environment variable handling in Python projects. python-decouple is more focused and lightweight, making it suitable for various Python projects, while django-environ offers more features and is tailored for Django applications. The choice between the two depends on the specific project requirements and complexity of the configuration needs.

A helper for organizing Django project settings by relying on well established programming patterns.

Pros of django-configurations

  • More flexible and powerful configuration system
  • Supports class-based configurations with inheritance
  • Allows for complex configuration scenarios and environment-specific settings

Cons of django-configurations

  • Steeper learning curve due to its more complex nature
  • Requires additional setup and configuration compared to django-environ
  • May be overkill for simpler projects or those with straightforward configuration needs

Code Comparison

django-configurations:

from configurations import Configuration

class Dev(Configuration):
    DEBUG = True
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'dev.db',
        }
    }

django-environ:

import environ

env = environ.Env()
DEBUG = env.bool('DEBUG', default=True)
DATABASES = {
    'default': env.db('DATABASE_URL', default='sqlite:///dev.db')
}

django-configurations offers a more object-oriented approach to configuration, allowing for inheritance and complex setups. django-environ, on the other hand, provides a simpler, environment variable-based configuration that's easier to set up and use for most projects. The choice between the two depends on the project's complexity and specific configuration needs.

Dynamic Django settings.

Pros of django-constance

  • Provides a user-friendly admin interface for managing dynamic settings
  • Supports different backends (database, redis) for storing configuration
  • Allows for real-time changes without server restart

Cons of django-constance

  • Limited to key-value pairs, less flexible than environment variables
  • Requires additional setup and configuration compared to django-environ
  • May introduce complexity for simple projects

Code Comparison

django-constance:

from constance import config

DEBUG = config.DEBUG
EMAIL_HOST = config.EMAIL_HOST

django-environ:

import environ

env = environ.Env()
DEBUG = env('DEBUG')
EMAIL_HOST = env('EMAIL_HOST')

Summary

django-constance is ideal for projects requiring dynamic settings management through an admin interface, with support for different backends. It's particularly useful for applications where non-technical users need to modify settings.

django-environ, on the other hand, focuses on managing configuration through environment variables, providing a simpler setup for projects that don't require real-time setting changes or an admin interface for configuration management.

The choice between the two depends on the specific needs of your project, such as the requirement for dynamic settings, admin interface, and the complexity of your configuration management.

:honey_pot: A fake Django admin login screen page.

Pros of django-admin-honeypot

  • Focused security feature for protecting Django admin interface
  • Logs attempted unauthorized access, providing valuable security insights
  • Simple to set up and integrate into existing Django projects

Cons of django-admin-honeypot

  • Limited in scope compared to django-environ's broader configuration management
  • May require additional setup for email notifications or integrations
  • Less actively maintained, with fewer recent updates

Code Comparison

django-admin-honeypot:

MIDDLEWARE = [
    ...
    'admin_honeypot.middleware.AdminHoneypotMiddleware',
    ...
]

ADMIN_HONEYPOT_EMAIL_ADMINS = True

django-environ:

import environ

env = environ.Env()
environ.Env.read_env()

DEBUG = env.bool('DEBUG', default=False)
SECRET_KEY = env('SECRET_KEY')

Summary

While django-admin-honeypot provides a specific security feature for Django admin interfaces, django-environ offers a more comprehensive solution for managing environment variables and configuration settings. django-admin-honeypot is ideal for projects seeking enhanced admin security, whereas django-environ is better suited for projects requiring flexible configuration management across different environments.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. raw:: html

<h1 align="center">django-environ</h1>
<p align="center">
    <a href="https://pypi.python.org/pypi/django-environ">
        <img src="https://img.shields.io/pypi/v/django-environ.svg" alt="Latest version released on PyPi" />
    </a>
    <a href="https://coveralls.io/github/joke2k/django-environ">
        <img src="https://coveralls.io/repos/github/joke2k/django-environ/badge.svg" alt="Coverage Status" />
    </a>
    <a href="https://github.com/joke2k/django-environ/actions?workflow=CI">
        <img src="https://github.com/joke2k/django-environ/workflows/CI/badge.svg?branch=develop" alt="CI Status" />
    </a>
    <a href="https://opencollective.com/django-environ">
        <img src="https://opencollective.com/django-environ/sponsors/badge.svg" alt="Sponsors on Open Collective" />
    </a>
    <a href="https://opencollective.com/django-environ">
        <img src="https://opencollective.com/django-environ/backers/badge.svg" alt="Backers on Open Collective" />
    </a>
    <a href="https://saythanks.io/to/joke2k">
        <img src="https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg" alt="Say Thanks!" />
    </a>
    <a href="https://raw.githubusercontent.com/joke2k/django-environ/main/LICENSE.txt">
        <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="Package license" />
    </a>
</p>

.. -teaser-begin-

django-environ is the Python package that allows you to use Twelve-factor methodology <https://www.12factor.net/>_ to configure your Django application with environment variables.

.. -teaser-end-

For that, it gives you an easy way to configure Django application using environment variables obtained from an environment file and provided by the OS:

.. -code-begin-

.. code-block:: python

import environ import os

env = environ.Env( # set casting, default value DEBUG=(bool, False) )

Set the project base directory

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))

Take environment variables from .env file

environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

False if not in os.environ because of casting above

DEBUG = env('DEBUG')

Raises Django's ImproperlyConfigured

exception if SECRET_KEY not in os.environ

SECRET_KEY = env('SECRET_KEY')

Parse database connection url strings

like psql://user:pass@127.0.0.1:8458/db

DATABASES = { # read os.environ['DATABASE_URL'] and raises # ImproperlyConfigured exception if not found # # The db() method is an alias for db_url(). 'default': env.db(),

   # read os.environ['SQLITE_URL']
   'extra': env.db_url(
       'SQLITE_URL',
       default='sqlite:////tmp/my-tmp-sqlite.db'
   )

}

CACHES = { # Read os.environ['CACHE_URL'] and raises # ImproperlyConfigured exception if not found. # # The cache() method is an alias for cache_url(). 'default': env.cache(),

   # read os.environ['REDIS_URL']
   'redis': env.cache_url('REDIS_URL')

}

.. -overview-

The idea of this package is to unify a lot of packages that make the same stuff: Take a string from os.environ, parse and cast it to some of useful python typed variables. To do that and to use the 12factor <https://www.12factor.net/>_ approach, some connection strings are expressed as url, so this package can parse it and return a urllib.parse.ParseResult. These strings from os.environ are loaded from a .env file and filled in os.environ with setdefault method, to avoid to overwrite the real environ. A similar approach is used in Two Scoops of Django <https://www.feldroy.com/books/two-scoops-of-django-3-x>_ book and explained in 12factor-django <https://wellfire.co/learn/easier-12-factor-django>_ article.

Using django-environ you can stop to make a lot of unversioned settings_*.py to configure your app. See cookiecutter-django <https://github.com/cookiecutter/cookiecutter-django>_ for a concrete example on using with a django project.

Feature Support

  • Fast and easy multi environment for deploy
  • Fill os.environ with .env file variables
  • Variables casting
  • Url variables exploded to django specific package settings
  • Optional support for Docker-style file based config variables (use environ.FileAwareEnv instead of environ.Env)

.. -project-information-

Project Information

django-environ is released under the MIT / X11 License <https://choosealicense.com/licenses/mit/>__, its documentation lives at Read the Docs <https://django-environ.readthedocs.io/en/latest/>, the code on GitHub <https://github.com/joke2k/django-environ>, and the latest release on PyPI <https://pypi.org/project/django-environ/>_.

It’s rigorously tested on Python 3.6+, and officially supports Django 1.11, 2.2, 3.0, 3.1, 3.2, 4.0, 4.1 and 4.2.

If you'd like to contribute to django-environ you're most welcome!

.. -support-

Support

Should you have any question, any remark, or if you find a bug, or if there is something you can't do with the django-environ, please open an issue <https://github.com/joke2k/django-environ>_.