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

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

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

Добавлен: 02.01.2026

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

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

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

29.5.ADDING RENDERER GLOBALS (DEPRECATED)

29.5Adding Renderer Globals (Deprecated)

latex-warning.png

this feature is deprecated as of Pyramid 1.1. A non-deprecated mechanism which allows event subscribers to add renderer global values is documented in Using The Before Render Event.

Whenever Pyramid handles a request to perform a rendering (after a view with a renderer= configuration attribute is invoked, or when any of the methods beginning with render within the pyramid.renderers module are called), renderer globals can be injected into the system values sent to the renderer. By default, no renderer globals are injected, and the “bare” system values (such as request, context, view, and renderer_name) are the only values present in the system dictionary passed to every renderer.

A callback that Pyramid will call every time a renderer is invoked can be added by passing a renderer_globals_factory argument to the constructor of the configurator. This callback can either be a callable object or a dotted Python name representing such a callable.

1 def renderer_globals_factory(system):

2return {’a’: 1}

3

4 config = Configurator(

5renderer_globals_factory=renderer_globals_factory)

Such a callback must accept a single positional argument (notionally named system) which will contain the original system values. It must return a dictionary of values that will be merged into the system dictionary. See System Values Used During Rendering for description of the values present in the system dictionary.

If you’re doing imperative configuration, and you’d rather do it after you’ve already constructed a configurator it can also be registered via the pyramid.config.Configurator.set_renderer_globals_factory() method:

1

2

3

from pyramid.config import Configurator

def renderer_globals_factory(system):

323

29. USING HOOKS

4return {’a’: 1}

5

 

6

config = Configurator()

7

config.set_renderer_globals_factory(renderer_globals_factory)

29.6 Using Response Callbacks

Unlike many other web frameworks, Pyramid does not eagerly create a global response object. Adding a response callback allows an application to register an action to be performed against whatever response object is returned by a view, usually in order to mutate the response.

The pyramid.request.Request.add_response_callback() method is used to register a response callback.

A response callback is a callable which accepts two positional parameters: request and response. For example:

1

2

3

4

5

def cache_callback(request, response):

"""Set the cache_control max_age for the response""" if request.exception is not None:

response.cache_control.max_age = 360 request.add_response_callback(cache_callback)

No response callback is called if an unhandled exception happens in application code, or if the response object returned by a view callable is invalid. Response callbacks are, however, invoked when a exception view is rendered successfully: in such a case, the request.exception attribute of the request when it enters a response callback will be an exception object instead of its default value of None.

Response callbacks are called in the order they’re added (first-to-most-recently-added). All response callbacks are called after the NewResponse event is sent. Errors raised by response callbacks are not handled specially. They will be propagated to the caller of the Pyramid router application.

A response callback has a lifetime of a single request. If you want a response callback to happen as the result of every request, you must re-register the callback into every new request (perhaps within a subscriber of a NewRequest event).

324



29.7. USING FINISHED CALLBACKS

29.7 Using Finished Callbacks

A finished callback is a function that will be called unconditionally by the Pyramid router at the very end of request processing. A finished callback can be used to perform an action at the end of a request unconditionally.

The pyramid.request.Request.add_finished_callback() method is used to register a finished callback.

A finished callback is a callable which accepts a single positional parameter: request. For example:

1

import logging

2

 

3

log = logging.getLogger(__name__)

4

 

5

def log_callback(request):

6

"""Log information at the end of request"""

7log.debug(’Request is finished.’)

8 request.add_finished_callback(log_callback)

Finished callbacks are called in the order they’re added (first-to-most-recently-added). Finished callbacks (unlike a response callback) are always called, even if an exception happens in application code that prevents a response from being generated.

The set of finished callbacks associated with a request are called very late in the processing of that request; they are essentially the very last thing called by the router before a request “ends”. They are called after response processing has already occurred in a top-level finally: block within the router request processing code. As a result, mutations performed to the request provided to a finished callback will have no meaningful effect, because response processing will have already occurred, and the request’s scope will expire almost immediately after all finished callbacks have been processed.

Errors raised by finished callbacks are not handled specially. They will be propagated to the caller of the Pyramid router application.

A finished callback has a lifetime of a single request. If you want a finished callback to happen as the result of every request, you must re-register the callback into every new request (perhaps within a subscriber of a NewRequest event).

325

29. USING HOOKS

29.8 Changing the Traverser

The default traversal algorithm that Pyramid uses is explained in The Traversal Algorithm. Though it is rarely necessary, this default algorithm can be swapped out selectively for a different traversal pattern via configuration.

1

2

3

4

from pyramid.config import Configurator from myapp.traversal import Traverser config = Configurator() config.add_traverser(Traverser)

In the example above, myapp.traversal.Traverser is assumed to be a class that implements the following interface:

1 class Traverser(object):

2def __init__(self, root):

3""" Accept the root object returned from the root factory """

4

5def __call__(self, request):

