> Read the latest version of this page
Edit me on GitHub

pyramid.config

class Configurator(registry=None, package=None, settings=None, root_factory=None, authentication_policy=None, authorization_policy=None, renderers=DEFAULT_RENDERERS, debug_logger=None, locale_negotiator=None, request_factory=None, renderer_globals_factory=None, default_permission=None, session_factory=None, autocommit=False)[source]

A Configurator is used to configure a Pyramid application registry.

The Configurator accepts a number of arguments: registry, package, settings, root_factory, authentication_policy, authorization_policy, renderers debug_logger, locale_negotiator, request_factory, renderer_globals_factory, default_permission, session_factory, and autocommit.

If the registry argument is passed as a non-None value, it must be an instance of the pyramid.registry.Registry class representing the registry to configure. If registry is None, the configurator will create a pyramid.registry.Registry instance itself; it will also perform some default configuration that would not otherwise be done. After construction, the configurator may be used to add configuration to the registry. The overall state of a registry is called the ‘configuration state’.

Warning

If a registry is passed to the Configurator constructor, all other constructor arguments except package are ignored.

If the package argument is passed, it must be a reference to a Python package (e.g. sys.modules['thepackage']) or a dotted Python name to same. This value is used as a basis to convert relative paths passed to various configuration methods, such as methods which accept a renderer argument, into absolute paths. If None is passed (the default), the package is assumed to be the Python package in which the caller of the Configurator constructor lives.

If the settings argument is passed, it should be a Python dictionary representing the deployment settings for this application. These are later retrievable using the pyramid.registry.Registry.settings attribute (aka request.registry.settings).

If the root_factory argument is passed, it should be an object representing the default root factory for your application or a dotted Python name to same. If it is None, a default root factory will be used.

If authentication_policy is passed, it should be an instance of an authentication policy or a dotted Python name to same.

If authorization_policy is passed, it should be an instance of an authorization policy or a dotted Python name to same.

Note

A ConfigurationError will be raised when an authorization policy is supplied without also supplying an authentication policy (authorization requires authentication).

If renderers is passed, it should be a list of tuples representing a set of renderer factories which should be configured into this application (each tuple representing a set of positional values that should be passed to pyramid.config.Configurator.add_renderer()). If it is not passed, a default set of renderer factories is used.

If debug_logger is not passed, a default debug logger that logs to stderr will be used. If it is passed, it should be an instance of the logging.Logger (PEP 282) standard library class or a dotted Python name to same. The debug logger is used by Pyramid itself to log warnings and authorization debugging information.

If locale_negotiator is passed, it should be a locale negotiator implementation or a dotted Python name to same. See Using a Custom Locale Negotiator.

If request_factory is passed, it should be a request factory implementation or a dotted Python name to same. See Changing the Request Factory. By default it is None, which means use the default request factory.

If renderer_globals_factory is passed, it should be a renderer globals factory implementation or a dotted Python name to same. See Adding Renderer Globals. By default, it is None, which means use no renderer globals factory.

If default_permission is passed, it should be a permission string to be used as the default permission for all view configuration registrations performed against this Configurator. An example of a permission string:'view'. Adding a default permission makes it unnecessary to protect each view configuration with an explicit permission, unless your application policy requires some exception for a particular view. By default, default_permission is None, meaning that view configurations which do not explicitly declare a permission will always be executable by entirely anonymous users (any authorization policy in effect is ignored). See also Setting a Default Permission.

If session_factory is passed, it should be an object which implements the session factory interface. If a nondefault value is passed, the session_factory will be used to create a session object when request.session is accessed. Note that the same outcome can be achieved by calling pyramid.config.Configurator.set_session_factory(). By default, this argument is None, indicating that no session factory will be configured (and thus accessing request.session will throw an error) unless set_session_factory is called later during configuration.

If autocommit is True, every method called on the configurator will cause an immediate action, and no configuration conflict detection will be used. If autocommit is False, most methods of the configurator will defer their action until pyramid.config.Configurator.commit() is called. When pyramid.config.Configurator.commit() is called, the actions implied by the called methods will be checked for configuration conflicts unless autocommit is True. If a conflict is detected a ConfigurationConflictError will be raised. Calling pyramid.config.Configurator.make_wsgi_app() always implies a final commit.

