问题
There is a development.ini or production.ini in a pyramid project. I add my own config data in the ini files like:
[thrift]
host = 0.0.0.0
port = 8080
and I want to use the config data in one of py files in the project. How can I get the data without the request object? (I've seen a solution which uses request.)
回答1:
You can access the settings at request.registry.settings
or pyramid.threadlocal.get_current_registry().settings
. It behaves like dictionary.
If you want to use the second one, that is getting the settings without having the request, I have to warn you. According to the doc :
This function should be used extremely sparingly, usually only in unit testing code. it’s almost always usually a mistake to use get_current_registry outside a testing context because its usage makes it possible to write code that can be neither easily tested nor scripted.
Any part of your code that needs access to the settings is part of the web application, and should access the request, not some magically accessible global. You might think you have a good reason, but there's probably a better way. If you want to discuss that (maybe in another question if it's complex, as some code would help), I'll be glad to help you find a clean way to do it.
回答2:
Whenever I wonder how to do something in pyramid I usually refer to one of the pyramid examples on github.
Parsing Example Pyramid Config
I don't know how "pyrmadic" they are but they usaully work fine. Here they just use ConfigParser
just as you would in any python project to parse your .ini files
回答3:
Think 'python' rather than 'pyramid'.
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('development.ini')
db_url = config.get('app:main', 'sqlalchemy.url')
来源:https://stackoverflow.com/questions/10893628/how-can-i-get-the-ini-data-in-pyramid