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

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

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

Добавлен: 02.01.2026

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

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

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

44. PYRAMID.CONFIG

config.add_traverser(MyCustomTraverser, MyRootClass)

When more than one traverser is active, the “most specific” traverser will be used (the one that matches the class or interface of the value returned by the root factory most closely).

Note that either adapter or iface can be a dotted Python name or a Python object.

See Changing the Traverser for more information.

add_tween(tween_factory, under=None, over=None)

latex-note.png

This feature is new as of Pyramid 1.2.

Add a ‘tween factory’. A tween (a contraction of ‘between’) is a bit of code that sits between the Pyramid router’s main request handling function and the upstream WSGI component that uses Pyramid as its ‘app’. Tweens are a feature that may be used by Pyramid framework extensions, to provide, for example, Pyramid-specific view timing support, bookkeeping code that examines exceptions before they are returned to the upstream WSGI application, or a variety of other features. Tweens behave a bit like WSGI ‘middleware’ but they have the benefit of running in a context in which they have access to the Pyramid application registry as well as the Pyramid rendering machinery.

latex-note.png

You can view the tween ordering configured into a given Pyramid application by using the ptweens command. See

Displaying “Tweens”.

550

The tween_factory argument must be a dotted Python name to a global object representing the tween factory.

The under and over arguments allow the caller of add_tween to provide a hint about where in the tween chain this tween factory should be placed when an implicit tween chain is used. These hints are only used when an explicit tween chain is not used (when the pyramid.tweens configuration value is not set). Allowable values for under or over (or both) are:

•None (the default).

•A dotted Python name to a tween factory: a string representing the dotted name of a tween factory added in a call to add_tween in the same configuration session.

•One of the constants pyramid.tweens.MAIN, pyramid.tweens.INGRESS, or pyramid.tweens.EXCVIEW. •An iterable of any combination of the above. This allows the user to specify fallbacks if the desired tween is not included, as well as compatibility with multiple other tweens.

under means ‘closer to the main Pyramid application than’, over means ‘closer to the request ingress than’.

For example, calling add_tween(’myapp.tfactory’, over=pyramid.tweens.MAIN) will attempt to place the tween

factory

represented

by the dotted name myapp.tfactory di-

rectly ‘above’ (in

ptweens order) the main Pyramid request

handler.

Likewise,

calling add_tween(’myapp.tfactory’,

over=pyramid.tweens.MAIN, under=’mypkg.someothertween’) will attempt to place this tween factory ‘above’ the main handler but ‘below’ (a fictional) ‘mypkg.someothertween’ tween factory.

If all options for under (or over) cannot be found in the current

configuration, it is an error.

If some options are specified purely

for compatibilty with other

tweens, just add a fallback of MAIN

or INGRESS. For example, under=(’mypkg.someothertween’, ’mypkg.someothertween2’, INGRESS). This constraint will require the tween to be located under both the ‘mypkg.someothertween’ tween, the ‘mypkg.someothertween2’ tween, and INGRESS. If any of these is not in the current configuration, this constraint will only organize itself based on the tweens that are present.

Specifying neither over nor under is equivalent to specifying under=INGRESS.

Implicit tween ordering is obviously only best-effort. Pyramid will attempt to present an implicit order of tweens as best it can, but the only surefire

551


44. PYRAMID.CONFIG

way to get any particular ordering is to use an explicit tween order. A user may always override the implicit tween ordering by using an explicit pyramid.tweens configuration value setting.

under, and over arguments are ignored when an explicit tween chain is specified using the pyramid.tweens configuration value.

For more information, see Registering “Tweens”.

set_request_factory(factory)

The object passed as factory should be an object (or a dotted Python name which refers to an object) which will be used by the Pyramid router to create all request objects. This factory object must have the same methods and attributes as the pyramid.request.Request class (particularly __call__, and blank).

See pyramid.config.Configurator.set_request_property() for a less intrusive way to extend the request objects with custom properties.

latex-note.png

Using the request_factory argument to the pyramid.config.Configurator constructor can be used to achieve the same purpose.

