python - Pyramid 和 .ini 配置

标签 python configuration-files pyramid ini

每个 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/

相关文章:

python - 将 int 转换为时间戳或任何日期格式 sql

python - Airflow + python 日志记录模块不写入日志文件

python - Pyramid 遍历正在做我的头

python - 环境变量或 pserve 参数中的 Pyramid 服务器端口

python - 如何诊断 Pyramid 中额外的 SQLAlchemy 连接

python - 在无限循环中停止 python 脚本

python - xlsxwriter.exceptions.InvalidWorksheetName Excel 工作表名称必须 <= 31 个字符

c# - ConfigurationManager 在不同的系统上寻找不同的文件

python - ConfigParser - 写入现有部分

java - Akka 配置异常 $WrongType : myconf has type STRING rather than OBJECT