If default_view_mapper is passed, it will be used as the default view mapper factory for view configurations that don’t otherwise specify one (see pyramid.interfaces.IViewMapperFactory). If a default_view_mapper is not passed, a superdefault view mapper will be used.

registry

The application registry which holds the configuration associated with this configurator.

begin(request=None)[source]

Indicate that application or test configuration has begun. This pushes a dictionary containing the application registry implied by registry attribute of this configurator and the request implied by the request argument on to the thread local stack consulted by various pyramid.threadlocal API functions.

end()[source]

Indicate that application or test configuration has ended. This pops the last value pushed on to the thread local stack (usually by the begin method) and returns that value.

hook_zca()[source]

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. If zope.component cannot be imported, this method will raise an ImportError.

unhook_zca()[source]

Call zope.component.getSiteManager.reset() to undo the action of pyramid.config.Configurator.hook_zca(). If zope.component cannot be imported, this method will raise an ImportError.

get_settings()[source]

Return a deployment settings object for the current application. A deployment settings object is a dictionary-like object that contains key/value pairs based on the dictionary passed as the settings argument to the pyramid.config.Configurator constructor or the pyramid.router.make_app() API.

Note

For backwards compatibility, dictionary keys can also be looked up as attributes of the settings object.

Note

the pyramid.registry.Registry.settings API performs the same duty.

commit()[source]

Commit any pending configuration actions. If a configuration conflict is detected in the pending configuration actins, this method will raise a ConfigurationConflictError; within the traceback of this error will be information about the source of the conflict, usually including file names and line numbers of the cause of the configuration conflicts.

action(discriminator, callable=None, args=(), kw=None, order=0)[source]

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

Note

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 action. It is optional. args and kw are tuple and dict objects respectively, which are passed to callable when this action is executed.

order is a crude order control mechanism, only rarely used (has no effect when autocommit is True).

include(*callables)[source]

Include one or more configuration callables, to support imperative application extensibility.

A configuration callable should be a callable that accepts a single argument named config, which will be an instance of a Configurator (be warned that it will not be the same configurator instance on which you call this method, however). The code which runs as the result of calling the callable should invoke methods on the configurator passed to it which add configuration state. The return value of a callable will be ignored.

Values allowed to be presented via the *callables argument to this method: any callable Python object or any dotted Python name which resolves to a callable Python object. It may also be a Python module, in which case, the module will be searched for a callable named includeme, which will be treated as the configuration callable.

For example, if the includeme function below lives in a module named myapp.myconfig:

1
2
3
4
5
6
7
8
# myapp.myconfig module

def my_view(request):
    from pyramid.response import Response
    return Response('OK')

def includeme(config):
    config.add_view(my_view)

You might cause it be included within your Pyramid application like so:

1
2
3
4
5
from pyramid.config import Configurator

def main(global_config, **settings):
    config = Configurator()
    config.include('myapp.myconfig.includeme')

Because the function is named includeme, the function name can also be omitted from the dotted name reference:

1
2
3
4
5
from pyramid.config import Configurator

def main(global_config, **settings):
    config = Configurator()
    config.include('myapp.myconfig')

Included configuration statements will be overridden by local configuration statements if an included callable causes a configuration conflict by registering something with the same configuration parameters.

add_directive(name, directive, action_wrap=True)[source]

Add a directive method to the configurator.

Framework extenders can add directive methods 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)[source]

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 Python dotted name representing a package.

maybe_dotted(dotted)[source]

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.

absolute_asset_spec(relative_spec)[source]

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.

setup_registry(settings=None, root_factory=None, authentication_policy=None, renderers=DEFAULT_RENDERERS, debug_logger=None, locale_negotiator=None, request_factory=None, renderer_globals_factory=None)[source]

When you pass a non-None registry argument to the Configurator 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 the Zope ‘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.

add_renderer(name, factory)[source]

Add a Pyramid renderer factory to the current configuration state.

The name argument is the renderer name. Use None to represent the default renderer (a renderer which will be used for all views unless they name another renderer specifically).

The factory argument is Python reference to an implementation of a renderer factory or a dotted Python name to same.

Note that this function must be called before any add_view invocation that names the renderer name as an argument. As a result, it’s usually a better idea to pass globally used renderers into the Configurator constructor in the sequence of renderers passed as renderer than it is to use this method.

