我有一个小项目,我想同时部署到 Heroku 和 OpenShift,以便在这两个平台上进行尝试。我正在使用 Python/Django 所以我想利用动态导入功能来定义每个环境的设置,为我想要部署到的平台维护一个设置模块,例如:
my_project/
settings/
__init__.py <-- This is what's being imported during app init, here is where I want to detect which platform specific settings module to load
dev_settings.py
heroku_settings.py
openshift_settings.py
到目前为止,我使用此代码:
ENVIRONMENT = the_function_or_code_that_returns_the_environment() # Defaults to "dev"
from django.utils.importlib import import_module
try:
# Import any symbols that begin with A-Z. Append to lists any symbols that
# begin with "EXTRA_".
local_settings_module_name = '%s_settings' % ENVIRONMENT
local_settings = import_module(local_settings_module_name)
import re
for attr in dir(local_settings):
match = re.search('^EXTRA_(\w+)', attr)
if match:
name = match.group(1)
value = getattr(local_settings, attr)
try:
globals()[name] += value
except KeyError:
globals()[name] = value
elif re.search('^[A-Z]', attr):
globals()[attr] = getattr(local_settings, attr)
except ImportError:
pass
最好通过默认(不是由我/开发人员设置)环境变量来检测这一点。Heroku 只公开了一些:
DATABASE_URL
ENVIRONMENT
LANG
LD_LIBRARY_PATH
LIBRARY_PATH
PATH
PYTHONHASHSEED
PYTHONHOME
PYTHONPATH
PYTHONUNBUFFERED
SHARED_DATABASE_URL
和 OpenShift 的:
OPENSHIFT_DB_HOST
OPENSHIFT_LOG_DIR
OPENSHIFT_TMP_DIR
OPENSHIFT_DB_CTL_SCRIPT
OPENSHIFT_REPO_DIR
OPENSHIFT_HOMEDIR
OPENSHIFT_GEAR_NAME
OPENSHIFT_PHPMYADMIN_IP
OPENSHIFT_RUNTIME_DIR
OPENSHIFT_INTERNAL_PORT
OPENSHIFT_PHPMYADMIN_CTL_SCRIPT
OPENSHIFT_DB_MYSQL_51_RESTORE
OPENSHIFT_DB_MYSQL_51_DUMP
OPENSHIFT_DB_PASSWORD
OPENSHIFT_DB_USERNAME
OPENSHIFT_PHPMYADMIN_GEAR_DIR
OPENSHIFT_RUN_DIR
OPENSHIFT_INTERNAL_IP
OPENSHIFT_GEAR_DIR
OPENSHIFT_GEAR_CTL_SCRIPT
OPENSHIFT_APP_DNS
OPENSHIFT_GEAR_TYPE
OPENSHIFT_GEAR_DNS
OPENSHIFT_DB_MYSQL_51_EMBEDDED_TYPE
OPENSHIFT_DB_URL
OPENSHIFT_APP_NAME
OPENSHIFT_DATA_DIR
OPENSHIFT_DB_SOCKET
OPENSHIFT_GEAR_UUID
OPENSHIFT_APP_UUID
OPENSHIFT_DB_TYPE
OPENSHIFT_DB_MYSQL_51_DUMP_CLEANUP
OPENSHIFT_DB_PORT
OpenShift 变量带有前缀,OPENSHIFT_
因此有一个开头,但 Heroku 并非如此。
如何使用环境变量可靠地检测平台?