金字塔和 .ini 配置

发布于 2024-12-06 15:29:03 字数 453 浏览 2 评论 0原文

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

Each Pyramid application has an associated .ini file that contains its settings. For example, a default might look like:

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

I am wondering if it is possible to add your own configuration values in there, and read them at run-time (mostly from a view callable). For instance, I might want to have

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

Or is it better to have a separate .ini file and parse it during startup?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不…忘初心 2024-12-13 15:29:03

当然可以。

在您的入口点函数中(大多数情况下是 __init__.py 中的 main(global_config, **settings)),您的配置可以在 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()

根据 最新 Pyramid 文档,您可以通过 request.registry.settings 访问视图函数中的设置。另外,据我所知,它将通过 event.request.registry.settings 位于事件订阅者中。

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

Sure you can.

In your entry point function (main(global_config, **settings) in __init__.py in most cases), your config is accessible in the settings variable.

For example, in your .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()

According to the latest Pyramid docs, you can access the settings in a view function via request.registry.settings. Also, as far as I know, it will be in event subscribers via event.request.registry.settings.

Regarding your question about using another file, I'm pretty sure it's good practice to put all your config in the regular init file, using dotted notation like you did.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文