API Reference

The __init__ module

The top-level module for django-environ package.

This module tracks the version of the package as well as the base package info used by various functions within django-environ.

Refer to the documentation for details on the use of this package.

The copyright notice of the package.

environ.__version__ = '0.13.0'

The version of the package.

environ.__license__ = 'MIT'

The license of the package.

environ.__author__ = 'Daniele Faraglia'

The author of the package.

environ.__author_email__ = 'daniele.faraglia@gmail.com'

The email of the author of the package.

environ.__maintainer__ = 'Daniele Faraglia'

The maintainer of the package.

environ.__maintainer_email__ = 'daniele.faraglia@gmail.com'

The email of the maintainer of the package.

environ.__url__ = 'https://django-environ.readthedocs.org'

The URL of the package.

environ.__description__ = 'A package that allows you to utilize 12factor inspired environment variables to configure your Django application.'

The description of the package.

The compat module

This module handles import compatibility issues.

environ.compat.choose_rediscache_driver()[source]

Backward compatibility for RedisCache driver.

environ.compat.choose_postgres_driver()[source]

Backward compatibility for postgresql driver.

environ.compat.choose_pymemcache_driver()[source]

Backward compatibility for pymemcache.

environ.compat.REDIS_DRIVER = 'django.core.cache.backends.redis.RedisCache'

The name of the RedisCache driver.

environ.compat.DJANGO_POSTGRES = 'django.db.backends.postgresql'

The name of the PostgreSQL driver.

environ.compat.PYMEMCACHE_DRIVER = 'django.core.cache.backends.memcached.PyLibMCCache'

The name of the Pymemcache driver.

The environ module

class environ.NoValue[source]

Represent of no value object.

class environ.DefaultValueWarning[source]

Warning used when returning an explicit default value.

class environ.Env(**scheme)[source]

Provide scheme-based lookups of environment variables so that each caller doesn’t have to pass in cast and default parameters.

Usage::

import environ
import os

env = environ.Env(
    # set casting, default value
    MAIL_ENABLED=(bool, False),
    SMTP_LOGIN=(str, 'DEFAULT')
)

# 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 due to casting above
MAIL_ENABLED = env('MAIL_ENABLED')

# 'DEFAULT' if not in os.environ due to casting above
SMTP_LOGIN = env('SMTP_LOGIN')
URL_CLASS

alias of ParseResult

classmethod configured(env_file=None, scheme=None, *, overwrite=False, parse_comments=False, encoding='utf8', smart_cast=True, escape_proxy=False, interpolate=True, warn_on_default=False, prefix='', **overrides)[source]

Create a configured Env instance.

This keeps Env.__init__ reserved for schema declarations while making it possible to configure instance flags in one step. If env_file is provided, the file is read after the instance is configured.

Parameters:
  • env_file – The path to the .env file your application should use. When omitted, no env file is read.

  • scheme – An optional mapping of schema declarations passed to Env.__init__.

  • overwriteoverwrite=True will force an overwrite of existing environment variables.

  • parse_comments – Determines whether to recognize and ignore inline comments in the .env file. Default is False.

  • encoding – The encoding to use when reading the environment file.

  • smart_cast – Enable or disable smart casting.

  • escape_proxy – Enable or disable escaped proxy values.

  • interpolate – Enable or disable proxy value interpolation.

  • warn_on_default – Enable or disable warnings for default values.

  • prefix – A prefix to prepend to variables read by the instance.

  • **overrides – Any additional keyword arguments provided directly to read_env will be added to the environment.

str(var, default: str | NoValue = <NoValue>, multiline=False, choices=<NoValue>) str[source]
Return type:

str

bytes(var, default: bytes | NoValue = <NoValue>, encoding='utf8') bytes[source]
Return type:

bytes

bool(var, default: bool | NoValue = <NoValue>) bool[source]
Return type:

bool

int(var, default: int | NoValue = <NoValue>) int[source]
Return type:

int

float(var, default: float | NoValue = <NoValue>) float[source]
Return type:

float

json(var, default=<NoValue>)[source]
Returns:

Json parsed

list(var, cast=None, default=<NoValue>) List[source]
Return type:

list

tuple(var, cast=None, default=<NoValue>) Tuple[source]
Return type:

tuple

dict(var, cast=<class 'dict'>, default=<NoValue>) Dict[source]
Return type:

dict

url(var, default=<NoValue>) ParseResult[source]
Return type:

urllib.parse.ParseResult

db_url(var='DATABASE_URL', default=<NoValue>, engine=None, options_cast=None, extra_options=None) Dict[source]

Returns a config dictionary, defaulting to DATABASE_URL.

The db method is an alias for db_url.

Return type:

dict

db(var='DATABASE_URL', default=<NoValue>, engine=None, options_cast=None, extra_options=None) Dict

Returns a config dictionary, defaulting to DATABASE_URL.

The db method is an alias for db_url.

Return type:

dict

cache_url(var='CACHE_URL', default=<NoValue>, backend=None) Dict[source]

Returns a config dictionary, defaulting to CACHE_URL.

The cache method is an alias for cache_url.

Return type:

dict

cache(var='CACHE_URL', default=<NoValue>, backend=None) Dict

Returns a config dictionary, defaulting to CACHE_URL.

The cache method is an alias for cache_url.

Return type:

dict

email_url(var='EMAIL_URL', default=<NoValue>, backend=None) Dict[source]

Returns a config dictionary, defaulting to EMAIL_URL.

The email method is an alias for email_url.

Return type:

dict

email(var='EMAIL_URL', default=<NoValue>, backend=None) Dict

Returns a config dictionary, defaulting to EMAIL_URL.

