金字塔和.ini配置

时间:2011-09-27 14:35:54

标签: python configuration-files pyramid ini

每个Pyramid应用程序都有一个包含其设置的关联.ini文件。例如,默认值可能如下所示:

[app:main]
use = egg:MyProject
pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = false
pyramid.debug_routematch = false
...

我想知道是否可以在那里添加自己的配置值,并在运行时读取它们(主要来自可调用的视图)。例如,我可能想要

[app:main]
blog.title = "Custom blog name"
blog.comments_enabled = true
...

或者,在启动时使用单独的.ini文件并解析它会更好吗?

1 个答案:

答案 0 :(得分:27)

当然可以。

在您的入口点功能(大多数情况下main(global_config, **settings)__init__.py)中,您的配置可在settings变量中访问。

例如,在.ini

[app:main]
blog.title = "Custom blog name"
blog.comments_enabled = true

__init__.py

def main(global_config, **settings):
    config = Configurator(settings=settings)
    blog_title = settings['blog.title']
    # you can also access you settings via config
    comments_enabled = config.registry.settings['blog.comments_enabled']
    return config.make_wsgi_app()

根据latest Pyramid docs,您可以通过request.registry.settings访问视图功能中的设置。此外,据我所知,它将通过event.request.registry.settings在事件订阅者中发布。

关于使用其他文件的问题,我非常确定将所有配置放在常规init文件中是一种好习惯,使用点缀符号,就像你一样。