每个 Pyramid 应用程序都有一个关联的 .ini 文件,其中包含其设置。例如,默认值可能如下所示:
[app:main]
use = egg:MyProject
pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = false
pyramid.debug_routematch = false
...
我想知道是否可以在其中添加您自己的配置值,并在运行时读取它们(主要是从可调用 View )。例如,我可能想要
[app:main]
blog.title = "Custom blog name"
blog.comments_enabled = true
...
还是有一个单独的 .ini 文件并在启动时解析它更好?
最佳答案
当然可以。
在你的入口点函数中(在大多数情况下,main(global_config, **settings)
in __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
访问 View 函数中的设置。此外,据我所知,它将通过 event.request.registry.settings
在事件订阅者中。
关于您关于使用另一个文件的问题,我很确定将所有配置放在常规初始化文件中是一种很好的做法,就像您一样使用点分符号。
关于python - Pyramid 和 .ini 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570930/