repoze.bfg.configuration

class Configurator(registry=None, package=None, settings=None, root_factory=None, authentication_policy=None, authorization_policy=None, renderers=DEFAULT_RENDERERS, debug_logger=None)

A Configurator is used to configure a repoze.bfg application registry.

The Configurator accepts a number of arguments: registry, package, settings, root_factory, zcml_file, authentication_policy, authorization_policy, renderers and debug_logger.

If the registry argument is passed as a non-None value, it must be an instance of the repoze.bfg.registry.Registry class representing the registry to configure. If registry is None, the configurator will create a repoze.bfg.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']). 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 repoze.bfg.settings.get_settings() API.

If the root_factory argument is passed, it should be an object representing the default root factory for your application. 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.

If authorization_policy is passed, it should be an instance of an authorization policy.

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. 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. The debug logger is used by repoze.bfg itself to log warnings and authorization debugging information.

registry
The application registry which holds the configuration associated with this configurator.
begin(request=None)
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 repoze.bfg.threadlocal API functions.
end()
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()
Call zope.component.getSiteManager.sethook() with the argument repoze.bfg.threadlocal.get_current_registry, causing the Zope Component Architecture ‘global’ APIs such as zope.component.getSiteManager(), zope.component.getAdapter() and others to use the repoze.bfg application registry rather than the Zope ‘global’ registry. If zope.component cannot be imported, this method will raise an ImportError.
unhook_zca()
Call zope.component.getSiteManager.reset() to undo the action of repoze.bfg.configuration.Configurator.hook_zca(). If zope.component cannot be imported, this method will raise an ImportError.
setup_registry(settings=None, root_factory=None, authentication_policy=None, renderers=DEFAULT_RENDERERS, debug_logger=None)

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 repoze.bfg 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 repoze.bfg. Use setup_registry to do this initialization.

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

add_renderer(name, factory)

Add a repoze.bfg renderer factory to the current configuration state.

The name argument is the renderer name.

The factory argument is Python reference to an implementation of a renderer factory.

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, path, 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, custom_predicates=(), view_permission=None, renderer=None, view_renderer=None, view_context=None, view_attr=None, use_global_views=False, _info=u'')

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 reference to a Python object (often a function or a class) that will generate a repoze.bfg context object when this route matches. For example, mypackage.models.MyFactoryClass. If this argument is not specified, a default root factory will be used.

Predicate Arguments

path

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

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: 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 route will be considered viable for a given request. If any custom predicate returns False, route matching continues. Note that the value context will always be None when passed to a custom route predicate.

Note

This feature is new as of repoze.bfg 1.2.

View-Related Arguments

view

A reference to a Python object that will be used as a view callable when this route matches. e.g. mypackage.views.my_view.

view_context

A reference to a class or an interface that 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 repoze.bfg 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 resource 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).

Note

This feature is new as of repoze.bfg 1.2.

add_static_view(name, path, cache_max_age=3600)

Add a view used to render static resources to the current configuration state.

The name argument is a string representing view name of the view which is registered.

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

See Serving Static Resources Using a ZCML Directive for more information.

add_settings(settings=None, **kw)

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 repoze.bfg.settings.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 calls the repoze.bfg.settings.get_settings() API and which uses return values from that API.

Note

This method is new as of repoze.bfg 1.2.

add_subscriber(subscriber, iface=None, info=u'')
Add an event subscriber for the event stream implied by the supplied iface interface. The subscriber argument represents a callable object; it will be called with a single object event whenever repoze.bfg emits an event associated with the iface. 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)

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 resource specification names naming a directory path (e.g. some.package:locale) or a combination of the two.

Example:

add_translations_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, _info=u'')

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 repoze.bfg; non-predicate arguments are informational.

Non-Predicate Arguments

view

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

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 resource 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 resource specification in the form some.dotted.package_name:relative/path, making it possible to address template resources 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 repoze.bfg 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 repoze.bfg.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.

Predicate Arguments

name

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

context

An object representing Python class 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 reference to a Python class or interface 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 Model Instances 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.

Note

This feature is new as of repoze.bfg 1.2.

load_zcml(spec)
Load configuration from a ZCML file into the current configuration state. The spec argument is an absolute filename, a relative filename, or a resource specification, defaulting to configure.zcml (relative to the package of the configurator’s caller).
make_wsgi_app()
Returns a repoze.bfg WSGI application representing the current configuration state and sends a repoze.bfg.interfaces.IWSGIApplicationCreatedEvent event to all listeners.
override_resource(to_override, override_with)

Add a repoze.bfg resource override to the current configuration state.

to_override is a resource specification to the resource being overridden.

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

See Resources for more information about resource overrides.

scan(package=None, categories=None)

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

The package argument should be a reference to a Python package or module object. 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 repoze.bfg-related decorators such as bfg_view. If this is not desirable because the codebase has other Venusian-using decorators that aren’t meant to be invoked during a particular scan, use ('bfg',) as a categories value to limit the execution of decorator callbacks to only those registered by repoze.bfg itself. Or pass a sequence of Venusian scan categories as necessary (e.g. ('bfg', 'myframework')) to limit the decorators called to the set of categories required.

set_forbidden_view(view=None, attr=None, renderer=None, wrapper=None)

Add a default forbidden view to the current configuration state.

Warning

This method has been deprecated in repoze.bfg 1.3. 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.

..note:: For backwards compatibility with repoze.bfg
1.2, unlike an ‘exception view’ as described in Exception Views, a context, request view callable registered using this API should not expect to receive the exception as its first (context) argument. Instead it should expect to receive the ‘real’ context as found via context-finding or None if no context could be found. The exception causing the registered view to be called is however still available as request.exception.

The view argument should be 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 repoze.bfg.configuration.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)

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

Warning

This method has been deprecated in repoze.bfg 1.3. 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.

..note:: For backwards compatibility with repoze.bfg
1.2, unlike an ‘exception view’ as described in Exception Views, a context, request view callable registered using this API should not expect to receive the exception as its first (context) argument. Instead it should expect to receive the ‘real’ context as found via context-finding or None if no context could be found. The exception causing the registered view to be called is however still available as request.exception.

The view argument should be 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 repoze.bfg.configuration.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)
Set the locale negotiator for this application. The locale negotiator is a callable which accepts a request object and which returns a locale name. 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.
testing_securitypolicy(userid=None, groupids=(), permissive=True)

Unit/integration testing helper: Registers a pair of faux repoze.bfg 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 repoze.bfg.security.authenticated_userid() or repoze.bfg.security.effective_principals() APIs are used.

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

testing_models(models)

Unit/integration testing helper: registers a dictionary of model objects that can be resolved via the repoze.bfg.traversal.find_model() API.

The repoze.bfg.traversal.find_model() 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_model (and thus to your code) when repoze.bfg.traversal.find_model() is called with an equivalent path string or tuple.

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.

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 repoze.bfg.registry.Registry.notify(), zope.component.event.dispatch() or zope.component.event.objectEventNotify().

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

testing_add_template(path, renderer=None)
Unit/integration testing helper: register a template renderer at path (usually a relative filename ala templates/foo.pt) 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 repoze.bfg.chameleon_zpt.render_template_to_response() function or repoze.bfg.chameleon_text.render_template_to_response() function or any other render_template* API of any built-in templating system (see repoze.bfg.chameleon_zpt and repoze.bfg.chameleon_text).

Previous topic

repoze.bfg.chameleon_zpt

Next topic

repoze.bfg.events

This Page