ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2740

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

10. RENDERERS

The above configuration will use the file named foo.mak in the templates directory of the mypackage package.

The Mako template renderer can take additional arguments beyond the standard pyramid.reload_templates setting, see the Environment Variables and .ini File Settings for additional Mako Template Render Settings.

10.4 Varying Attributes of Rendered Responses

Before a response constructed by a renderer is returned to Pyramid, several attributes of the request are examined which have the potential to influence response behavior.

View callables that don’t directly return a response should use the API of the pyramid.response.Response attribute available as request.response during their execution, to influence associated response behavior.

For example, if you need to change the response status from within a view callable that uses a renderer, assign the status attribute to the response attribute of the request before returning a result:

1

2

3

4

5

6

from pyramid.view import view_config

@view_config(name=’gone’, renderer=’templates/gone.pt’) def myview(request):

request.response.status = ’404 Not Found’ return {’URL’:request.URL}

Note that mutations of request.response in views which return a Response object directly will have no effect unless the response object returned is request.response. For example, the following example calls request.response.set_cookie, but this call will have no effect, because a different Response object is returned.

1 from pyramid.response import Response

2

3 def view(request):

4request.response.set_cookie(’abc’, ’123’) # this has no effect

5return Response(’OK’) # because we’re returning a different response

If you mutate request.response and you’d like the mutations to have an effect, you must return request.response:

114

10.5. DEPRECATED MECHANISM TO VARY ATTRIBUTES OF RENDERED RESPONSES

1

2

3

def view(request): request.response.set_cookie(’abc’, ’123’) return request.response

For more information on attributes of the

request,

see

the API documentation

in

pyramid.request.

For more information on

the API

of

request.response,

see

pyramid.request.Request.response.

 

 

 

 

10.5Deprecated Mechanism to Vary Attributes of Rendered Responses

latex-warning.png

This section describes behavior deprecated in Pyramid 1.1.

In previous releases of Pyramid (1.0 and before), the request.response attribute did not exist. Instead, Pyramid required users to set special response_ -prefixed attributes of the request to influence response behavior. As of Pyramid 1.1, those request attributes are deprecated and their use will cause a deprecation warning to be issued when used. Until their existence is removed completely, we document them below, for benefit of people with older code bases.

response_content_type Defines the content-type of the resulting response, e.g. text/xml.

response_headerlist A sequence of tuples describing header values that should be set in the response, e.g. [(’Set-Cookie’, ’abc=123’), (’X-My-Header’, ’foo’)].

response_status A WSGI-style status code (e.g. 200 OK) describing the status of the response.

response_charset The character set (e.g. UTF-8) of the response.

response_cache_for A value in seconds which will influence Cache-Control and Expires headers in the returned response. The same can also be achieved by returning various values in the response_headerlist, this is purely a convenience.

115



10. RENDERERS

10.6 Adding and Changing Renderers

New templating systems and serializers can be associated with Pyramid renderer names. To this end, configuration declarations can be made which change an existing renderer factory, and which add a new renderer factory.

Renderers can be registered imperatively using the pyramid.config.Configurator.add_renderer() API.

For example, to add a renderer which renders views which have a renderer attribute that is a path that ends in .jinja2:

1 config.add_renderer(’.jinja2’, ’mypackage.MyJinja2Renderer’)

The first argument is the renderer name. The second argument is a reference to an implementation of a renderer factory or a dotted Python name referring to such an object.

10.6.1 Adding a New Renderer

You may add a new renderer by creating and registering a renderer factory.

A renderer factory implementation is typically a class with the following interface:

1 class RendererFactory:

2def __init__(self, info):

3""" Constructor: info will be an object having the

4 following attributes: name (the renderer name), package

5(the package that was ’current’ at the time the

6renderer was registered), type (the renderer type

7 name), registry (the current application registry) and

8settings (the deployment settings dictionary). """

9

10def __call__(self, value, system):

11""" Call the renderer implementation with the value

12and the system value passed in as arguments and return

13the result (a string or unicode object). The value is

14the return value of a view. The system value is a

15dictionary containing available system values

16(e.g. view, context, and request). """

116

10.6. ADDING AND CHANGING RENDERERS

The formal interface definition of the info object passed to a renderer factory constructor is available as pyramid.interfaces.IRendererInfo.

There are essentially two different kinds of renderer factories:

A renderer factory which expects to accept an asset specification, or an absolute path, as the name attribute of the info object fed to its constructor. These renderer factories are registered with a name value that begins with a dot (.). These types of renderer factories usually relate to a file on the filesystem, such as a template.

A renderer factory which expects to accept a token that does not represent a filesystem path or an asset specification in the name attribute of the info object fed to its constructor. These renderer factories are registered with a name value that does not begin with a dot. These renderer factories are typically object serializers.

Asset Specifications

An asset specification is a colon-delimited identifier for an asset. The colon separates a Python package name from a package subpath. For example, the asset specification my.package:static/baz.css identifies the file named baz.css in the static subdirectory of the my.package Python package.

Here’s an example of the registration of a simple renderer factory via add_renderer():

1

2

3

# config is an instance of pyramid.config.Configurator

config.add_renderer(name=’amf’, factory=’my.package.MyAMFRenderer’)

Adding the above code to your application startup configuration will allow you to use the my.package.MyAMFRenderer renderer factory implementation in view configurations. Your application can use this renderer by specifying amf in the renderer attribute of a view configuration:

1

2

3

4

5

from pyramid.view import view_config

@view_config(renderer=’amf’) def myview(request):

return {’Hello’:’world’}

At startup time, when a view configuration is encountered, which has a name attribute that does not contain a dot, the full name value is used to construct a renderer from the associated renderer factory. In this case, the view configuration will create an instance of an MyAMFRenderer for each view configuration

117


10. RENDERERS

which includes amf as its renderer value. The name passed to the MyAMFRenderer constructor will always be amf.

Here’s an example of the registration of a more complicated renderer factory, which expects to be passed a filesystem path:

1 config.add_renderer(name=’.jinja2’,

2

factory=’my.package.MyJinja2Renderer’)

Adding the above code to your application startup will allow you to use the my.package.MyJinja2Renderer renderer factory implementation in view configurations by referring to any renderer which ends in .jinja in the renderer attribute of a view configuration:

1

2

3

4

5

from pyramid.view import view_config

@view_config(renderer=’templates/mytemplate.jinja2’) def myview(request):

return {’Hello’:’world’}

When a view configuration is encountered at startup time, which has a name attribute that does contain a dot, the value of the name attribute is split on its final dot. The second element of the split is typically the filename extension. This extension is used to look up a renderer factory for the configured view. Then the value of renderer is passed to the factory to create a renderer for the view. In this case, the view configuration will create an instance of a MyJinja2Renderer for each view configuration which includes anything ending with .jinja2 in its renderer value. The name passed to the MyJinja2Renderer constructor will be the full value that was set as renderer= in the view configuration.

10.6.2 Changing an Existing Renderer

You can associate more than one filename extension with the same existing renderer implementation as necessary if you need to use a different file extension for the same kinds of templates. For example, to associate the .zpt extension with the Chameleon ZPT renderer factory, use the pyramid.config.Configurator.add_renderer() method:

1 config.add_renderer(’.zpt’, ’pyramid.chameleon_zpt.renderer_factory’)

After you do this, Pyramid will treat templates ending in both the .pt and .zpt filename extensions as Chameleon ZPT templates.

To change the default mapping in which files with a .pt extension are rendered via a Chameleon ZPT page template renderer, use a variation on the following in your application’s startup code:

118