django-environ 从环境变量获取参数
Published on Aug. 22, 2023, 12:11 p.m.
django-environ 是一个 Python 包,它可以帮助您的Django配置环境变量。
安装
python -m pip install django-environ
要求
Django >= 1.11
Python >= 3.5
使用
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__)))
#从.env 文件读取配置参数
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:[email protected]: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')
}
官方文档
https://django-environ.readthedocs.io/en/latest/install.html