add_route(name, pattern=None, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=False, accept=None, path_info=None, request_method=None, request_param=None, traverse=None, custom_predicates=(), view_permission=None, renderer=None, view_renderer=None, view_context=None, view_attr=None, use_global_views=False, path=None, pregenerator=None)[source]

Add a route configuration to the current configuration state, as well as possibly a view configuration to be used to specify a view callable that will be invoked when this route matches. The arguments to this method are divided into predicate, non-predicate, and view-related types. Route predicate arguments narrow the circumstances in which a route will be match a request; non-predicate arguments are informational.

Non-Predicate Arguments

name

The name of the route, e.g. myroute. This attribute is required. It must be unique among all defined routes in a given application.

factory

A Python object (often a function or a class) or a dotted Python name which refers to the same object that will generate a Pyramid root resource object when this route matches. For example, mypackage.resources.MyFactory. If this argument is not specified, a default root factory will be used.

traverse

If you would like to cause the context to be something other than the root object when this route matches, you can spell a traversal pattern as the traverse argument. This traversal pattern will be used as the traversal path: traversal will begin at the root object implied by this route (either the global root, or the object returned by the factory associated with this route).

The syntax of the traverse argument is the same as it is for pattern. For example, if the pattern provided to add_route is articles/{article}/edit, and the traverse argument provided to add_route is /{article}, when a request comes in that causes the route to match in such a way that the article match value is ‘1’ (when the request URI is /articles/1/edit), the traversal path will be generated as /1. This means that the root object’s __getitem__ will be called with the name 1 during the traversal phase. If the 1 object exists, it will become the context of the request. Traversal has more information about traversal.

If the traversal path contains segment marker names which are not present in the pattern argument, a runtime error will occur. The traverse pattern should not contain segment markers that do not exist in the pattern argument.

A similar combining of routing and traversal is available when a route is matched which contains a *traverse remainder marker in its pattern (see Using *traverse In a Route Pattern). The traverse argument to add_route allows you to associate route patterns with an arbitrary traversal path without using a a *traverse remainder marker; instead you can use other match information.

Note that the traverse argument to add_route is ignored when attached to a route that has a *traverse remainder marker in its pattern.

pregenerator

This option should be a callable object that implements the pyramid.interfaces.IRoutePregenerator interface. A pregenerator is a callable called by the pyramid.url.route_url function to augment or replace the arguments it is passed when generating a URL for the route. This is a feature not often used directly by applications, it is meant to be hooked by frameworks that use Pyramid as a base.

Predicate Arguments

pattern

The pattern of the route e.g. ideas/{idea}. This argument is required. See Route Pattern Syntax for information about the syntax of route patterns. If the pattern doesn’t match the current URL, route matching continues.

Note

For backwards compatibility purposes (as of Pyramid 1.0), a path keyword argument passed to this function will be used to represent the pattern value if the pattern argument is None. If both path and pattern are passed, pattern wins.

xhr

This value should be either True or False. If this value is specified and is True, the request must possess an HTTP_X_REQUESTED_WITH (aka X-Requested-With) header for this route to match. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries. If this predicate returns False, route matching continues.

request_method

A string representing an HTTP method name, e.g. GET, POST, HEAD, DELETE, PUT. If this argument is not specified, this route will match if the request has any request method. If this predicate returns False, route matching continues.

path_info

This value represents a regular expression pattern that will be tested against the PATH_INFO WSGI environment variable. If the regex matches, this predicate will return True. If this predicate returns False, route matching continues.

request_param

This value can be any string. A view declaration with this argument ensures that the associated route will only match when the request has a key in the request.params dictionary (an HTTP GET or POST variable) that has a name which matches the supplied value. If the value supplied as the argument has a = sign in it, e.g. request_params="foo=123", then the key (foo) must both exist in the request.params dictionary, and the value must match the right hand side of the expression (123) for the route to “match” the current request. If this predicate returns False, route matching continues.

header

