【问题标题】:How can I access a custom section in a Pyramid .ini file?如何访问 Pyramid .ini 文件中的自定义部分?
【发布时间】:2013-11-08 11:26:53
【问题描述】:

我目前正在为多个服务编写数据收集服务。可能有 5 个不同的 API 端点具有不同的主机和端口号。我想为此创建一个设置文件,但认为 .ini 应该是一个更好的地方,或者我认为...

我的 development.ini 看起来像这样:

[app:main]
use = egg:awesomeproject
auth.tkt = 'abc'
auth.secret = 'I love python'

mongodb.host = 'somehost'
mongodb.port= 6379

[server:main]
use = egg:waitress#main
host = 0.0.0.0
port = 6543

[user:sg:qa]
host = 127.0.0.1
port = 1234

[customer:sg:qa]
host = 127.0.0.2
port = 4567

我尝试访问金字塔事件中的自定义部分,如下所示:

def add_api_path(event):
    request = event.request
    settings = request.registry.settings
    _type = 'customer:sg:qa'
    base_config = settings[_type]

但这不起作用,因为设置实际上是[app:main] 属性的字典。有人可以教我以金字塔方式访问这些部分的方法吗?我读到了另一种方法,使用 ConfigParser,但我想先问一下 Pyramid 中是否还有其他更简单的方法。

【问题讨论】:

    标签: python pyramid


    【解决方案1】:

    如果你想这样做,你必须自己解析配置文件。您看到的部分隔离行为是故意的。

    def main(global_conf, **settings):
        parser = ConfigParser({'here': global_conf['__here__']})
        parser.read(global_conf['__file__'])
        for k, v in parser.items('user:sg:qa'):
            settings['user:sg:qa:' + k] = v
    
        config = Configurator(settings=settings)
    

    然后你可以获取设置:

    request.registry.settings['user:sg:qa:host']
    

    更新

    在 Pyramid 1.9 中,ini 解析是可插入的,并创建了一个新库来帮助以标准方式加载文件的任意部分。以下是更新后的示例:

    import plaster
    
    def main(global_conf, **settings):
        user_settings = plaster.get_settings(global_conf['__file__'], 'user:sg:qa')
        for k, v in user_settings.items():
            settings['user:sg:qa:' + k] = v
    
        config = Configurator(settings=settings)
    

    【讨论】:

    • 是的,这就是我最终所做的。我使用 ConfigParser 来读取 conf 文件。我不知道上述方法的 global_conf 实际上是 .ini 文件虽然.....很有趣。
    • 其实是global_conf['__file__'],为了正确我会编辑答案
    • @MichaelMerickel 我发现最新的 Pyramid 版本使用密钥 here 而不是 __here__
    • 我已经稍微更新了示例,以演示使用 plaster(pyramid 的新可插入配置解析库)来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2021-07-09
    • 2022-06-16
    相关资源
    最近更新 更多