6""" Return a dictionary with (at least) the keys ‘‘root‘‘,

7‘‘context‘‘, ‘‘view_name‘‘, ‘‘subpath‘‘, ‘‘traversed‘‘,

8

‘‘virtual_root‘‘, and ‘‘virtual_root_path‘‘. These values are

9typically the result of a resource tree traversal. ‘‘root‘‘

10is the physical root object, ‘‘context‘‘ will be a resource

11object, ‘‘view_name‘‘ will be the view name used (a Unicode

12name), ‘‘subpath‘‘ will be a sequence of Unicode names that

13followed the view name but were not traversed, ‘‘traversed‘‘

14will be a sequence of Unicode names that were traversed

15(including the virtual root path, if any) ‘‘virtual_root‘‘

16will be a resource object representing the virtual root (or the

17physical root if traversal was not performed), and

18‘‘virtual_root_path‘‘ will be a sequence representing the

19virtual root path (a sequence of Unicode names) or None if

20traversal was not performed.

21

22Extra keys for special purpose functionality can be added as

23necessary.

24

25All values returned in the dictionary will be made available

26as attributes of the ‘‘request‘‘ object.

27"""

More than one traversal algorithm can be active at the same time. For instance, if your root factory returns more than one type of object conditionally, you could claim that an alternate traverser adapter is “for” only

326


29.9. CHANGING HOW PYRAMID.REQUEST.REQUEST.RESOURCE_URL() GENERATES A URL

one particular class or interface. When the root factory returned an object that implemented that class or interface, a custom traverser would be used. Otherwise, the default traverser would be used. For example:

1

2

3

4

5

from myapp.traversal import Traverser from myapp.resources import MyRoot

from pyramid.config import Configurator config = Configurator() config.add_traverser(Traverser, MyRoot)

If the above stanza was added to a Pyramid __init__.py file’s main function, Pyramid would use the myapp.traversal.Traverser only when the application root factory returned an instance of the myapp.resources.MyRoot object. Otherwise it would use the default Pyramid traverser to do traversal.

29.9Changing How pyramid.request.Request.resource_url()

Generates a URL

When you add a traverser as described in Changing the Traverser, it’s often convenient to continue to use the pyramid.request.Request.resource_url() API. However, since the way traversal is done will have been modified, the URLs it generates by default may be incorrect when used against resources derived from your custom traverser.

If you’ve added a traverser, you can change how resource_url() generates a URL for a specific type of resource by adding a call to pyramid.config.add_resource_url_adapter().

For example:

1

2

3

4

from myapp.traversal import ResourceURLAdapter from myapp.resources import MyRoot

config.add_resource_url_adapter(ResourceURLAdapter, MyRoot)

In the above example, the myapp.traversal.ResourceURLAdapter class will be used to provide services to resource_url() any time the resource passed to resource_url is of the class myapp.resources.MyRoot. The resource_iface argument MyRoot represents the type of interface that must be possessed by the resource for this resource url factory to be found. If the resource_iface argument is omitted, this resource url adapter will be used for all resources.

The API that must be implemented by your a class that provides IResourceURL is as follows:

327


29. USING HOOKS

1 class MyResourceURL(object):

2""" An adapter which provides the virtual and physical paths of a

3resource

4"""

5def __init__(self, resource, request):

6""" Accept the resource and request and set self.physical_path and

7self.virtual_path"""

8self.virtual_path = some_function_of(resource, request)

9self.physical_path = some_other_function_of(resource, request)

The default context URL generator is available for perusal as the class pyramid.traversal.ResourceURL in the traversal module of the Pylons GitHub Pyramid repository.

See pyramid.config.add_resource_url_adapter() for more information.

29.10 Changing How Pyramid Treats View Responses

It is possible to control how Pyramid treats the result of calling a view callable on a per-type basis by using a hook involving pyramid.config.Configurator.add_response_adapter() or the response_adapter decorator.

latex-note.png

This feature is new as of Pyramid 1.1.

Pyramid, in various places, adapts the result of calling a view callable to the IResponse interface to ensure that the object returned by the view callable is a “true” response object. The vast majority of time, the result of this adaptation is the result object itself, as view callables written by “civilians” who read the narrative documentation contained in this manual will always return something that implements the IResponse interface. Most typically, this will be an instance of the pyramid.response.Response class or a subclass. If a civilian returns a non-Response object from a view callable that isn’t configured to use a renderer, he will typically expect the router to raise an error. However, you can hook Pyramid in such a way that users can return arbitrary values from a view callable by providing an adapter which converts the arbitrary return value into something that implements

IResponse.

328

29.10. CHANGING HOW PYRAMID TREATS VIEW RESPONSES

For example, if you’d like to allow view callables to return bare string objects (without requiring a a renderer to convert a string to a response object), you can register an adapter which converts the string to a Response:

1 from pyramid.response import Response

2

3 def string_response_adapter(s):

4 response = Response(s)

5return response

6

7 # config is an instance of pyramid.config.Configurator

8

9 config.add_response_adapter(string_response_adapter, str)

Likewise, if you want to be able to return a simplified kind of response object from view callables, you can use the IResponse hook to register an adapter to the more complex IResponse interface:

1 from pyramid.response import Response

2

3 class SimpleResponse(object):

4 def __init__(self, body):

5self.body = body

6

7 def simple_response_adapter(simple_response): 8 response = Response(simple_response.body)

9return response

10

11 # config is an instance of pyramid.config.Configurator

12

13 config.add_response_adapter(simple_response_adapter, SimpleResponse)

If you want to implement your own Response object instead of using the pyramid.response.Response object in any capacity at all, you’ll have to make sure the object implements every attribute and method outlined in pyramid.interfaces.IResponse and you’ll have to ensure that it uses zope.interface.implementer(IResponse) as a class decoratoror.

1

from pyramid.interfaces import IResponse

2

from zope.interface import implementer

3

 

4

@implementer(IResponse)

5

class MyResponse(object):

6

# ... an implementation of every method and attribute

7

# documented in IResponse should follow ...

 

 

329