The email method is an alias for email_url.

Return type:

dict

search_url(var='SEARCH_URL', default: Dict | NoValue = <NoValue>, engine=None) Dict[source]

Returns a config dictionary, defaulting to SEARCH_URL.

Return type:

dict

channels_url(var='CHANNELS_URL', default: Dict | NoValue = <NoValue>, backend=None) Dict[source]

Returns a config dictionary, defaulting to CHANNELS_URL.

Return type:

dict

channels(var='CHANNELS_URL', default: Dict | NoValue = <NoValue>, backend=None) Dict

Returns a config dictionary, defaulting to CHANNELS_URL.

Return type:

dict

path(var, default: Path | NoValue = <NoValue>, **kwargs) Path[source]
Return type:

Path

get_value(var, cast=None, default=<NoValue>, parse_default=False)[source]

Return value for given environment variable.

Parameters:
  • var (str) – Name of variable.

  • cast (collections.abc.Callable or None) – Type to cast return value as.

  • default – If var not present in environ, return this instead. If default is a callable, it is called with no arguments to obtain the actual default value.

  • parse_default (bool) – Force to parse default.

Returns:

Value from environment or default (if set).

Return type:

IO[Any]

classmethod parse_value(value, cast)[source]

Parse and cast provided value

Parameters:
  • value – Stringed value.

  • cast – Type to cast return value as.

Returns:

Casted value

classmethod db_url_config(url, engine=None, options_cast=None, extra_options=None)[source]

Parse an arbitrary database URL.

Supports the following URL schemas:

  • PostgreSQL: postgres[ql]?:// or p[g]?sql://

  • PostGIS: postgis://

  • MySQL: mysql:// or mysql2://

  • MySQL (GIS): mysqlgis://

  • MySQL Connector Python from Oracle: mysql-connector://

  • SQLite: sqlite://

  • SQLite with SpatiaLite for GeoDjango: spatialite://

  • Oracle: oracle://

  • Microsoft SQL Server: mssql://

  • PyODBC: pyodbc://

  • Amazon Redshift: redshift://

  • LDAP: ldap://

Parameters:
  • url (urllib.parse.ParseResult or str) – Database URL to parse.

  • engine (str or None) – If None, the database engine is evaluates from the url.

  • options_cast (dict|None) – Optional per-option cast mapping for query-string-derived OPTIONS values. Unmapped options keep default casting behavior.

  • extra_options (dict|None) – Optional dictionary merged into OPTIONS after URL parsing. Values in extra_options override query-string OPTIONS.

Returns:

Parsed database URL.

Return type:

dict

classmethod cache_url_config(url, backend=None)[source]

Parse an arbitrary cache URL.

Parameters:
Returns:

Parsed cache URL.

Return type:

dict

classmethod email_url_config(url, backend=None)[source]

Parse an arbitrary email URL.

Parameters:
Returns:

Parsed email URL.

Return type:

dict

classmethod channels_url_config(url, backend=None)[source]

Parse an arbitrary channels URL.

Parameters:
Returns:

Parsed channels URL.

Return type:

dict

classmethod search_url_config(url, engine=None)[source]

Parse an arbitrary search URL.

Parameters:
Returns:

Parsed search URL.

Return type:

dict

classmethod read_env(env_file=None, overwrite=False, parse_comments=False, encoding='utf8', **overrides)[source]

Read a .env file into os.environ.

If not given a path to a dotenv path, does filthy magic stack backtracking to find the dotenv in the same directory as the file that called read_env.

Existing environment variables take precedent and are NOT overwritten by the file content. overwrite=True will force an overwrite of existing environment variables.

Parameters:
  • env_file – The path to the .env file your application should use. If a path is not provided, read_env will attempt to import the Django settings module from the Django project root.

  • overwriteoverwrite=True will force an overwrite of existing environment variables.

  • parse_comments – Determines whether to recognize and ignore inline comments in the .env file. Default is False.

  • encoding – The encoding to use when reading the environment file.

  • **overrides – Any additional keyword arguments provided directly to read_env will be added to the environment. If the key matches an existing environment variable, the value will be overridden.

class environ.FileAwareEnv(**scheme)[source]

First look for environment variables with _FILE appended. If found, their contents will be read from the file system and used instead.

Use as a drop-in replacement for the standard environ.Env:

python env = environ.FileAwareEnv()

For example, if a SECRET_KEY_FILE environment variable was set, env("SECRET_KEY") would find the related variable, returning the file contents rather than ever looking up a SECRET_KEY environment variable.

class environ.Path(start='', *paths, **kwargs)[source]

Inspired to Django Two-scoops, handling File Paths in Settings.

path(*paths, **kwargs)[source]

Create new Path based on self.root and provided paths.

Parameters:
  • paths – List of sub paths

  • kwargs – required=False

Return type:

Path

file(name, *args, **kwargs)[source]

Open a file.

Parameters:
  • name (str) – Filename appended to root

  • *args*args passed to open()

  • **kwargs**kwargs passed to open()

Return type:

IO[Any]

property root

Current directory for this Path

rfind(*args, **kwargs)[source]

Proxy method to str.rfind()

find(*args, **kwargs)[source]

Proxy method to str.find()

The fileaware_mapping module

class environ.fileaware_mapping.FileAwareMapping(env=None, cache=True)[source]

A mapping that wraps os.environ, first checking for the existence of a key appended with _FILE whenever reading a value. If a matching file key is found then the value is instead read from the file system at this location.

By default, values read from the file system are cached so future lookups do not hit the disk again.

A _FILE key has higher precedence than a value is set directly in the environment, and an exception is raised if the file can not be found.