This argument represents an HTTP header name or a header name/value pair. If the argument contains a : (colon), it will be considered a name/value pair (e.g. User-Agent:Mozilla/.* or Host:localhost). If the value contains a colon, the value portion should be a regular expression. If the value does not contain a colon, the entire value will be considered to be the header name (e.g. If-Modified-Since). If the value evaluates to a header name only without a value, the header specified by the name must be present in the request for this predicate to be true. If the value evaluates to a header name/value pair, the header specified by the name must be present in the request and the regular expression specified as the value must match the header value. Whether or not the value represents a header name or a header name/value pair, the case of the header name is not significant. If this predicate returns False, route matching continues.

accept

This value represents a match query for one or more mimetypes in the Accept HTTP request header. If this value is specified, it must be in one of the following forms: a mimetype match token in the form text/plain, a wildcard mimetype match token in the form text/* or a match-all wildcard mimetype match token in the form */*. If any of the forms matches the Accept header of the request, this predicate will be true. If this predicate returns False, route matching continues.

custom_predicates

This value should be a sequence of references to custom predicate callables. Use custom predicates when no set of predefined predicates does what you need. Custom predicates can be combined with predefined predicates as necessary. Each custom predicate callable should accept two arguments: info and request and should return either True or False after doing arbitrary evaluation of the info and/or the request. If all custom and non-custom predicate callables return True the associated route will be considered viable for a given request. If any predicate callable returns False, route matching continues. Note that the value info passed to a custom route predicate is a dictionary containing matching information; see Custom Route Predicates for more information about info.

View-Related Arguments

view

A Python object or dotted Python name to the same object that will be used as a view callable when this route matches. e.g. mypackage.views.my_view.

view_context

A class or an interface or dotted Python name to the same object which the context of the view should match for the view named by the route to be used. This argument is only useful if the view attribute is used. If this attribute is not specified, the default (None) will be used.

If the view argument is not provided, this argument has no effect.

This attribute can also be spelled as for_ or view_for.

view_permission

The permission name required to invoke the view associated with this route. e.g. edit. (see Using Pyramid Security With URL Dispatch for more information about permissions).

If the view attribute is not provided, this argument has no effect.

This argument can also be spelled as permission.

view_renderer

This is either a single string term (e.g. json) or a string implying a path or asset specification (e.g. templates/views.pt). If the renderer value is a single term (does not contain a dot .), the specified term will be used to look up a renderer implementation, and that renderer implementation will be used to construct a response from the view return value. If the renderer term contains a dot (.), the specified term will be treated as a path, and the filename extension of the last element in the path will be used to look up the renderer implementation, which will be passed the full path. The renderer implementation will be used to construct a response from the view return value. See Writing View Callables Which Use a Renderer for more information.

If the view argument is not provided, this argument has no effect.

This argument can also be spelled as renderer.

view_attr

The view machinery defaults to using the __call__ method of the view callable (or the function itself, if the view callable is a function) to obtain a response dictionary. The attr value allows you to vary the method attribute used to obtain the response. For example, if your view was a class, and the class has a method named index and you wanted to use this method instead of the class’ __call__ method to return the response, you’d say attr="index" in the view configuration for the view. This is most useful when the view definition is a class.

If the view argument is not provided, this argument has no effect.

use_global_views

When a request matches this route, and view lookup cannot find a view which has a route_name predicate argument that matches the route, try to fall back to using a view that otherwise matches the context, request, and view name (but which does not match the route_name predicate).
add_static_view(name, path, **kw)[source]

Add a view used to render static assets such as images and CSS files.

The name argument is a string representing an application-relative local URL prefix. It may alternately be a full URL.

The path argument is the path on disk where the static files reside. This can be an absolute path, a package-relative path, or a asset specification.

The cache_max_age keyword argument is input to set the Expires and Cache-Control headers for static assets served. Note that this argument has no effect when the name is a url prefix. By default, this argument is None, meaning that no particular Expires or Cache-Control headers are set in the response.

The permission keyword argument is used to specify the permission required by a user to execute the static view. By default, it is the string __no_permission_required__. The __no_permission_required__ string is a special sentinel which indicates that, even if a default permission exists for the current application, the static view should be renderered to completely anonymous users. This default value is permissive because, in most web apps, static assets seldom need protection from viewing.

Usage

The add_static_view function is typically used in conjunction with the pyramid.url.static_url() function. add_static_view adds a view which renders a static asset when some URL is visited; pyramid.url.static_url() generates a URL to that asset.

