### Install django-environ using pip Source: https://github.com/joke2k/django-environ/blob/develop/docs/install.md Install the stable version of django-environ using pip. This is the recommended method for most users. ```console python -m pip install django-environ ``` -------------------------------- ### Basic Django Project Setup with django-environ Source: https://github.com/joke2k/django-environ/blob/develop/README.rst Demonstrates how to set up BASE_DIR and read environment variables from a .env file for DEBUG and SECRET_KEY. ```python # 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') ``` -------------------------------- ### Install unstable django-environ from Git (archive) Source: https://github.com/joke2k/django-environ/blob/develop/docs/install.md Install the latest development version of django-environ from a GitHub archive URL. This method also installs the unstable 'develop' branch. ```console pip install --upgrade https://github.com/joke2k/django-environ.git/archive/develop.tar.gz ``` -------------------------------- ### Install development dependencies Source: https://github.com/joke2k/django-environ/blob/develop/CONTRIBUTING.rst Installs necessary development tools like tox for testing across different Python versions and environments. ```bash python -m pip install -U pip tox tox-gh-actions setuptools ``` -------------------------------- ### Example .env file format Source: https://github.com/joke2k/django-environ/blob/develop/docs/quickstart.md Define environment variables in a .env file. This format supports various URL types for databases, caches, and other services. ```shell DEBUG=on SECRET_KEY=your-secret-key DATABASE_URL=psql://user:un-githubbedpassword@127.0.0.1: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=django_redis.client.DefaultClient&password=ungithubbed-secret ``` -------------------------------- ### Install unstable django-environ from Git (editable) Source: https://github.com/joke2k/django-environ/blob/develop/docs/install.md Install the latest development version of django-environ directly from the 'develop' branch on GitHub in editable mode. Use this for testing the latest features, but be aware it may be unstable. ```console pip install -e git://github.com/joke2k/django-environ.git#egg=django-environ ``` -------------------------------- ### Docker Compose Configuration for Secrets Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Example docker-compose.yml snippet showing how to mount secrets as files for containers. ```yaml secrets: secret_key: external: true services: app: secrets: - secret_key environment: - SECRET_KEY_FILE=/run/secrets/secret_key ``` -------------------------------- ### Example .env.dist file for version control Source: https://github.com/joke2k/django-environ/blob/develop/docs/quickstart.md Create a .env.dist file to document mandatory environment variables for your project. This file can be committed to version control to help new team members set up the project. ```shell # 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 , Mary " # A list of all the people who should get broken link notifications. MANAGERS="Blake , Alice Judge " # 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 ``` -------------------------------- ### Interpolating Proxy Values Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Demonstrates how environment variable values starting with '$' can be interpolated with other variables. This feature is enabled by default. ```python import environ env = environ.Env() # BAR=FOO # PROXY=$BAR assert env.str('PROXY') == 'FOO' ``` -------------------------------- ### Prefixing Environment Variables in Django Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Use this when you need to namespace all your environment variables, for example, to avoid conflicts or organize settings for a specific application like Django. Ensure the prefix is set before accessing any variables. ```shell # .env file contents DJANGO_TEST="foo" ``` ```python # settings.py file contents import environ env = environ.Env() env.prefix = 'DJANGO_' env.str('TEST') # foo ``` -------------------------------- ### Escape Proxy Variables in Django-environ Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Enable `escape_proxy` to prevent values starting with '$' from being interpreted as proxy variables. Prepend a backslash to the variable to escape it. ```python import environ env = environ.Env() env.escape_proxy = True # ESCAPED_VAR=$baz env.str('ESCAPED_VAR') # $baz ``` -------------------------------- ### Create and activate virtual environment Source: https://github.com/joke2k/django-environ/blob/develop/CONTRIBUTING.rst Sets up a Python virtual environment for development. Ensure you are in the project's root directory before running these commands. ```bash python3 -m venv .venv . .venv/bin/activate ``` -------------------------------- ### Configure Env Instance in One Step Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Utilize `environ.Env.configured()` for a streamlined process of creating and configuring an `Env` instance with flags like `prefix`, `smart_cast`, and `warn_on_default`. ```python env = environ.Env.configured( prefix='DJANGO_', smart_cast=False, warn_on_default=True, ) env.bool('DEBUG', default=False) ``` ```python env = environ.Env.configured( BASE_DIR('.env'), overwrite=True, parse_comments=True, prefix='DJANGO_', smart_cast=False, ) ``` ```python env = environ.Env.configured( BASE_DIR('.env'), scheme={ 'DEBUG': (bool, False), 'DATABASE_URL': str, }, ) ``` -------------------------------- ### Cache Configuration with django-environ Source: https://github.com/joke2k/django-environ/blob/develop/README.rst Illustrates how to configure cache backends by parsing URLs from environment variables, including a default Redis configuration. ```python 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') } ``` -------------------------------- ### Database Configuration with django-environ Source: https://github.com/joke2k/django-environ/blob/develop/README.rst Shows how to parse database connection URLs from environment variables, including a default SQLite configuration. ```python # 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' ) } ``` -------------------------------- ### Run the test suite with tox Source: https://github.com/joke2k/django-environ/blob/develop/CONTRIBUTING.rst Executes the project's test suite using tox. You can also target specific environments, such as 'py312-django51' for Python 3.12 and Django 5.1. ```bash tox tox -e py312-django51 ``` -------------------------------- ### Using Path Objects for Reading Env Files Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Illustrates how to use `pathlib.Path` objects when specifying the location of environment files. This provides a more object-oriented approach to file path manipulation. ```python import os import pathlib import environ # Build paths inside the project like this: BASE_DIR('subdir'). BASE_DIR = environ.Path(__file__) - 3 env = environ.Env() # The four lines below do the same: env.read_env(BASE_DIR('.env')) env.read_env(os.path.join(BASE_DIR, '.env')) env.read_env(pathlib.Path(str(BASE_DIR)).joinpath('.env')) env.read_env(pathlib.Path(str(BASE_DIR)) / '.env') ``` -------------------------------- ### Configure SAML Attribute Mapping with Complex Dict Format Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Handles complex dictionary structures for settings like SAML_ATTRIBUTE_MAPPING. The .env file uses a semicolon-separated key-value format, and the Python code parses it into a dictionary with tuple values. ```shell # .env file contents SAML_ATTRIBUTE_MAPPING="uid=username;mail=email;cn=first_name;sn=last_name;" ``` ```python # settings.py file contents import environ env = environ.Env() # {'uid': ('username',), 'mail': ('email',), 'cn': ('first_name',), 'sn': ('last_name',)} SAML_ATTRIBUTE_MAPPING = env.dict( 'SAML_ATTRIBUTE_MAPPING', cast={'value': tuple}, default={} ) ``` -------------------------------- ### Reading Multiline Values from .env Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Demonstrates how to read multiline values from a .env file using `env.str()` with the `multiline=True` option. Shows the difference between unquoted, quoted, and escaped newline characters. ```shell # .env file contents UNQUOTED_CERT=---BEGIN---\r\n---END--- QUOTED_CERT="---BEGIN---\r\n---END---" ESCAPED_CERT=---BEGIN---\\n---END--- ``` ```python import environ env = environ.Env() print(env.str('UNQUOTED_CERT', multiline=True)) # ---BEGIN--- # ---END--- print(env.str('UNQUOTED_CERT', multiline=False)) # ---BEGIN---\r\n---END--- print(env.str('QUOTED_CERT', multiline=True)) # ---BEGIN--- # ---END--- print(env.str('QUOTED_CERT', multiline=False)) # ---BEGIN---\r\n---END--- print(env.str('ESCAPED_CERT', multiline=True)) # ---BEGIN--- # ---END--- print(env.str('ESCAPED_CERT', multiline=False)) # ---BEGIN---\\n---END--- ``` -------------------------------- ### Configure Database URL with Extra Options Source: https://github.com/joke2k/django-environ/blob/develop/docs/types.md Use `db_url_config` to parse a database URL and merge additional options, such as pool settings, into the configuration. ```python config = environ.Env.db_url_config( "postgres://user:password@host:5432/dbname", extra_options={ "pool": {"min_size": 2, "max_size": 4, "timeout": 10}, }, ) # {"OPTIONS": {"pool": {"min_size": 2, "max_size": 4, "timeout": 10}}} ``` -------------------------------- ### environ.Env.db_url_config Source: https://github.com/joke2k/django-environ/blob/develop/docs/types.md Configuration for database URLs, including support for extra options. ```APIDOC ## environ.Env.db_url_config ### Description Allows configuration of database URLs with support for extra options that are merged into `OPTIONS`. ### Method `db_url_config` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python config = environ.Env.db_url_config( "postgres://user:password@host:5432/dbname", extra_options={ "pool": {"min_size": 2, "max_size": 4, "timeout": 10}, }, ) # Expected OPTIONS: {"OPTIONS": {"pool": {"min_size": 2, "max_size": 4, "timeout": 10}}} ``` ### Response #### Success Response (200) None (This is a configuration method) #### Response Example None ``` -------------------------------- ### Initialize django-environ Source: https://github.com/joke2k/django-environ/blob/develop/README.rst Initialize the environ.Env object, specifying casting and default values for environment variables like DEBUG. ```python import environ from pathlib import Path env = environ.Env( # set casting, default value DEBUG=(bool, False) ) ``` -------------------------------- ### Configure Multiple Redis Cache Locations Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Configure multiple master/slave or shard locations for redis cache by providing a comma-separated list of host:port pairs in the CACHE_URL. ```shell CACHE_URL='rediscache://master:6379,slave1:6379,slave2:6379/1' ``` -------------------------------- ### Reading Multiple Env Files in Django-environ Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Demonstrates how to read environment variables from different .env files based on an environment variable pointing to the desired file location. This is useful for production systems with distinct .env file paths. ```shell # /etc/environment file contents DEBUG=False ``` ```shell # .env file contents DEBUG=True ``` ```python env = environ.Env() env.read_env(env.str('ENV_PATH', '.env')) ``` -------------------------------- ### environ.Env.cache_url Source: https://github.com/joke2k/django-environ/blob/develop/docs/types.md Supported URL schemas for cache configurations. ```APIDOC ## environ.Env.cache_url ### Description Supports various URL schemas for configuring cache backends. ### Method `cache_url` ### Endpoint N/A (This is a method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage with a Redis cache URL cache_url = "rediscache://user:password@host:6379/0" config = environ.Env.cache_url(cache_url) ``` ### Response #### Success Response (200) None (This is a configuration method) #### Response Example None ### Supported URL Schemas * Database: `dbcache://` * Dummy: `dummycache://` * File: `filecache://` * Memory: `locmemcache://` * Memcached: * `memcache://` (uses `python-memcached` backend, deprecated in Django 3.2) * `pymemcache://` (uses `pymemcache` backend if Django >=3.2 and package is installed, otherwise will use `pylibmc` backend) * `pylibmc://` * Redis: `rediscache://`, `redis://`, or `rediss://` * Valkey: `valkey://`, or `valkeys://` ``` -------------------------------- ### environ.Env.search_url Source: https://github.com/joke2k/django-environ/blob/develop/docs/types.md Supported URL schemas for search engine configurations. ```APIDOC ## environ.Env.search_url ### Description Supports various URL schemas for configuring search engine backends. ### Method `search_url` ### Endpoint N/A (This is a method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage with an Elasticsearch URL search_url = "elasticsearch://user:password@host:9200/" config = environ.Env.search_url(search_url) ``` ### Response #### Success Response (200) None (This is a configuration method) #### Response Example None ### Supported URL Schemas * Elasticsearch: `elasticsearch://` (http) or `elasticsearchs://` (https) * Elasticsearch2: `elasticsearch2://` (http) or `elasticsearch2s://` (https) * Elasticsearch5: `elasticsearch5://` (http) or `elasticsearch5s://` (https) * Elasticsearch7: `elasticsearch7://` (http) or `elasticsearch7s://` (https) * Solr: `solr://` * Whoosh: `whoosh://` * Xapian: `xapian://` * Simple cache: `simple://` ``` -------------------------------- ### environ.Env.email_url Source: https://github.com/joke2k/django-environ/blob/develop/docs/types.md Supported URL schemas for email configurations. ```APIDOC ## environ.Env.email_url ### Description Supports various URL schemas for configuring email backends. ### Method `email_url` ### Endpoint N/A (This is a method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage with an SMTP+TLS email URL email_url = "smtp+tls://user:password@smtp.example.com:587/" config = environ.Env.email_url(email_url) ``` ### Response #### Success Response (200) None (This is a configuration method) #### Response Example None ### Supported URL Schemas * SMTP: `smtp://` * SMTP+SSL: `smtp+ssl://` * SMTP+TLS: `smtp+tls://` * Console mail: `consolemail://` * File mail: `filemail://` * LocMem mail: `memorymail://` * Dummy mail: `dummymail://` ``` -------------------------------- ### Restricting String Values with Choices Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Shows how to restrict environment variable string values to a predefined list using the `choices` argument in `env.str()`. An `ImproperlyConfigured` exception is raised if the value is not in the allowed list. ```python import environ from django.core.exceptions import ImproperlyConfigured env = environ.Env() # APP_ENV=prod env.str("APP_ENV", choices=("dev", "prod", "staging")) # "prod" # APP_ENV=unknown try: env.str("APP_ENV", choices=("dev", "prod", "staging")) except ImproperlyConfigured: ... ``` -------------------------------- ### Configure Django Email Settings Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Use the email() method as an alias for email_url() to set email configuration. Ensure EMAIL_URL is defined in your environment or provide a default. ```python # The email() method is an alias for email_url(). EMAIL_CONFIG = env.email( 'EMAIL_URL', default='smtp://user:password@localhost:25' ) vars().update(EMAIL_CONFIG) ``` -------------------------------- ### Enable Warnings for Default Values Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Enable warnings on the Env instance to be notified when a missing environment variable falls back to a default value. This emits a DefaultValueWarning. ```python import environ env = environ.Env() env.warn_on_default = True value = env("MISSING_VAR", default="fallback") ``` -------------------------------- ### Read Secrets from Files with FileAwareEnv Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Use environ.FileAwareEnv to read environment variables from files, commonly used with Docker secrets. ```python import environ env = environ.FileAwareEnv() SECRET_KEY = env("SECRET_KEY") ``` -------------------------------- ### Configure Database URL Options - django-environ Source: https://github.com/joke2k/django-environ/blob/develop/docs/types.md Use env.db_url_config to parse a database URL and specify custom casting for query parameters like booleans or JSON. ```python import json import environ url = ( "mysql://user:password@host:3306/dbname?" "reconnect=true&ssl=%7B%22ca%22%3A%22%2Fapp%2Ffoo%2Fca.pem%22%7D" ) config = environ.Env.db_url_config( url, options_cast={ "reconnect": bool, "ssl": json.loads, } ) ``` -------------------------------- ### Django settings.py integration with django-environ Source: https://github.com/joke2k/django-environ/blob/develop/docs/quickstart.md Integrate django-environ into your Django settings.py to read environment variables. Ensure the .env file is in the project root and read using `environ.Env.read_env()`. ```python 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 # 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') } ``` -------------------------------- ### Overwriting Existing Env Values with Read Env Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Use `overwrite=True` in `environ.Env.read_env()` to give precedence to variables defined in env files over existing environment variables. ```python env = environ.Env() env.read_env(BASE_DIR('.env'), overwrite=True) ``` -------------------------------- ### Handling Inline Comments in .env Files Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Demonstrates how `django-environ` parses inline comments in `.env` files using the `parse_comments` parameter. Use `parse_comments=True` to ignore comments, or `parse_comments=False` (or default) to include them in values. Be aware that values containing '#' will be truncated when comments are parsed. ```shell # .env file contents BOOL_TRUE_WITH_COMMENT=True # This is a comment STR_WITH_HASH=foo#bar # This is also a comment ``` ```python import environ # Using parse_comments=True env = environ.Env() env.read_env(parse_comments=True) print(env('BOOL_TRUE_WITH_COMMENT')) # Output: True print(env('STR_WITH_HASH')) # Output: foo # Using parse_comments=False env = environ.Env() env.read_env(parse_comments=False) print(env('BOOL_TRUE_WITH_COMMENT')) # Output: True # This is a comment print(env('STR_WITH_HASH')) # Output: foo#bar # This is also a comment # Using default behavior env = environ.Env() env.read_env() print(env('BOOL_TRUE_WITH_COMMENT')) # Output: True # This is a comment print(env('STR_WITH_HASH')) # Output: foo#bar # This is also a comment ``` -------------------------------- ### Disabling Proxy Interpolation Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Illustrates how to disable the default interpolation of proxy values by setting `env.interpolate = False`. This allows reading the raw value, including the '$' prefix. ```python env = environ.Env() env.interpolate = False # PROXY=$BAR assert env.str('PROXY') == '$BAR' ``` -------------------------------- ### Parse Django Admins using email.utils.getaddresses Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md An alternative method to parse Django ADMINS using the getaddresses function from Python's email.utils module. This handles more complex email address formats. ```python # DJANGO_ADMINS=Alice Judge ,blake@cyb.org from email.utils import getaddresses ADMINS = getaddresses([env('DJANGO_ADMINS')]) ``` -------------------------------- ### Parse Django Admins from Environment List Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Handles nested list settings like Django's ADMINS. This snippet parses a comma-separated list of 'Name:email' pairs from the DJANGO_ADMINS environment variable. ```python # DJANGO_ADMINS=Blake:blake@cyb.org,Alice:alice@cyb.org ADMINS = [x.split(':') for x in env.list('DJANGO_ADMINS')] ``` -------------------------------- ### Use Callable Defaults for Lazy Evaluation Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Use a callable as a default value when the environment variable is absent. The callable is only invoked when the variable is missing, which is useful for generating default values with side-effects. ```python import tempfile import environ env = environ.Env() # tempfile.mkdtemp() is called only when MEDIA_ROOT is not set MEDIA_ROOT = env('MEDIA_ROOT', default=tempfile.mkdtemp) ``` -------------------------------- ### Overwrite Existing Environment Variables in django-environ Source: https://github.com/joke2k/django-environ/blob/develop/docs/faq.md To override existing environment variables with values from a .env file, pass `overwrite=True` to `environ.Env.read_env()`. This is useful when the deployment environment might not have all necessary configurations set. ```python environ.Env.read_env(overwrite=True) ``` -------------------------------- ### Parse Django Admins using email.utils.parseaddr Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Another option for parsing Django ADMINS using parseaddr from email.utils. This method is suitable for parsing email addresses and names from a string. ```python # DJANGO_ADMINS="Blake , Alice Judge " from email.utils import parseaddr ADMINS = tuple(parseaddr(email) for email in env.list('DJANGO_ADMINS')) ``` -------------------------------- ### Encode Unsafe Characters in URL Values Source: https://github.com/joke2k/django-environ/blob/develop/docs/tips.md Encode values containing unsafe characters using urllib.parse.quote() before setting them in a .env file for URLs. ```shell DATABASE_URL=mysql://user:%23password@127.0.0.1:3306/dbname ``` -------------------------------- ### Parse Dictionary String - django-environ Source: https://github.com/joke2k/django-environ/blob/develop/docs/types.md Use env.parse_value with dict to parse simple key-value pairs from a string. For more complex dictionaries with mixed types, provide a cast dictionary. ```python import environ env = environ.Env() # {'key': 'val', 'foo': 'bar'} env.parse_value('key=val,foo=bar', dict) ``` ```python env.parse_value( 'key=val;foo=1.1;baz=True', dict(value=str, cast=dict(foo=float,baz=bool)) ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.