【发布时间】:2019-10-19 00:56:02
【问题描述】:
我正在寻找在 django 应用程序中加载 envvars.sh 文件的解决方案。我宁愿在设置模块中执行此操作,并在其外部保留一个文件。这是我目前拥有的:
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
def source_envvars(fname='envvars.sh'):
"""Equivalent of `$ source {fname}` with lines in the form of `export key=value`"""
envvars = os.path.join(SITE_ROOT, fname)
if not os.path.exists(envvars): return
with open(fname, 'r') as f:
for line in f:
if line.startswith('export '):
line = line.strip()
key = line.split('=')[0].split()[1]
value = line.split('=')[1].strip('"\'')
os.environ[key] = value
if not os.environ.get('DB_HOST'): source_envvars()
# rest of settings.py file...
使用这种方法有什么缺点吗?我知道这不支持复杂的 bash 类型的导出,但我所拥有的只是以下形式的基本导出:
export DB_HOST=rds.amazon.com/12345
上述方法是否正确实例化了所有变量,或者它似乎遗漏了什么或以某种方式不安全?
【问题讨论】:
标签: python django environment-variables