简体   繁体   中英

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:

[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,

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

How do I read the sqlalchemy.url parameter from the [app:main] ?

文档所示 ,在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 t the same location as my development.ini (primarily the 4th row shows the difference):

>>> 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:

>>> 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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