简体   繁体   English

Python和金字塔-使用configparser在python中读取ini文件

[英]Python and Pyramid -reading a ini file in python using configparser

I need to read an ini configuration file in Python and the related sample from the related section of the development.ini is below: 我需要阅读Python中的ini配置文件,并且来自development.ini相关部分的相关示例如下:

[app:main]
use = egg:ePRO

pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = true
pyramid.debug_routematch = true
pyramid.debug_templates = true

sqlalchemy.url = postgres://scott:tiger@localhost:5432/db

I'm using the ConfigParser module to read the file but unable to read the sqlalchemy.url parameter from the INI file, 我正在使用ConfigParser模块读取文件,但无法从INI文件读取sqlalchemy.url参数,

config = ConfigParser.ConfigParser()
config.read(config_uri)

How do I read the sqlalchemy.url parameter from the [app:main] ? 如何从[app:main]读取sqlalchemy.url参数?

文档所示 ,在config对象上使用get方法

url = config.get('app:main', 'sqlalchemy.url')

In my case I found that the following was necessary (a better example by using the Pyramid bootstrap features to connect to the SQLAlchemy database follows in the Update section) is added at the bottom of this question, since the %(here)s occurs in the url for SQLite in the same folder, so I am adding this answer to this question in the case this is helpful for anyone else, especially since the Pyramid alchemy scaffold uses SQLite by default (with this configuration and with the (here)s , and the answer above did not work correctly for me with either a ConfigParser , or SafeConfigParser , instance. I am working with Python 2.7.5 and it looks like this relates specifically to the characters in the sqlalchemy.url requiring raw_mode by specifying the additional 1 parameter in the get command to obtain this value. The documentation link , also mentioned in the above, includes notes about raw mode. The following is from Python interactive prompt launched in my Pyramid application directly a 在我的情况下,我发现以下步骤是必需的(在更新部分中添加了使用Pyramid bootstrap功能连接到SQLAlchemy数据库的更好示例),因为%(here)s发生在SQLite的网址位于同一文件夹中,因此,在对其他人有帮助的情况下,我将此问题添加到此问题中,尤其是因为金字塔alchemy支架默认情况下使用SQLite(具有此配置和(here)s ,和上面的答案没有正确的我无论是工作ConfigParser ,或SafeConfigParser ,实例。我使用Python 2.7.5工作,它看起来像这样具体涉及到的人物sqlalchemy.url通过指定额外的1需要raw_mode get命令中的参数以获得该值。上面也提到的文档链接包括有关原始模式的注释。以下是在我的Pyramid应用程序中直接启动的Python交互式提示符 t the same location as my development.ini (primarily the 4th row shows the difference): 与我的development.ini相同的位置(主要是第四行显示了区别):

>>> import ConfigParser, os
>>> config = ConfigParser.ConfigParser()
>>> config.readfp(open('development.ini'))
>>> config.get('app:main', 'sqlalchemy.url', 1)
'sqlite:///%(here)s/db.sqlite'

Also note that the following gives a similar error message to the following command: 还请注意,以下内容与以下命令给出了类似的错误消息:

>>> config.get('app:main', 'sqlalchemy.url', 0)

These are results I encountered with Python 2.7.5 when executing the code above is as follows: 这些是我在执行上述代码时在Python 2.7.5中遇到的结果,如下所示:

>>> url = config.get('app:main', 'sqlalchemy.url')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "--python_path--\lib\ConfigParser.py", line 623, in get
    return self._interpolate(section, option, value, d)
  File "--python_path--\lib\ConfigParser.py", line 669, in _interpolate
    option, section, rawval, e.args[0])
ConfigParser.InterpolationMissingOptionError: Bad value substitution:
        section: [app:main]
        option : sqlalchemy.url
        key    : here
        rawval : sqlite:///%(here)s/db.sqlite

For a specific reference from the documentation, see the following excerpt which illustrates this more clearly and is far more portable than not using raw mode: 有关文档的特定参考,请参见以下摘录,该摘录更清楚地说明了这一点,并且比不使用原始模式时更易于移植:

# Set the third, optional argument of get to 1 if you wish to use raw mode.
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"

Update - Connect to Pyramid Database And Still Use SQLAlchemy 更新-连接到金字塔数据库并仍然使用SQLAlchemy

The following code has been tested with Pyramid 1.6.1 and uses the MyModel class exactly as it comes from the alchemy scaffold with no additions/changes made to the model structure: 以下代码已经通过Pyramid 1.6.1进行了测试,并完全按照MyModel炼金术类支架的方式使用MyModel类,而无需对模型结构进行添加/更改:

from sqlalchemy import engine_from_config

from pyramidapp.models import (
    DBSession,
    MyModel,
)
from pyramid.paster import bootstrap
env = bootstrap('/path/to/development.ini')
settings = env['registry'].settings
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
one = DBSession.query(MyModel).first()
print("ID: %i Name: %s Value: %i " % (third.id, third.name, third.value))

Sample Output: 样本输出:

ID: 1 Name: one Value: 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM