在我的情况下,我发现以下是必要的(在更新部分中使用 Pyramid bootstrap 功能连接到 SQLAlchemy 数据库的更好示例)添加到此问题的底部,因为 %(here)s 出现在同一文件夹中 SQLite 的 url 中,所以我在这个问题中添加了这个答案,以防这对其他人有帮助,特别是因为 Pyramid alchemy 脚手架使用 SQLite默认情况下(使用此配置和 (here)s,上面的答案对我来说不适用于 ConfigParser 或 SafeConfigParser 实例。我正在使用 Python 2.7.5 并且看起来这与 sqlalchemy.url 中的字符特别相关,需要 raw_mode 通过在 get 命令中指定附加 1 参数来获取此值上面也提到了documentation link,里面有关于raw模式的注释,以下来自Pytho在我的 Pyramid 应用程序中直接在与我的 development.ini 相同的位置启动了交互式提示(主要是第 4 行显示了差异):
>>> 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!"
更新 - 连接到 Pyramid 数据库并仍然使用 SQLAlchemy
以下代码已在 Pyramid 1.6.1 中进行了测试,并完全按照来自炼金术脚手架的 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