pyramid.config

class Configurator(registry=None, package=None, settings=None, root_factory=None, security_policy=None, authentication_policy=None, authorization_policy=None, renderers=None, debug_logger=None, locale_negotiator=None, request_factory=None, response_factory=None, default_permission=None, session_factory=None, default_view_mapper=None, autocommit=False, exceptionresponse_view=<function default_exceptionresponse_view>, route_prefix=None, introspection=True, root_package=None)[source]

A Configurator is used to configure a Pyramid application registry.

The Configurator lifecycle can be managed by using a context manager to automatically handle calling pyramid.config.Configurator.begin() and pyramid.config.Configurator.end() as well as pyramid.config.Configurator.commit().

with Configurator(settings=settings) as config:
    config.add_route('home', '/')
    app = config.make_wsgi_app()

If the registry argument is not None, 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 its construction, the configurator may be used to add further configuration to the registry.

Warning

If registry is assigned the above-mentioned class instance, all other constructor arguments are ignored, with the exception of package.

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 the 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 root_package is passed, it will propagate through the configuration hierarchy as a way for included packages to locate resources relative to the package in which the main Configurator was created. If None is passed (the default), the root_package will be derived from the package argument. The package attribute is always pointing at the package being included when using include(), whereas the root_package does not change.

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 the same. If it is None, a default root factory will be used.

If security_policy is passed, it should be an instance of a security policy or a dotted Python name to the same.

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

If authorization_policy is passed, it should be an instance of an authorization policy or a dotted Python name to the 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 None (the default), a default set of renderer factories is used. Else, it should be a list of tuples representing a set of renderer factories which should be configured into this application, and each tuple representing a set of positional values that should be passed to pyramid.config.Configurator.add_renderer().

If debug_logger is not passed, a default debug logger that logs to a logger will be used (the logger name will be the package name of the caller of this configurator). If it is passed, it should be an instance of the logging.Logger (PEP 282) standard library class or a Python logger name. 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 the same. See Changing the Request Factory. By default it is None, which means use the default request factory.

If response_factory is passed, it should be a response factory implementation or a dotted Python name to the same. See Changing the Response Factory. By default it is None, which means use the default response 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

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 default_view_mapper is not passed, a superdefault view mapper will be used.

If exceptionresponse_view is passed, it must be a view callable or None. If it is a view callable, it will be used as an exception view callable when an exception response is raised. If exceptionresponse_view is None, no exception response view will be registered, and all raised exception responses will be bubbled up to Pyramid's caller. By default, the pyramid.httpexceptions.default_exceptionresponse_view function is used as the exceptionresponse_view.

If route_prefix is passed, all routes added with pyramid.config.Configurator.add_route() will have the specified path prepended to their pattern.

If introspection is passed, it must be a boolean value. If it's True, introspection values during actions will be kept for use for tools like the debug toolbar. If it's False, introspection values provided by registrations will be ignored. By default, it is True.

New in version 1.1: The exceptionresponse_view argument.

New in version 1.2: The route_prefix argument.

New in version 1.3: The introspection argument.

New in version 1.6: The root_package argument. The response_factory argument.

New in version 1.9: The ability to use the configurator as a context manager with the with-statement to make threadlocal configuration available for further configuration with an implicit commit.

Controlling Configuration State

commit()

Commit any pending configuration actions. If a configuration conflict is detected in the pending configuration actions, 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.

Warning

You should think very carefully before manually invoking commit(). Especially not as part of any reusable configuration methods. Normally it should only be done by an application author at the end of configuration in order to override certain aspects of an addon.

