金字塔和.ini配置

发布于 2021-01-29 15:26:38

每个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文件并在启动时进行解析?

关注者
0
被浏览
71
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    你当然可以。

    在您的入口函数中(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()
    

    根据最新的Pyramid文档,您可以通过访问视图功能中的设置request.registry.settings。而且,据我所知,事件将通过订阅event.request.registry.settings

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



推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看