Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

29.3. CHANGING THE REQUEST FACTORY

1

2

3

4

5

from pyramid.view import view_config from pyramid.response import Response

def forbidden_view(request): return Response(’forbidden’)

latex-note.png

When a forbidden view callable is invoked, it is passed a request. The exception attribute of the request will be an instance of the HTTPForbidden exception that caused the forbidden view to be called. The value of request.exception.message will be a value explaining why the forbidden was raised and request.exception.result will be extended information about the forbidden exception. These messages will be different when the pyramid.debug_authorization environment setting is true than it is when it is false.

29.3 Changing the Request Factory

Whenever Pyramid handles a request from a WSGI server, it creates a request object based on the WSGI environment it has been passed. By default, an instance of the pyramid.request.Request class is created to represent the request object.

The class (aka “factory”) that Pyramid uses to create a request object instance can be changed by passing a request_factory argument to the constructor of the configurator. This argument can be either a callable or a dotted Python name representing a callable.

1 from pyramid.request import Request

2

3 class MyRequest(Request):

4pass

5

6 config = Configurator(request_factory=MyRequest)

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_request_factory() method:

321

29. USING HOOKS

1

from pyramid.config import Configurator

2

from pyramid.request import Request

3

 

4

class MyRequest(Request):

5

pass

6

 

7

config = Configurator()

8

config.set_request_factory(MyRequest)

 

 

29.4 Using The Before Render Event

Subscribers to the pyramid.events.BeforeRender event may introspect and modify the set of renderer globals before they are passed to a renderer. This event object iself has a dictionary-like interface that can be used for this purpose. For example:

1

2

3

4

5

6

from pyramid.events import subscriber from pyramid.events import BeforeRender

@subscriber(BeforeRender) def add_global(event):

event[’mykey’] = ’foo’

An object of this type is sent as an event just before a renderer is invoked (but after the application-level renderer globals factory added via set_renderer_globals_factory, if any, has injected its own keys into the renderer globals dictionary).

If a subscriber attempts to add a key that already exist in the renderer globals dictionary, a KeyError is raised. This limitation is enforced because event subscribers do not possess any relative ordering. The set of keys added to the renderer globals dictionary by all pyramid.events.BeforeRender subscribers and renderer globals factories must be unique.

See the API documentation for the BeforeRender event interface at pyramid.interfaces.IBeforeRender.

Another (deprecated) mechanism which allows event subscribers more control when adding renderer global values exists in Adding Renderer Globals (Deprecated).

322

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

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]