Pyramid settings from buildout

Tags: buildout, pyramid

I’m currently experimenting with a pyramid site at work. One of the things I wondered about was how to get settings I normally configure in my Buildout configuration into my Pyramid code. Probably I’d have to generate Pyramid’s .ini file from a template and see how I could access that from my code.

Yesterday I noticed a question on stackoverflow about that very same problem. And Martijn Pieters (wow, 68k stackoverflow score) already pointed at the generate-from-a-template solution. A good reason to figure out how to actually get at such a setting from within my Pyramid Python code! So I wrote an answer.

Let’s work our way backwards to what you need. First in your view code where you want the buildout directory:

def your_view(request):
    buildout_dir = request.registry.settings['buildout_dir']
    ....

request.registry.settings (see documentation) is a “dictonary-like deployment settings object”. That’s the **settings that gets passed into your main method like def main(global_config, **settings).

Those settings are what’s in the [app:main] part of your deployment.ini or production.ini file. So add the buildout directory there:

[app:main]
use = egg:your_app

buildout_dir = /home/you/wherever/it/is

pyramid.reload_templates = true
pyramid.debug_authorization = false
...

But, and this is the last step, you don’t want to have that hardcoded path in there. So generate the .ini with a template and collective.recipe.template. Collective.recipe.template uses a ${partname:variable}-like expansion language. In your case you need ${buildout:directory}. Rename development.ini to development.ini.in and change the indicated line:

[app:main]
use = egg:your_app

buildout_dir = ${buildout:dir}
#              ^^^^^^^^^^^^^^^

pyramid.reload_templates = true
pyramid.debug_authorization = false
...

Add a buildout part in buildout.cfg to generate development.ini from that development.ini.in template you just created:

[buildout]
...
parts =
    ...
    inifile
    ...

[inifile]
recipe = collective.recipe.template
input = ${buildout:directory}/development.ini.in
output = ${buildout:directory}/development.ini

Note that you can do all sorts of cool stuff with collective.recipe.template. ${serverconfig:portnumber} to generate a matching port number in your production.ini and at the same in your your_site_name.nginx.conf, for instance. Perfect application of the DRY principle: Don’t repeat yourself. Have fun!

 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):