Pyramid and .ini configuration

浪子不回头ぞ 提交于 2019-12-18 11:49:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7570930/pyramid-and-ini-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!