有没有一种简单的方法可以在Pyramid中找到运行时环境

时间:2012-06-11 06:10:14

标签: python pyramid

在金字塔中,我需要根据不同的运行时环境渲染我的模板 - 启用谷歌分析,使用缩小的代码等(在生产时)。有没有一种简单的方法来找出当前的环境 - 也许是一个现有的标志来找出使用了哪个ini文件?

2 个答案:

答案 0 :(得分:15)

Pyramid INI文件可以保存arbitrary configuration entries,那么为什么不在文件中包含区分生产和开发部署的标志?

我会这样做的;在您的生产.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的标志,用于缩小资源等的标志。这样,您可以测试开发环境中的每个设置,为这些开关编写单元测试等。

答案 1 :(得分: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...

然后,您可以在init脚本中或启动服务器时设置变量:

PYRAMID_ENV=production python server.py

访问环境变量的文档:http://docs.python.org/library/os.html#os.environ

相关问题