Django-Style "settings.py" Configuration¶
If you enjoy accessing global configuration via import statements ala
settings.py, you can do something similar in Pyramid.
settings.pyfile in your application's package (for example, if your application is named "myapp", put it in the filesystem directory named
myapp; the one with an
Add values to it at its top level.
# settings.py import pytz timezone = pytz('US/Eastern')
Then simply import the module into your application:
1from myapp import settings 2 3def myview(request): 4 timezone = settings.timezone 5 return Response(timezone.zone)
This is all you really need to do if you just want some global configuration values for your application.
However, more frequently, values in your
settings.py file need to be
conditionalized based on deployment settings. For example, the timezone
above is different between development and deployment. In order to
conditionalize the values in your
settings.py you can use other values
from the Pyramid
production.ini. To do so,
settings.py might instead do this:
1import os 2 3ini = os.environ['PYRAMID_SETTINGS'] 4config_file, section_name = ini.split('#', 1) 5 6from paste.deploy.loadwsgi import appconfig 7config = appconfig('config:%s' % config_file, section_name) 8 9import pytz 10 11timezone = pytz.timezone(config['timezone'])
The value of
config in the above snippet will be a dictionary
representing your application's
development.ini configuration section.
For example, for the above code to work, you'll need to add a
key/value pair to a section of your
[app:myapp] use = egg:MyApp timezone = US/Eastern
settings.py is written like this, before starting Pyramid, ensure
you have an OS environment value (akin to Django's
/place/to/development.ini is the full path to the ini file.
the section name in the config file that represents your app
[app:myapp]). In the above example, your application will refuse
to start without this environment variable being present.