django-environ Documentation

repository·develop·Indexed 25 days ago

https://github.com/joke2k/django-environ

A Python package that enables Twelve-factor app configuration for Django applications using environment variables and .env files. It simplifies parsing complex connection strings for databases, caches, and email into Django-compatible settings. Key features include the Env and FileAwareEnv classes for reading and casting variables, support for Docker-style file-based secrets, and tools for managing environment-specific configurations.

Tokens
6.4K
Snippets
24
Records
46
Agent score
85%

What's inside django-environ

  1. Overwrite existing environment variables from .env files

    develop

    By default, existing environment variables in os.environ are not overwritten by values found in a .env file. To force the .env file values to take precedence, pass overwrite=True to the read_env method.

    env = environ.Env()
    env.read_env(BASE_DIR('.env'), overwrite=True)
  2. Overwrite existing environment variables

    develop

    By default, django-environ will not overwrite environment variables that are already set in your system's os.environ. This is intended to allow the deployment environment to take precedence over the .env file.

    To force django-environ to overwrite existing environment variables with values from your .env file, pass overwrite=True to the read_env() method.

  3. Submit a pull request

    develop

    To have your changes considered for inclusion in django-environ, follow this workflow:

    1. Discuss first: Check for open issues or open a new issue to discuss your feature idea or bug fix.
    2. Fork and Branch: Fork the repository and create a topic branch from the develop branch.
    3. Develop and Test: Write a test that demonstrates the bug fix or verifies the new feature.
    4. Open PR: Open your pull request against the develop branch. Note that main is the stable/release branch and is updated from develop by maintainers.

    Note: By submitting a patch, you agree to allow the project owner to license your work under the same license as the project.

  4. Specify a custom .env file location via environment variable

    develop

    You can point to a specific .env file location using an environment variable (e.g., ENV_PATH). This is useful in production environments where the configuration file resides in a non-standard directory. Use env.read_env() combined with env.str() to resolve the path.

    env = environ.Env()
    env.read_env(env.str('ENV_PATH', '.env'))
  5. Configure Django with django-environ

    develop

    Use django-environ to implement Twelve-factor methodology by configuring your Django application via environment variables. You can define casting rules and default values when initializing environ.Env, load variables from a .env file using environ.Env.read_env(), and parse connection URLs (database, cache, etc.) directly into Django settings.

    import environ
    from pathlib import Path
    
    env = environ.Env(
        # set casting, default value
        DEBUG=(bool, False)
    )
    
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    # Take environment variables from .env file
    environ.Env.read_env(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
    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')
    }
  6. Apply a prefix to all environment variables

    develop

    To avoid namespace collisions, you can prefix all environment variable lookups. You can do this by setting the prefix attribute on an Env instance. When a prefix is set, the library will automatically look for variables in os.environ that start with that prefix.

    # .env file contents
    # DJANGO_TEST="foo"
    
    # settings.py
    import environ
    
    env = environ.Env()
    env.prefix = 'DJANGO_'
    
    # This will look for 'DJANGO_TEST' in the environment
    value = env.str('TEST')  # returns "foo"
  7. Report a bug

    develop

    Before reporting a bug, ensure you are using the latest version of django-environ and check the GitHub issue search to see if it has already been reported. You should also try to reproduce the issue using the latest main or develop branches.

    When submitting a bug report, include:

    • Relevant package versions.
    • Steps to recreate the issue.
    • A full stacktrace if an exception occurred.
    • An executable code example or a reduced test case where possible.
    • Details about your environment (OS, expected outcome, etc.).
  8. Use Docker-style file-based variables

    develop

    When using platforms like Docker Swarm or Kubernetes that provide secrets as files (e.g., in /run/secrets/), use the FileAwareEnv class instead of the standard Env class. FileAwareEnv automatically looks for an environment variable with _FILE appended to the name. If found, it reads the contents of that file and uses them as the value.

    import environ
    
    # Use FileAwareEnv to support _FILE suffix
    env = environ.FileAwareEnv()
    SECRET_KEY = env("SECRET_KEY")
  9. Create a .env.dist template for project onboarding

    develop

    Create a .env.dist file in your repository to serve as a template for required environment variables. This file should include comments explaining the purpose of variables and provide safe default or placeholder values. This file is intended to be committed to version control.

    # SECURITY WARNING: don't run with the debug turned on in production!
    DEBUG=True
    
    # Should robots.txt allow everything to be crawled?
    ALLOW_ROBOTS=False
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY=secret
    
    # A list of all the people who get code error notifications.
    ADMINS="John Doe <john@example.com>, Mary <mary@example.com>"
    
    # A list of all the people who should get broken link notifications.
    MANAGERS="Blake <blake@cyb.org>, Alice Judge <alice@cyb.org>"
    
    # By default, Django will send system email from root@localhost.
    # However, some mail providers reject all email from this address.
    SERVER_EMAIL=webmaster@example.com
  10. Install the unstable development version of django-environ

    develop

    If you need the latest unreleased features from the develop branch, you can install it directly from GitHub. Note that this version is a work-in-progress and may be unstable.

    $ pip install -e git://github.com/joke2k/django-environ.git#egg=django-environ
    # OR
    $ pip install --upgrade https://github.com/joke2k/django-environ.git/archive/develop.tar.gz
  11. Set up a local development environment

    develop

    To set up a local environment for contributing to django-environ, follow these steps to create a virtual environment, install development dependencies, and run the test suite using tox.

    1. Create and activate a virtual environment
    2. Install development dependencies (including tox, tox-gh-actions, and setuptools)
    3. Run the test suite using tox or a specific environment like py312-django51.
  12. Install django-environ via pip

    develop

    Install the stable version of django-environ using pip. It is recommended to install it into a virtual environment. Note that after installation, you do not need to add django-environ to your Django INSTALLED_APPS setting.

    $ python -m pip install django-environ