15

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

Community
  • 1
  • 1
Tallmad
  • 1,951
  • 4
  • 22
  • 29

3 Answers3

26

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.

madjar
  • 12,691
  • 2
  • 44
  • 52
  • 1
    Thanks. Edited to make it clearer in the answer. By the way, the registry is not the setting file (see http://pyramid.readthedocs.org/en/1.3-branch/glossary.html#term-application-registry ). – madjar Jun 05 '12 at 14:21
  • Note that to add a custom setting and using this answer you can't add it in a new section. You need to add it to the existing [app:main] section. See [the documentation](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html#adding-a-custom-setting). – Zitrax May 03 '16 at 19:22
3

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

dm03514
  • 54,664
  • 18
  • 108
  • 145
-2

Think 'python' rather than 'pyramid'.

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('development.ini')
db_url = config.get('app:main', 'sqlalchemy.url')
noisyboiler
  • 221
  • 1
  • 3
  • 10