如何访问 Pyramid .ini 文件中的自定义部分? [英] How can I access a custom section in a Pyramid .ini file?

查看:51
本文介绍了如何访问 Pyramid .ini 文件中的自定义部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently writing a data collection service for multiple services. There are probably 5 different API Endpoints with differing hosts & port numbers. I wanted to create a settings file for this but thought that the .ini should be a better place, or so I thought...

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

My development.ini looks something like this:

[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

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

I tried to access the custom sections within a pyramid event like such:

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

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

But that didn't work, because settings is actually a dict of the [app:main] attributes. Can someone teach me the way to access the sections the Pyramid way? I read about another way, using ConfigParser, but I wanted to ask if there's any other easier way in Pyramid first.

推荐答案

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

If you want to do that you'll have to parse the config file yourself. The section-isolation behavior you're seeing is intentional.

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 解析变得可插入,并创建了一个新库以帮助以标准方式加载文件的任意部分.以下是更新后的示例:

In Pyramid 1.9 the ini parsing was made pluggable and a new library was created to assist in loading arbitrary sections of the file in a standard way. Below is the updated example:

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)

这篇关于如何访问 Pyramid .ini 文件中的自定义部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