The name argument to add_static_view is usually a view name. When this is the case, the pyramid.url.static_url() API will generate a URL which points to a Pyramid view, which will serve up a set of assets that live in the package itself. For example:

add_static_view('images', 'mypackage:images/')

Code that registers such a view can generate URLs to the view via pyramid.url.static_url():

static_url('mypackage:images/logo.png', request)

When add_static_view is called with a name argument that represents a URL prefix, as it is above, subsequent calls to pyramid.url.static_url() with paths that start with the path argument passed to add_static_view will generate a URL something like http://<Pyramid app URL>/images/logo.png, which will cause the logo.png file in the images subdirectory of the mypackage package to be served.

add_static_view can alternately be used with a name argument which is a URL, causing static assets to be served from an external webserver. This happens when the name argument is a fully qualified URL (e.g. starts with http:// or similar). In this mode, the name is used as the prefix of the full URL when generating a URL using pyramid.url.static_url(). For example, if add_static_view is called like so:

add_static_view('http://example.com/images', 'mypackage:images/')

Subsequently, the URLs generated by pyramid.url.static_url() for that static view will be prefixed with http://example.com/images:

static_url('mypackage:images/logo.png', request)

When add_static_view is called with a name argument that is the URL http://example.com/images, subsequent calls to pyramid.url.static_url() with paths that start with the path argument passed to add_static_view will generate a URL something like http://example.com/logo.png. The external webserver listening on example.com must be itself configured to respond properly to such a request.

See Serving Static Assets for more information.

add_settings(settings=None, **kw)[source]

Augment the settings argument passed in to the Configurator constructor with one or more ‘setting’ key/value pairs. A setting is a single key/value pair in the dictionary-ish object returned from the API pyramid.registry.Registry.settings and pyramid.config.Configurator.get_settings().

You may pass a dictionary:

config.add_settings({'external_uri':'http://example.com'})

Or a set of key/value pairs:

config.add_settings(external_uri='http://example.com')

This function is useful when you need to test code that accesses the pyramid.registry.Registry.settings API (or the pyramid.config.Configurator.get_settings() API) and which uses values from that API.

add_subscriber(subscriber, iface=None)[source]

Add an event subscriber for the event stream implied by the supplied iface interface. The subscriber argument represents a callable object (or a dotted Python name which identifies a callable); it will be called with a single object event whenever Pyramid emits an event associated with the iface, which may be an interface or a class or a dotted Python name to a global object representing an interface or a class. Using the default iface value, None will cause the subscriber to be registered for all event types. See Using Events for more information about events and subscribers.

add_translation_dirs(*specs)[source]

Add one or more translation directory paths to the current configuration state. The specs argument is a sequence that may contain absolute directory paths (e.g. /usr/share/locale) or asset specification names naming a directory path (e.g. some.package:locale) or a combination of the two.

Example:

config.add_translation_dirs('/usr/share/locale',
                            'some.package:locale')
add_view(view=None, name='', for_=None, permission=None, request_type=None, route_name=None, request_method=None, request_param=None, containment=None, attr=None, renderer=None, wrapper=None, xhr=False, accept=None, header=None, path_info=None, custom_predicates=(), context=None, decorator=None, mapper=None)[source]

Add a view configuration to the current configuration state. Arguments to add_view are broken down below into predicate arguments and non-predicate arguments. Predicate arguments narrow the circumstances in which the view callable will be invoked when a request is presented to Pyramid; non-predicate arguments are informational.

Non-Predicate Arguments

view

A view callable or a dotted Python name which refers to a view callable. This argument is required unless a renderer argument also exists. If a renderer argument is passed, and a view argument is not provided, the view callable defaults to a callable that returns an empty dictionary (see Writing View Callables Which Use a Renderer).

permission

The name of a permission that the user must possess in order to invoke the view callable. See Configuring View Security for more information about view security and permissions. If permission is omitted, a default permission may be used for this view registration if one was named as the pyramid.config.Configurator constructor’s default_permission argument, or if pyramid.config.Configurator.set_default_permission() was used prior to this view registration. Pass the string __no_permission_required__ as the permission argument to explicitly indicate that the view should always be executable by entirely anonymous users, regardless of the default permission, bypassing any authorization policy that may be in effect.

attr

The view machinery defaults to using the __call__ method of the view callable (or the function itself, if the view callable is a function) to obtain a response. The attr value allows you to vary the method attribute used to obtain the response. For example, if your view was a class, and the class has a method named index and you wanted to use this method instead of the class’ __call__ method to return the response, you’d say attr="index" in the view configuration for the view. This is most useful when the view definition is a class.

renderer

This is either a single string term (e.g. json) or a string implying a path or asset specification (e.g. templates/views.pt) naming a renderer implementation. If the renderer value does not contain a dot ., the specified string will be used to look up a renderer implementation, and that renderer implementation will be used to construct a response from the view return value. If the renderer value contains a dot (.), the specified term will be treated as a path, and the filename extension of the last element in the path will be used to look up the renderer implementation, which will be passed the full path. The renderer implementation will be used to construct a response from the view return value.

Note that if the view itself returns a response (see View Callable Responses), the specified renderer implementation is never called.

When the renderer is a path, although a path is usually just a simple relative pathname (e.g. templates/foo.pt, implying that a template named “foo.pt” is in the “templates” directory relative to the directory of the current package of the Configurator), a path can be absolute, starting with a slash on UNIX or a drive letter prefix on Windows. The path can alternately be a asset specification in the form some.dotted.package_name:relative/path, making it possible to address template assets which live in a separate package.

The renderer attribute is optional. If it is not defined, the “null” renderer is assumed (no rendering is performed and the value is passed back to the upstream Pyramid machinery unmolested).

wrapper

The view name of a different view configuration which will receive the response body of this view as the request.wrapped_body attribute of its own request, and the response returned by this view as the request.wrapped_response attribute of its own request. Using a wrapper makes it possible to “chain” views together to form a composite response. The response of the outermost wrapper view will be returned to the user. The wrapper view will be found as any view is found: see View Lookup and Invocation. The “best” wrapper view will be found based on the lookup ordering: “under the hood” this wrapper view is looked up via pyramid.view.render_view_to_response(context, request, 'wrapper_viewname'). The context and request of a wrapper view is the same context and request of the inner view. If this attribute is unspecified, no view wrapping is done.

decorator

A dotted Python name to function (or the function itself) which will be used to decorate the registered view callable. The decorator function will be called with the view callable as a single argument. The view callable it is passed will accept (context, request). The decorator must return a replacement view callable which also accepts (context, request).

mapper

A Python object or dotted Python name which refers to a view mapper, or None. By default it is None, which indicates that the view should use the default view mapper. This plug-point is useful for Pyramid extension developers, but it’s not very useful for ‘civilians’ who are just developing stock Pyramid applications. Pay no attention to the man behind the curtain.

Predicate Arguments

name

The view name. Read Traversal to understand the concept of a view name.

context

An object or a dotted Python name referring to an interface or class object that the context must be an instance of, or the interface that the context must provide in order for this view to be found and called. This predicate is true when the context is an instance of the represented class or if the context provides the represented interface; it is otherwise false. This argument may also be provided to add_view as for_ (an older, still-supported spelling).

route_name

This value must match the name of a route configuration declaration (see URL Dispatch) that must match before this view will be called. Note that the route configuration referred to by route_name usually has a *traverse token in the value of its path, representing a part of the path that will be used by traversal against the result of the route’s root factory.

Warning

Using this argument services an advanced feature that isn’t often used unless you want to perform traversal after a route has matched. See Combining Traversal and URL Dispatch for more information on using this advanced feature.

request_type

This value should be an interface that the request must provide in order for this view to be found and called. This value exists only for backwards compatibility purposes.

request_method

This value can either be one of the strings GET, POST, PUT, DELETE, or HEAD representing an HTTP REQUEST_METHOD. A view declaration with this argument ensures that the view will only be called when the request’s method attribute (aka the REQUEST_METHOD of the WSGI environment) string matches the supplied value.

request_param

This value can be any string. A view declaration with this argument ensures that the view will only be called when the request has a key in the request.params dictionary (an HTTP GET or POST variable) that has a name which matches the supplied value. If the value supplied has a = sign in it, e.g. request_params="foo=123", then the key (foo) must both exist in the request.params dictionary, and the value must match the right hand side of the expression (123) for the view to “match” the current request.

containment

This value should be a Python class or interface or a dotted Python name to such an object that a parent object in the lineage must provide in order for this view to be found and called. The nodes in your object graph must be “location-aware” to use this feature. See Location-Aware Resources for more information about location-awareness.

xhr

This value should be either True or False. If this value is specified and is True, the request must possess an HTTP_X_REQUESTED_WITH (aka X-Requested-With) header that has the value XMLHttpRequest for this view to be found and called. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries.

accept

The value of this argument represents a match query for one or more mimetypes in the Accept HTTP request header. If this value is specified, it must be in one of the following forms: a mimetype match token in the form text/plain, a wildcard mimetype match token in the form text/* or a match-all wildcard mimetype match token in the form */*. If any of the forms matches the Accept header of the request, this predicate will be true.

header

This value represents an HTTP header name or a header name/value pair. If the value contains a : (colon), it will be considered a name/value pair (e.g. User-Agent:Mozilla/.* or Host:localhost). The value portion should be a regular expression. If the value does not contain a colon, the entire value will be considered to be the header name (e.g. If-Modified-Since). If the value evaluates to a header name only without a value, the header specified by the name must be present in the request for this predicate to be true. If the value evaluates to a header name/value pair, the header specified by the name must be present in the request and the regular expression specified as the value must match the header value. Whether or not the value represents a header name or a header name/value pair, the case of the header name is not significant.

path_info

This value represents a regular expression pattern that will be tested against the PATH_INFO WSGI environment variable. If the regex matches, this predicate will be True.

custom_predicates

This value should be a sequence of references to custom predicate callables. Use custom predicates when no set of predefined predicates do what you need. Custom predicates can be combined with predefined predicates as necessary. Each custom predicate callable should accept two arguments: context and request and should return either True or False after doing arbitrary evaluation of the context and/or the request. If all callables return True, the associated view callable will be considered viable for a given request.
derive_view(view, attr=None, renderer=None)[source]

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

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.

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.

make_wsgi_app()[source]

Commits any pending configuration statements, sends a pyramid.events.ApplicationCreated event to all listeners, and returns a Pyramid WSGI application representing the committed configuration state.

override_asset(to_override, override_with, _override=None)[source]

Add a Pyramid asset override to the current configuration state.

to_override is a asset specification to the asset being overridden.

override_with is a asset specification to the asset that is performing the override.

See Static Assets for more information about asset overrides.

scan(package=None, categories=None)[source]

Scan a Python package and any of its subpackages for objects marked with configuration decoration such as pyramid.view.view_config. Any decorated object found will influence the current configuration state.

The package argument should be a Python package or module object (or a dotted Python name which refers to such a package or module). If package is None, the package of the caller is used.

The categories argument, if provided, should be the Venusian ‘scan categories’ to use during scanning. Providing this argument is not often necessary; specifying scan categories is an extremely advanced usage. By default, categories is None which will execute all Venusian decorator callbacks including Pyramid-related decorators such as pyramid.view.view_config. See the Venusian documentation for more information about limiting a scan by using an explicit set of categories.

set_forbidden_view(view=None, attr=None, renderer=None, wrapper=None)[source]

Add a default forbidden view to the current configuration state.

Warning

This method has been deprecated in Pyramid 1.0. Do not use it for new development; it should only be used to support older code bases which depend upon it. See Changing the Forbidden View to see how a forbidden view should be registered in new projects.

The view argument should be a view callable or a dotted Python name which refers to a view callable.

The attr argument should be the attribute of the view callable used to retrieve the response (see the add_view method’s attr argument for a description).

The renderer argument should be the name of (or path to) a renderer used to generate a response for this view (see the pyramid.config.Configurator.add_view() method’s renderer argument for information about how a configurator relates to a renderer).

The wrapper argument should be the name of another view which will wrap this view when rendered (see the add_view method’s wrapper argument for a description).

set_notfound_view(view=None, attr=None, renderer=None, wrapper=None)[source]

Add a default not found view to the current configuration state.

Warning

This method has been deprecated in Pyramid 1.0. Do not use it for new development; it should only be used to support older code bases which depend upon it. See Changing the Not Found View to see how a not found view should be registered in new projects.

The view argument should be a view callable or a dotted Python name which refers to a view callable.

The attr argument should be the attribute of the view callable used to retrieve the response (see the add_view method’s attr argument for a description).

The renderer argument should be the name of (or path to) a renderer used to generate a response for this view (see the pyramid.config.Configurator.add_view() method’s renderer argument for information about how a configurator relates to a renderer).

The wrapper argument should be the name of another view which will wrap this view when rendered (see the add_view method’s wrapper argument for a description).

set_locale_negotiator(negotiator)[source]

Set the locale negotiator for this application. The locale negotiator is a callable which accepts a request object and which returns a locale name. The negotiator argument should be the locale negotiator implementation or a dotted Python name which refers to such an implementation.

Later calls to this method override earlier calls; there can be only one locale negotiator active at a time within an application. See Activating Translation for more information.

Note

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

set_default_permission(permission)[source]

Set the default permission to be used by all subsequent view configuration registrations. permission should be a permission string to be used as the default permission. An example of a permission string:'view'. Adding a default permission makes it unnecessary to protect each view configuration with an explicit permission, unless your application policy requires some exception for a particular view.

If a default permission is not set, views represented by view configuration registrations which do not explicitly declare a permission will be executable by entirely anonymous users (any authorization policy is ignored).

Later calls to this method override will conflict with earlier calls; there can be only one default permission active at a time within an application.

Warning

If a default permission is in effect, view configurations meant to create a truly anonymously accessible view (even exception view views) must use the explicit permission string __no_permission_required__ as the permission. When this string is used as the permission for a view configuration, the default permission is ignored, and the view is registered, making it available to all callers regardless of their credentials.

See also Setting a Default Permission.

Note

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

set_session_factory(session_factory)[source]

Configure the application with a session factory. If this method is called, the session_factory argument must be a session factory callable.

set_request_factory(factory)[source]

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).