begin(request=<object object>)[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 onto the thread local stack consulted by various pyramid.threadlocal API functions.

If request is not specified and the registry owned by the configurator is already pushed as the current threadlocal registry then this method will keep the current threadlocal request unchanged.

Changed in version 1.8: The current threadlocal request is propagated if the current threadlocal registry remains unchanged.

end()[source]

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

include(callable, route_prefix=None)[source]

Include a configuration callable, to support imperative application extensibility.

Warning

In versions of Pyramid prior to 1.2, this function accepted *callables, but this has been changed to support only a single callable.

A configuration callable should be a callable that accepts a single argument named config, which will be an instance of a Configurator. However, be warned that it will not be the same configurator instance on which you call this method. The code which runs as a 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 callable 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# myapp.myconfig module
2
3def my_view(request):
4    from pyramid.response import Response
5    return Response('OK')
6
7def includeme(config):
8    config.add_view(my_view)

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

1from pyramid.config import Configurator
2
3def main(global_config, **settings):
4    config = Configurator()
5    config.include('myapp.myconfig.includeme')

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

1from pyramid.config import Configurator
2
3def main(global_config, **settings):
4    config = Configurator()
5    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.

If the route_prefix is supplied, it must be a string and will have a similar effect to using pyramid.config.Configurator.route_prefix_context(). Any calls to pyramid.config.Configurator.add_route() within the included callable will have their pattern prefixed with the value of route_prefix. This can be used to help mount a set of routes at a different location than the included callable's author intended, while still maintaining the same route names. For example:

1from pyramid.config import Configurator
2
3def included(config):
4    config.add_route('show_users', '/show')
5
6def main(global_config, **settings):
7    config = Configurator()
8    config.include(included, route_prefix='/users')

In the above configuration, the show_users route will have an effective route pattern of /users/show, instead of /show because the route_prefix argument will be prepended to the pattern.

New in version 1.2: The route_prefix parameter.

Changed in version 1.9: The included function is wrapped with a call to pyramid.config.Configurator.begin() and pyramid.config.Configurator.end() while it is executed.

make_wsgi_app()[source]

Commits any pending configuration statements, sends a pyramid.events.ApplicationCreated event to all listeners, adds this configuration's registry to pyramid.config.global_registries, and returns a Pyramid WSGI application representing the committed configuration state.

route_prefix_context(route_prefix)

Return this configurator with a route prefix temporarily set.

When the context exits, the route_prefix is reset to the original.

route_prefix is a string suitable to be used as a route prefix, or None.

Example Usage:

config = Configurator()
with config.route_prefix_context('foo'):
    config.add_route('bar', '/bar')

New in version 1.10.

scan(package=None, categories=('pyramid',), onerror=None, ignore=None, **kw)[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 ['pyramid'] which will execute only Pyramid-related Venusian decorator callbacks such as from pyramid.view.view_config. See the Venusian documentation for more information about limiting a scan by using an explicit set of categories. Pass None to pick up all Venusian decorators.

The onerror argument, if provided, should be a Venusian onerror callback function. The onerror function is passed to venusian.Scanner.scan() to influence error behavior when an exception is raised during the scanning process. See the Venusian documentation for more information about onerror callbacks.

The ignore argument, if provided, should be a Venusian ignore value. Providing an ignore argument allows the scan to ignore particular modules, packages, or global objects during a scan. ignore can be a string or a callable, or a list containing strings or callables. The simplest usage of ignore is to provide a module or package by providing a full path to its dotted name. For example: config.scan(ignore='my.module.subpackage') would ignore the my.module.subpackage package during a scan, which would prevent the subpackage and any of its submodules from being imported and scanned. See the Venusian documentation for more information about the ignore argument.

To perform a scan, Pyramid creates a Venusian Scanner object. The kw argument represents a set of keyword arguments to pass to the Venusian Scanner object's constructor. See the venusian documentation (its Scanner class) for more information about the constructor. By default, the only keyword arguments passed to the Scanner constructor are {'config':self} where self is this configurator object. This services the requirement of all built-in Pyramid decorators, but extension systems may require additional arguments. Providing this argument is not often necessary; it's an advanced usage.

New in version 1.1: The **kw argument.

New in version 1.3: The ignore argument.

Changed in version 2.0: The categories argument now defaults to ['pyramid'] instead of None to control which decorator callbacks are executed.

Adding Routes and Views

Adding an Event Subscriber

Using Security

add_permission(permission_name)

A configurator directive which registers a free-standing permission without associating it with a view callable. This can be used so that the permission shows up in the introspectable data under the permissions category (permissions mentioned via add_view already end up in there). For example:

config = Configurator()
config.add_permission('view')

Extending the Request Object

Using I18N

Overriding Assets

Getting and Adding Settings

add_settings(settings=None, **kw)

Augment the deployment settings with one or more key/value pairs.

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.

get_settings()

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.

Note

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

Hooking Pyramid Behavior

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

New in version 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.

Note

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

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 directly '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 compatibility 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 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.

Extension Author APIs

action(discriminator, callable=None, args=(), kw=None, order=0, introspectables=(), **extra)

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

Warning

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)[source]

Add a directive method to the configurator.

Warning

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

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

Warning

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

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.

Utility Methods

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.

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.

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, security_policy=None, authentication_policy=None, authorization_policy=None, renderers=None, debug_logger=None, locale_negotiator=None, request_factory=None, response_factory=None, default_permission=None, session_factory=None, default_view_mapper=None, exceptionresponse_view=<function default_exceptionresponse_view>)[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 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.

Note

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

testing_resources(resources)

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_securitypolicy(userid=None, identity=None, permissive=True, remember_result=None, forget_result=None)

Unit/integration testing helper. Registers a faux security policy.

This function is most useful when testing code that uses the security APIs, such as pyramid.request.Request.identity(), pyramid.request.Request.authenticated_userid, or pyramid.request.Request.has_permission(),

The behavior of the registered security policy depends on the arguments passed to this method.

Parameters:
  • userid (str) -- If provided, the policy's authenticated_userid method will return this value. As a result, pyramid.request.Request.authenticated_userid will have this value as well.

  • identity (object) -- If provided, the policy's identity method will return this value. As a result, pyramid.request.Request.identity` will have this value.

  • permissive (bool) -- If true, the policy will allow access to any user for any permission. If false, the policy will deny all access.

  • remember_result (list) -- If provided, the policy's remember method will return this value. Otherwise, remember will return an empty list.

  • forget_result (list) -- If provided, the policy's forget method will return this value. Otherwise, forget will return an empty list.

New in version 1.4: The remember_result argument.

New in version 1.4: The forget_result argument.

Changed in version 2.0: Removed groupids argument and add identity argument.

Attributes

introspectable

A shortcut attribute which points to the pyramid.registry.Introspectable class (used during directives to provide introspection to actions).

New in version 1.3.

introspector

The introspector related to this configuration. It is an instance implementing the pyramid.interfaces.IIntrospector interface.

New in version 1.3.

registry

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

global_registries

The set of registries that have been created for Pyramid applications, one for each call to pyramid.config.Configurator.make_wsgi_app() in the current process. The object itself supports iteration and has a last property containing the last registry loaded.

The registries contained in this object are stored as weakrefs, thus they will only exist for the lifetime of the actual applications for which they are being used.

class not_(value)[source]

You can invert the meaning of any predicate value by wrapping it in a call to pyramid.config.not_.

1from pyramid.config import not_
2
3config.add_view(
4    'mypackage.views.my_view',
5    route_name='ok',
6    request_method=not_('POST')
7    )

The above example will ensure that the view is called if the request method is not POST, at least if no other view is more specific.

This technique of wrapping a predicate value in not_ can be used anywhere predicate values are accepted:

New in version 1.5.

PHASE0_CONFIG
PHASE1_CONFIG
PHASE2_CONFIG
PHASE3_CONFIG