金字塔和 .ini 配置

2023-11-22

每个 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 文件并在启动期间解析它?


你当然可以。

在你的入口点函数中(main(global_config, **settings) in __init__.py在大多数情况下),您的配置可以在settings多变的。

例如,在你的.ini:

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

In your __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()

根据最新的金字塔文档,您可以通过以下方式访问视图函数中的设置request.registry.settings。另外,据我所知,事件订阅者将通过event.request.registry.settings.

关于您有关使用另一个文件的问题,我很确定将所有配置放入常规初始化文件中是一个很好的做法,使用点分符号就像您所做的那样。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

金字塔和 .ini 配置 的相关文章

随机推荐