set_root_factory(factory)

Add a root factory to the current configuration state. If the factory argument is None a default root factory will be registered.

latex-note.png

Using the root_factory argument to the pyramid.config.Configurator constructor can be used to achieve the same purpose.

552

set_session_factory(factory)

Configure the application with a session factory. If this method is called, the factory argument must be a session factory callable or a dotted Python name to that factory.

latex-note.png

Using the session_factory argument to the pyramid.config.Configurator constructor can be used to achieve the same purpose.

set_view_mapper(mapper)

Setting a view mapper makes it possible to make use of view callable objects which implement different call signatures than the ones supported by Pyramid as described in its narrative documentation.

The mapper should argument be an object implementing pyramid.interfaces.IViewMapperFactory or a dotted Python name to such an object. The provided mapper will become the default view mapper to be used by all subsequent view configuration registrations.

See also Using a View Mapper.

latex-note.png

Using the default_view_mapper argument to the pyramid.config.Configurator constructor can be used to achieve the same purpose.

Extension Author APIs

553


44. PYRAMID.CONFIG

action(discriminator, callable=None, args=(), kw=None, order=0, in-

trospectables=(), **extra)

Register an action which will be executed when pyramid.config.Configurator.commit() is called (or executed immediately if autocommit is True).

latex-warning.png

This method is typically only used by Pyramid framework extension authors, not by Pyramid application developers.

The discriminator uniquely identifies the action. It must be given, but it can be None, to indicate that the action never conflicts. It must be a hashable value.

The callable is a callable object which performs the task associated with the action when the action is executed. It is optional.

args and kw are tuple and dict objects respectively, which are passed to callable when this action is executed. Both are optional.

order is a grouping mechanism; an action with a lower order will be executed before an action with a higher order (has no effect when autocommit is True).

introspectables is a sequence of introspectable objects (or the empty sequence if no introspectable objects are associated with this action). If this configurator’s introspection attribute is False, these introspectables will be ignored.

extra provides a facility for inserting extra keys and values into an action dictionary.

add_directive(name, directive, action_wrap=True)

Add a directive method to the configurator.

554

latex-warning.png

This method is typically only used by Pyramid framework extension authors, not by Pyramid application developers.

Framework

 

extenders

can

add

directive

meth-

ods

to

a

configurator

by

instructing

their

users

to

 

call

config.add_directive(’somename’,

’some.callable’). This will make some.callable accessible as config.somename. some.callable should be a function which accepts config as a first argument, and arbitrary positional and keyword arguments following. It should use config.action as necessary to perform actions. Directive methods can then be invoked like ‘built-in’ directives such as add_view, add_route, etc.

The action_wrap argument should be True for directives which perform config.action with potentially conflicting discriminators. action_wrap will cause the directive to be wrapped in a decorator which provides more accurate conflict cause information.

add_directive does not participate in conflict detection, and later calls to add_directive will override earlier calls.

with_package(package)

Return a new Configurator instance with the same registry as this configurator using the package supplied as the package argument to the new configurator. package may be an actual Python package object or a dotted Python name representing a package.

derive_view(view, attr=None, renderer=None)

Create a view callable using the function, instance, or class (or dotted Python name referring to the same) provided as view object.

latex-warning.png

This method is typically only used by Pyramid framework extension authors, not by Pyramid application developers.

555


44. PYRAMID.CONFIG

This is API is useful to framework extenders who create pluggable systems which need to register ‘proxy’ view callables for functions, instances, or classes which meet the requirements of being a Pyramid view callable. For example, a some_other_framework function in another framework may want to allow a user to supply a view callable, but he may want to wrap the view callable in his own before registering the wrapper as a Pyramid view callable. Because a Pyramid view callable can be any of a number of valid objects, the framework extender will not know how to call the user-supplied object. Running it through derive_view normalizes it to a callable which accepts two arguments: context and request.

For example:

def some_other_framework(user_supplied_view): config = Configurator(reg)

proxy_view = config.derive_view(user_supplied_view) def my_wrapper(context, request):

