Django-Style "settings.py" Configuration

settings.py

  • 创建一个 settings.py myapp ; the one with an __init__.py 在里面。

  • 在其顶层向其添加值。

例如::

# settings.py
import pytz

timezone = pytz('US/Eastern')

然后简单地将模块导入应用程序:

1from myapp import settings
2
3def myview(request):
4    timezone = settings.timezone
5    return Response(timezone.zone)

如果您只需要一些应用程序的全局配置值,那么这就是您真正需要做的全部工作。

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 你可以用 other values from the Pyramid development.iniproduction.ini . 这样做,你的 settings.py

 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'])

价值 config in the above snippet will be a dictionary representing your application's development.ini timezone development.ini ::

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

export PYRAMID_SETTINGS=/place/to/development.ini#myapp

/place/to/development.ini myapp is the section name in the config file that represents your app (e.g. [app:myapp] )In the above example, your application will refuse to start without this environment variable being present.