簡體   English   中英

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

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

我需要閱讀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

我正在使用ConfigParser模塊讀取文件,但無法從INI文件讀取sqlalchemy.url參數,

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

如何從[app:main]讀取sqlalchemy.url參數?

文檔所示 ,在config對象上使用get方法

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

在我的情況下,我發現以下步驟是必需的(在更新部分中添加了使用Pyramid bootstrap功能連接到SQLAlchemy數據庫的更好示例),因為%(here)s發生在SQLite的網址位於同一文件夾中,因此,在對其他人有幫助的情況下,我將此問題添加到此問題中,尤其是因為金字塔alchemy支架默認情況下使用SQLite(具有此配置和(here)s ,和上面的答案沒有正確的我無論是工作ConfigParser ,或SafeConfigParser ,實例。我使用Python 2.7.5工作,它看起來像這樣具體涉及到的人物sqlalchemy.url通過指定額外的1需要raw_mode get命令中的參數以獲得該值。上面也提到的文檔鏈接包括有關原始模式的注釋。以下是在我的Pyramid應用程序中直接啟動的Python交互式提示符 與我的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'

還請注意,以下內容與以下命令給出了類似的錯誤消息:

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

這些是我在執行上述代碼時在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

有關文檔的特定參考,請參見以下摘錄,該摘錄更清楚地說明了這一點,並且比不使用原始模式時更易於移植:

# 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!"

更新-連接到金字塔數據庫並仍然使用SQLAlchemy

以下代碼已經通過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))

樣本輸出:

ID: 1 Name: one Value: 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM