ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 02.01.2026
Просмотров: 2685
Скачиваний: 0
17. ENVIRONMENT VARIABLES AND .INI FILE SETTINGS
17.12 Mako Template Render Settings
Mako derives additional settings to configure its template renderer that should be set when using it. Many of these settings are optional and only need to be set if they should be different from the default. The Mako Template Renderer uses a subclass of Mako’s template lookup and accepts several arguments to configure it.
17.12.1 Mako Directories
The value(s) supplied here are passed in as the template directories. They should be in asset specification format, for example: my.package:templates.
Config File Setting Name
mako.directories
17.12.2 Mako Module Directory
The value supplied here tells Mako where to store compiled Mako templates. If omitted, compiled templates will be stored in memory. This value should be an absolute path, for example: %(here)s/data/templates would use a directory called data/templates in the same parent directory as the INI file.
Config File Setting Name
mako.module_directory
17.12.3 Mako Input Encoding
The encoding that Mako templates are assumed to have. By default this is set to utf-8. If you wish to use a different template encoding, this value should be changed accordingly.
Config File Setting Name
mako.input_encoding
190
17.12. MAKO TEMPLATE RENDER SETTINGS
17.12.4 Mako Error Handler
A callable (or a dotted Python name which names a callable) which is called whenever Mako compile or runtime exceptions occur. The callable is passed the current context as well as the exception. If the callable returns True, the exception is considered to be handled, else it is re-raised after the function completes. Is used to provide custom error-rendering functions.
Config File Setting Name
mako.error_handler
17.12.5 Mako Default Filters
List of string filter names that will be applied to all Mako expressions.
Config File Setting Name
mako.default_filters
17.12.6 Mako Import
String list of Python statements, typically individual “import” lines, which will be placed into the module level preamble of all generated Python modules.
Config File Setting Name
mako.imports
17.12.7 Mako Strict Undefined
true or false, representing the “strict undefined” behavior of Mako (see Mako Context Variables). By default, this is false.
Config File Setting Name
mako.strict_undefined
191
17. ENVIRONMENT VARIABLES AND .INI FILE SETTINGS
17.12.8 Mako Preprocessor
A callable (or a dotted Python name which names a callable) which is called to preprocess the source before the template is called. The callable will be passed the full template source before it is parsed. The return result of the callable will be used as the template source code.
latex-note.png
This feature is new in Pyramid 1.1.
Config File Setting Name
mako.preprocessor
17.13 Examples
Let’s presume your configuration file is named MyProject.ini, and there is a section representing your application named [app:main] within the file that represents your Pyramid application. The configuration file settings documented in the above “Config File Setting Name” column would go in the [app:main] section. Here’s an example of such a section:
1
2
3
4
[app:main]
use = egg:MyProject pyramid.reload_templates = true pyramid.debug_authorization = true
You can also use environment variables to accomplish the same purpose for settings documented as such. For example, you might start your Pyramid application using the following command line:
$ PYRAMID_DEBUG_AUTHORIZATION=1 PYRAMID_RELOAD_TEMPLATES=1 \ bin/paster serve MyProject.ini
If you started your application this way, your Pyramid application would behave in the same manner as if you had placed the respective settings in the [app:main] section of your application’s .ini file.
192
17.14. UNDERSTANDING THE DISTINCTION BETWEEN RELOAD_TEMPLATES AND
RELOAD_ASSETS
If you want to turn all debug settings (every setting that starts with pyramid.debug_). on in one fell swoop, you can use PYRAMID_DEBUG_ALL=1 as an environment variable setting or you may use pyramid.debug_all=true in the config file. Note that this does not affect settings that do not start with pyramid.debug_* such as pyramid.reload_templates.
If you want to turn all pyramid.reload settings (every setting that starts with pyramid.reload_) on in one fell swoop, you can use PYRAMID_RELOAD_ALL=1 as an environment variable setting or you may use pyramid.reload_all=true in the config file. Note that this does not affect settings that do not start with pyramid.reload_* such as pyramid.debug_notfound.
latex-note.png
Specifying configuration settings via environment variables is generally most useful during development, where you may wish to augment or override the more permanent settings in the configuration file. This is useful because many of the reload and debug settings may have performance or security (i.e., disclosure) implications that make them undesirable in a production environment.
17.14Understanding the Distinction Between reload_templates and reload_assets
The difference between pyramid.reload_assets and pyramid.reload_templates is a bit subtle. Templates are themselves also treated by Pyramid as asset files (along with other static files), so the distinction can be confusing. It’s helpful to read Overriding Assets for some context about assets in general.
When pyramid.reload_templates is true, Pyramid takes advantage of the underlying templating systems’ ability to check for file modifications to an individual template file. When pyramid.reload_templates is true but pyramid.reload_assets is not true, the template filename returned by the pkg_resources package (used under the hood by asset resolution) is cached by Pyramid on the first request. Subsequent requests for the same template file will return a cached template filename. The underlying templating system checks for modifications to this particular file for every request. Setting pyramid.reload_templates to True doesn’t affect performance dramatically (although it should still not be used in production because it has some effect).
193
17. ENVIRONMENT VARIABLES AND .INI FILE SETTINGS
However, when pyramid.reload_assets is true, Pyramid will not cache the template filename, meaning you can see the effect of changing the content of an overridden asset directory for templates without restarting the server after every change. Subsequent requests for the same template file may return different filenames based on the current state of overridden asset directories. Setting pyramid.reload_assets to True affects performance dramatically, slowing things down by an order of magnitude for each template rendering. However, it’s convenient to enable when moving files around in overridden asset directories. pyramid.reload_assets makes the system very slow when templates are in use. Never set pyramid.reload_assets to True on a production system.
17.15 Adding A Custom Setting
From time to time, you may need to add a custom setting to your application. Here’s how:
•If you’re using an .ini file, change the .ini file, adding the setting to the [app:foo] section representing your Pyramid application. For example:
[app:main]
# .. other settings debug_frobnosticator = True
•In the main() function that represents the place that your Pyramid WSGI application is created, anticipate that you’ll be getting this key/value pair as a setting and do any type conversion necessary.
If you’ve done any type conversion of your custom value, reset the converted values into the settings dictionary before you pass the dictionary as settings to the Configurator. For example:
def main(global_config, **settings):
# ...
from pyramid.settings import asbool debug_frobnosticator = asbool(settings.get(
’debug_frobnosticator’, ’false’)) settings[’debug_frobnosticator’] = debug_frobnosticator config = Configurator(settings=settings)
194
17.15. ADDING A CUSTOM SETTING
latex-note.png
It’s especially important that you mutate the settings dictionary with the converted version of the variable before passing it to the Configurator: the configurator makes a copy of settings, it doesn’t use the one you pass directly.
•When creating an includeme function that will be later added to your application’s configuration you may access the settings dictionary through the instance of the Configurator that is passed into the function as its only argument. For Example:
def includeme(config):
settings = config.registry.settings debug_frobnosticator = settings[’debug_frobnosticator’]
•In the runtime code that you need to access the new settings value, find the value in the registry.settings dictionary and use it. In view code (or any other code that has access to the request), the easiest way to do this is via request.registry.settings. For example:
settings = request.registry.settings debug_frobnosticator = settings[’debug_frobnosticator’]
If you wish to use the value in code that does not have access to the request and you wish to use the value, you’ll need to use the pyramid.threadlocal.get_current_registry() API to obtain the current registry, then ask for its settings attribute. For example:
registry = pyramid.threadlocal.get_current_registry() settings = registry.settings
debug_frobnosticator = settings[’debug_frobnosticator’]
195
17. ENVIRONMENT VARIABLES AND .INI FILE SETTINGS
196
CHAPTER
EIGHTEEN
LOGGING
Pyramid allows you to make use of the Python standard library logging module. This chapter describes how to configure logging and how to send log messages to loggers that you’ve configured.
latex-warning.png
This chapter assumes you’ve used a scaffold to create a project which contains development.ini and production.ini files which help configure logging. All of the scaffolds which ship along with Pyramid do this. If you’re not using a scaffold, or if you’ve used a third-party scaffold which does not create these files, the configuration information in this chapter will not be applicable.
18.1 Logging Configuration
A Pyramid project created from a scaffold is configured to allow you to send messages to Python standard library logging package loggers from within your application. In particular, the PasteDeploy development.ini and production.ini files created when you use a scaffold include a basic configuration for the Python logging package.
PasteDeploy .ini files use the Python standard library ConfigParser format; this the same format used as the Python logging module’s Configuration file format. The application-related and logging-related
197
18. LOGGING
sections in the configuration file can coexist peacefully, and the logging-related sections in the file are used from when you run pserve.
The pserve command calls the logging.fileConfig function using the specified ini file if it contains a [loggers] section (all of the scaffold-generated .ini files do). logging.fileConfig reads the logging configuration from the ini file upon which pserve was invoked.
Default logging configuration is provided in both the default development.ini and the production.ini file. The logging configuration in the development.ini file is as follows:
1 |
# Begin logging configuration |
2 |
|
3 |
[loggers] |
4 |
keys = root, {{package_logger}} |
5 |
|
6 |
[handlers] |
7 |
keys = console |
8 |
|
9 |
[formatters] |
10 |
keys = generic |
11 |
|
12[logger_root]
13level = INFO
14handlers = console
15
16[logger_{{package_logger}}]
17level = DEBUG
18handlers =
19qualname = {{package}}
20
21[handler_console]
22class = StreamHandler
23args = (sys.stderr,)
24level = NOTSET
25formatter = generic
26
27[formatter_generic]
28format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s
29
30 # End logging configuration
The production.ini file uses the WARN level in its logger configuration, but it is otherwise identical.
The name {{package_logger}} above will be replaced with the name of your project’s package, which is derived from the name you provide to your project. For instance, if you do:
198