在金字塔中,我需要根据不同的运行时环境来渲染我的模板——启用谷歌分析、使用缩小代码等(在生产中)。有没有一种简单的方法可以找出当前的环境——也许是一个现有的标志来找出使用了哪个 ini 文件?
问问题
1557 次
2 回答
15
Pyramid INI 文件可以包含任意配置条目,那么为什么不在文件中包含一个标志来区分生产和开发部署呢?
我会这样做;在您的生产 .ini 文件中:
[app:main]
production_deployment = True # Set to False in your development .ini file
将此值传递给 Pyramid Configurator:
def main(global_config, **settings):
# ...
from pyramid.settings import asbool
production_deployment = asbool(settings.get(
'production_deployment', 'false'))
settings['production_deployment'] = production_deployment
config = Configurator(settings=settings)
您现在可以从 Pyramid 代码中的任何位置访问设置。例如,在请求处理程序中:
settings = request.registry.settings
if settings['production_deployment']:
# Enable some production code here.
但是,在这种情况下,我也会使用更细粒度的设置;用于启用 Google Analytics 的标志,用于缩小资源等的标志。这样您就可以在开发环境中测试每个单独的设置,为这些开关编写单元测试等。
于 2012-06-11T06:43:52.337 回答
3
我将这种东西设置为一个环境变量,命名为类似的东西PYRAMID_ENV
,可以通过os.environ
. 例如在您的代码中:
import os
pyramid_env = os.environ.get('PYRAMID_ENV', 'debug')
if pyramid_env == 'debug':
# Setup debug things...
else:
# Setup production things...
然后你可以在初始化脚本或启动服务器时设置变量:
PYRAMID_ENV=production python server.py
关于访问环境变量的文档:http: //docs.python.org/library/os.html#os.environ
于 2012-06-11T06:29:34.397 回答