do_something_that_mutates(request) return proxy_view(context, request)

config.add_view(my_wrapper)

The view object provided should be one of the following:

•A function or another non-class callable object that accepts a request as a single positional argument and which returns a response object.

•A function or other non-class callable object that accepts two positional arguments, context, request and which returns a response object.

•A class which accepts a single positional argument in its constructor named request, and which has a __call__ method that accepts no arguments that returns a response object.

•A class which accepts two positional arguments named context, request, and which has a __call__ method that accepts no arguments that returns a response object.

•A dotted Python name which refers to any of the kinds of objects above. This API returns a callable which accepts the arguments context, request and which returns the result of calling the provided view object.

The attr keyword argument is most useful when the view object is a class. It names the method that should be used as the callable. If attr is not provided, the attribute effectively defaults to __call__. See Defining a View Callable as a Class for more information.

556


The renderer keyword argument should be a renderer name. If supplied, it will cause the returned callable to use a renderer to convert the user-supplied view result to a response object. If a renderer argument is not supplied, the user-supplied view must itself return a response object.

Utility Methods

absolute_asset_spec(relative_spec)

Resolve the potentially relative asset specification string passed as relative_spec into an absolute asset specification string and return the string. Use the package of this configurator as the package to which the asset specification will be considered relative when generating an absolute asset specification. If the provided relative_spec argument is already absolute, or if the relative_spec is not a string, it is simply returned.

maybe_dotted(dotted)

Resolve the dotted Python name dotted to a global Python object. If dotted is not a string, return it without attempting to do any name resolution. If dotted is a relative dotted name (e.g. .foo.bar, consider it relative to the package argument supplied to this Configurator’s constructor.

ZCA-Related APIs

hook_zca()

Call zope.component.getSiteManager.sethook() with the argument pyramid.threadlocal.get_current_registry, causing the Zope Component Architecture ‘global’ APIs such as zope.component.getSiteManager(), zope.component.getAdapter() and others to use the Pyramid application registry rather than the Zope ‘global’ registry.

unhook_zca()

Call zope.component.getSiteManager.reset() to undo the action of pyramid.config.Configurator.hook_zca().

setup_registry(settings=None, root_factory=None, authentication_policy=None, authorization_policy=None, renderers=None, debug_logger=None, locale_negotiator=None, request_factory=None, renderer_globals_factory=None, default_permission=None, session_factory=None, default_view_mapper=None, exceptionresponse_view=<function de-

fault_exceptionresponse_view at 0x2a097d0>)

When you pass a non-None registry argument to the Configurator

557

44. PYRAMID.CONFIG

constructor, no initial setup is performed against the registry. This is because the registry you pass in may have already been initialized for use under Pyramid via a different configurator. However, in some circumstances (such as when you want to use a global registry instead of a registry created as a result of the Configurator constructor), or when you want to reset the initial setup of a registry, you do want to explicitly initialize the registry associated with a Configurator for use under Pyramid. Use setup_registry to do this initialization.

setup_registry configures settings, a root factory, security policies, renderers, a debug logger, a locale negotiator, and various other settings using the configurator’s current registry, as per the descriptions in the Configurator constructor.

Testing Helper APIs

testing_add_renderer(path, renderer=None)

Unit/integration testing helper: register a renderer at path (usually a relative filename ala templates/foo.pt or an asset specification) and return the renderer object. If the renderer argument is None, a ‘dummy’ renderer will be used. This function is useful when testing code that calls the pyramid.renderers.render() function or pyramid.renderers.render_to_response() function or any other render_* or get_* API of the pyramid.renderers module.

Note that calling this method for with a path argument representing a renderer factory type (e.g. for foo.pt usually implies the chameleon_zpt renderer factory) clobbers any existing renderer factory registered for that type.

latex-note.png

This method is also available under the alias testing_add_template (an older name for it).

testing_add_subscriber(event_iface=None)

Unit/integration testing helper: Registers a subscriber which listens for events of the type event_iface. This method returns a list object which is appended to by the subscriber whenever an event is captured.

558