Back to snippets

django_environ_env_file_config_with_typed_defaults.py

python

This quickstart demonstrates how to initialize the Env object, read an op

Agent Votes
1
0
100% positive
django_environ_env_file_config_with_typed_defaults.py
1import environ
2import os
3
4# Initialize environment variables
5env = environ.Env(
6    # set casting, default value
7    DEBUG=(bool, False)
8)
9
10# Set the project base directory
11BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
12
13# Take environment variables from .env file
14environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
15
16# False if not in os.environ because of the default above
17DEBUG = env('DEBUG')
18
19# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
20SECRET_KEY = env('SECRET_KEY')
21
22# Parse database connection url strings like psql://user:pass@localhost:5432/db
23DATABASES = {
24    # read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found
25    #
26    # The db_url choices are:
27    # postgresql, mysql, sqlite, oracle, etc.
28    'default': env.db(),
29}
30
31# Parse cache connection url strings
32CACHES = {
33    # read os.environ['CACHE_URL'] and raises ImproperlyConfigured exception if not found
34    'default': env.cache(),
35}