我有一个我想要部署到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
.

优选通过默认值(未设置为ME / Developer)环境变量来检测此。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的情况并非如此。

如何使用环境变量可靠地检测平台?

有帮助吗?

解决方案 2

@kevin,我将我的评论发布为答案,所以人们可以快速看到它(或改进它!):

if len([k for k in os.environ.keys() if k.startswith('OPENSHIFT_')]):
    ENVIRONMENT = 'openshift'
elif len([k for k in os.environ.values() if k.find('heroku') > -1]):
    ENVIRONMENT = 'heroku'

local_settings_module_name = '%s_settings' % ENVIRONMENT
local_settings = import_module(local_settings_module_name)
# do the magic with the `local_settings` module
.

其他提示

我建议设置自己的env配置设置。这可以使用Heroku轻松完成。

heroku config:add MY_DEPLOYMENT_PLATFORM=heroku
. 然后,在您的初始化程序(或您需要的地方)中,您可以访问这样的值:
if ENV["MY_DEPLOYMENT_PLATFORM"] == "heroku"
 // perform heroku config
else 
 // perform other PAAS config
end
.

这是我如何检测目前我的应用程序的paas。overide_settings方法不是我的。

def override_settings(dottedpath):
    """Imports uppercase modules from an string based module.
    Example:
        override_settings('my.module.settings')
    """
    try:
        _m = import_module(dottedpath)
    except ImportError:
        warnings.warn("Failed to import %s" % dottedpath) # <-- will show up in your error log
    else:
        _thismodule = sys.modules[__name__]
        for _k in dir(_m): # <-- moved the block inside else
            if _k.isupper() and not _k.startswith('__'): setattr(_thismodule,
                _k, getattr(_m, _k))

ON_OPENSHIFT = False
if os.environ.has_key('OPENSHIFT_REPO_DIR'):
    ON_OPENSHIFT = True

ON_HEROKU = False
if os.environ.get('LD_LIBRARY_PATH', None) == '/app/.heroku/vendor/lib':
    ON_HEROKU = True

if ON_OPENSHIFT:
    override_settings('settings.openshift')

if ON_HEROKU:
    override_settings('settings.heroku')
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top