【问题标题】:Python and Pyramid -reading a ini file in python using configparserPython 和 Pyramid - 使用 configparser 在 python 中读取 ini 文件
【发布时间】:2014-01-03 18:48:04
【问题描述】:

我需要在 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参数?

【问题讨论】:

    标签: python sqlalchemy pyramid configparser


    【解决方案1】:

    作为the documentation shows,在您的config 对象上使用get 方法

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

    【讨论】:

      【解决方案2】:

      在我的情况下,我发现以下是必要的(在更新部分中使用 Pyramid bootstrap 功能连接到 SQLAlchemy 数据库的更好示例)添加到此问题的底部,因为 %(here)s 出现在同一文件夹中 SQLite 的 url 中,所以我在这个问题中添加了这个答案,以防这对其他人有帮助,特别是因为 Pyramid alchemy 脚手架使用 SQLite默认情况下(使用此配置和 (here)s,上面的答案对我来说不适用于 ConfigParserSafeConfigParser 实例。我正在使用 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        • 2021-08-03
        • 2021-01-13
        • 1970-01-01
        相关资源
        最近更新 更多