2011-09-27 71 views
15

每个金字塔应用程序都有一个关联的.ini文件,其中包含其设置。例如,默认情况下可能看起来像:金字塔和.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文件并解析它?

回答

26

当然可以。

在您的入口点功能(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文件中是一种很好的做法,使用像你这样的虚线符号。