金字塔:如何避免将完整路径放入__init__.py中

Jer*_*y T 2 python path pyramid

我需要在main函数中提取配置文件:

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """ 

    parser = SafeConfigParser()
    ret = parser.read('/var/www/finance/corefinance/database.ini')
    connstring = parser.get('postgres', 'connstring')
    settings['sqlalchemy.url'] = connstring
Run Code Online (Sandbox Code Playgroud)

database.ini的位置是从init .py 的位置向上一级

我以为我可以使用"../database.ini",但这不起作用.唯一有效的是投入整条道路.如何避免在此文件中放入完整路径?

Raj*_*Raj 5

当然,在__init__.py中,您可以使用项目父目录的字符串表示来定义变量:

project_dir = '/var/www/finance/corefinance/'
Run Code Online (Sandbox Code Playgroud)

但我相信你并没有要求SO得到这样的答案.


另一种方法是在development.iniproduction.ini[app:main]部分中添加类似于以下行的内容:

project_dir = %(here)s/mycoolwebsite
Run Code Online (Sandbox Code Playgroud)

或者甚至只是:

project_dir = %(here)s
Run Code Online (Sandbox Code Playgroud)

然后在__init__.py(以及您想要引用项目的父目录的任何其他位置)中,您可以使用以下命令检索该值:

project_dir = config.registry.settings['project_dir']
Run Code Online (Sandbox Code Playgroud)

有关自定义变量的详细信息,请参阅:http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html#adding-a-custom-setting