Note

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

set_renderer_globals_factory(factory)[source]

The object passed as factory should be an callable (or a dotted Python name which refers to an callable) that will be used by the Pyramid rendering machinery as a renderers global factory (see Adding Renderer Globals).

The factory callable must accept a single argument named system (which will be a dictionary) and it must return a dictionary. When an application uses a renderer, the factory’s return dictionary will be merged into the system dictionary, and therefore will be made available to the code which uses the renderer.

Note

Using the renderer_globals_factory() argument to the pyramid.config.Configurator constructor can be used to achieve the same purpose.

testing_securitypolicy(userid=None, groupids=(), permissive=True)[source]

Unit/integration testing helper: Registers a pair of faux Pyramid security policies: a authentication policy and a authorization policy.

The behavior of the registered authorization policy depends on the permissive argument. If permissive is true, a permissive authorization policy is registered; this policy allows all access. If permissive is false, a nonpermissive authorization policy is registered; this policy denies all access.

The behavior of the registered authentication policy depends on the values provided for the userid and groupids argument. The authentication policy will return the userid identifier implied by the userid argument and the group ids implied by the groupids argument when the pyramid.security.authenticated_userid() or pyramid.security.effective_principals() APIs are used.

This function is most useful when testing code that uses the APIs named pyramid.security.has_permission(), pyramid.security.authenticated_userid(), pyramid.security.effective_principals(), and pyramid.security.principals_allowed_by_permission().

testing_resources(resources)[source]

Unit/integration testing helper: registers a dictionary of resource objects that can be resolved via the pyramid.traversal.find_resource() API.

The pyramid.traversal.find_resource() API is called with a path as one of its arguments. If the dictionary you register when calling this method contains that path as a string key (e.g. /foo/bar or foo/bar), the corresponding value will be returned to find_resource (and thus to your code) when pyramid.traversal.find_resource() is called with an equivalent path string or tuple.

testing_add_subscriber(event_iface=None)[source]

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.

When an event is dispatched that matches the value implied by the event_iface argument, that event will be appended to the list. You can then compare the values in the list to expected event notifications. This method is useful when testing code that wants to call pyramid.registry.Registry.notify(), or zope.component.event.dispatch().

The default value of event_iface (None) implies a subscriber registered for any kind of event.

testing_add_renderer(path, renderer=None)[source]

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.

Note

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

Previous topic

pyramid.chameleon_zpt

Next topic

pyramid.events

This Page