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)[ソース]¶
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()
andpyramid.config.Configurator.end()
as well aspyramid.config.Configurator.commit()
.with Configurator(settings=settings) as config: config.add_route('home', '/') app = config.make_wsgi_app()
If the
registry
argument is notNone
, it must be an instance of thepyramid.registry.Registry
class representing the registry to configure. Ifregistry
isNone
, the configurator will create apyramid.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.警告
If
registry
is assigned the above-mentioned class instance, all other constructor arguments are ignored, with the exception ofpackage
.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 arenderer
argument, into absolute paths. IfNone
is passed (the default), the package is assumed to be the Python package in which the caller of theConfigurator
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 mainConfigurator
was created. IfNone
is passed (the default), theroot_package
will be derived from thepackage
argument. Thepackage
attribute is always pointing at the package being included when usinginclude()
, whereas theroot_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 thepyramid.registry.Registry.settings
attribute (akarequest.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 isNone
, 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.注釈
A
ConfigurationError
will be raised when an authorization policy is supplied without also supplying an authentication policy (authorization requires authentication).If
renderers
isNone
(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 topyramid.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 thelogging.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 isNone
, 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 isNone
, 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
isNone
, 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, thesession_factory
will be used to create a session object whenrequest.session
is accessed. Note that the same outcome can be achieved by callingpyramid.config.Configurator.set_session_factory()
. By default, this argument isNone
, indicating that no session factory will be configured (and thus accessingrequest.session
will throw an error) unlessset_session_factory
is called later during configuration.If
autocommit
isTrue
, every method called on the configurator will cause an immediate action, and no configuration conflict detection will be used. Ifautocommit
isFalse
, most methods of the configurator will defer their action untilpyramid.config.Configurator.commit()
is called. Whenpyramid.config.Configurator.commit()
is called, the actions implied by the called methods will be checked for configuration conflicts unlessautocommit
isTrue
. If a conflict is detected, aConfigurationConflictError
will be raised. Callingpyramid.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 (seepyramid.interfaces.IViewMapperFactory
). Ifdefault_view_mapper
is not passed, a superdefault view mapper will be used.If
exceptionresponse_view
is passed, it must be a view callable orNone
. If it is a view callable, it will be used as an exception view callable when an exception response is raised. Ifexceptionresponse_view
isNone
, no exception response view will be registered, and all raised exception responses will be bubbled up to Pyramid's caller. By default, thepyramid.httpexceptions.default_exceptionresponse_view
function is used as theexceptionresponse_view
.If
route_prefix
is passed, all routes added withpyramid.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'sTrue
, introspection values during actions will be kept for use for tools like the debug toolbar. If it'sFalse
, introspection values provided by registrations will be ignored. By default, it isTrue
.バージョン 1.1 で追加: The
exceptionresponse_view
argument.バージョン 1.2 で追加: The
route_prefix
argument.バージョン 1.3 で追加: The
introspection
argument.バージョン 1.6 で追加: The
root_package
argument. Theresponse_factory
argument.バージョン 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.警告
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>)[ソース]¶
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 therequest
argument onto the thread local stack consulted by variouspyramid.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.バージョン 1.8 で変更: The current threadlocal request is propagated if the current threadlocal registry remains unchanged.
- end()[ソース]¶
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)[ソース]¶
Include a configuration callable, to support imperative application extensibility.
警告
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 namedincludeme
, which will be treated as the configuration callable.For example, if the
includeme
function below lives in a module namedmyapp.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 usingpyramid.config.Configurator.route_prefix_context()
. Any calls topyramid.config.Configurator.add_route()
within the included callable will have their pattern prefixed with the value ofroute_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 theroute_prefix
argument will be prepended to the pattern.バージョン 1.2 で追加: The
route_prefix
parameter.バージョン 1.9 で変更: The included function is wrapped with a call to
pyramid.config.Configurator.begin()
andpyramid.config.Configurator.end()
while it is executed.
- make_wsgi_app()[ソース]¶
Commits any pending configuration statements, sends a
pyramid.events.ApplicationCreated
event to all listeners, adds this configuration's registry topyramid.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, orNone
.Example Usage:
config = Configurator() with config.route_prefix_context('foo'): config.add_route('bar', '/bar')
バージョン 1.10 で追加.
- scan(package=None, categories=('pyramid',), onerror=None, ignore=None, **kw)[ソース]¶
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). Ifpackage
isNone
, 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 frompyramid.view.view_config
. See the Venusian documentation for more information about limiting a scan by using an explicit set of categories. PassNone
to pick up all Venusian decorators.The
onerror
argument, if provided, should be a Venusianonerror
callback function. The onerror function is passed tovenusian.Scanner.scan()
to influence error behavior when an exception is raised during the scanning process. See the Venusian documentation for more information aboutonerror
callbacks.The
ignore
argument, if provided, should be a Venusianignore
value. Providing anignore
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 ofignore
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 themy.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 theignore
argument.To perform a
scan
, Pyramid creates a VenusianScanner
object. Thekw
argument represents a set of keyword arguments to pass to the VenusianScanner
object's constructor. See the venusian documentation (itsScanner
class) for more information about the constructor. By default, the only keyword arguments passed to the Scanner constructor are{'config':self}
whereself
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.バージョン 1.1 で追加: The
**kw
argument.バージョン 1.3 で追加: The
ignore
argument.バージョン 2.0 で変更: The
categories
argument now defaults to['pyramid']
instead ofNone
to control which decorator callbacks are executed.
Adding Routes and Views
- add_route(name, pattern=None, factory=None, for_=None, header=None, xhr=None, accept=None, path_info=None, request_method=None, request_param=None, traverse=None, custom_predicates=(), use_global_views=False, path=None, pregenerator=None, static=False, inherit_slash=None, **predicates)¶
Add a route configuration to the current configuration state. Arguments to
add_route
are divided into predicate and non-predicate types. Route predicate arguments narrow the circumstances in which a route will 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. See The Resource Tree for more information about root factories.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 thefactory
associated with this route).The syntax of the
traverse
argument is the same as it is forpattern
. For example, if thepattern
provided toadd_route
isarticles/{article}/edit
, and thetraverse
argument provided toadd_route
is/{article}
, when a request comes in that causes the route to match in such a way that thearticle
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. Thetraverse
pattern should not contain segment markers that do not exist in thepattern
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). Thetraverse
argument to add_route allows you to associate route patterns with an arbitrary traversal path without using a*traverse
remainder marker; instead you can use other match information.Note that the
traverse
argument toadd_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 thepyramid.request.Request.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.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).static
If
static
isTrue
, this route will never match an incoming request; it will only be useful for URL generation. By default,static
isFalse
. See Static Routes.バージョン 1.1 で追加.
inherit_slash
This argument can only be used when the
pattern
is an empty string (''
). By default, the composed route pattern will always include a trailing slash, but this argument provides a way to opt-out if both, you (the developer invokingadd_route
) and the integrator (the developer setting the route prefix), agree that the pattern should not contain a trailing slash. For example:with config.route_prefix_context('/users'): config.add_route('users', '', inherit_slash=True)
In this example, the resulting route pattern will be
/users
. Alternatively, if the route prefix were/users/
, then the resulting route pattern would be/users/
.バージョン 2.0 で追加.
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.注釈
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 thepattern
argument isNone
. If bothpath
andpattern
are passed,pattern
wins.xhr
This value should be either
True
orFalse
. If this value is specified and isTrue
, the request must possess anHTTP_X_REQUESTED_WITH
(akaX-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 returnsFalse
, route matching continues.request_method
A string representing an HTTP method name, e.g.
GET
,POST
,HEAD
,DELETE
,PUT
or a tuple of elements containing HTTP method names. If this argument is not specified, this route will match if the request has any request method. If this predicate returnsFalse
, route matching continues.バージョン 1.2 で変更: The ability to pass a tuple of items as
request_method
. Previous versions allowed only a string.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 returnTrue
. If this predicate returnsFalse
, route matching continues.request_param
This value can be any string or an iterable of strings. 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 HTTPGET
orPOST
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_param="foo=123"
, then both the key (foo
) must exist in therequest.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 returnsFalse
, route matching continues.header
This argument can be a string or an iterable of strings for HTTP headers. The matching is determined as follow:
If a string does not contain a
:
(colon), it will be considered to be the header name (exampleIf-Modified-Since
). In this case, the header specified by the name must be present in the request for this string to match. Case is not significant.If a string contains a colon, it will be considered a name/value pair (for example
User-Agent:Mozilla/.*
orHost:localhost
), where the value part is a regular expression. The header specified by the name must be present in the request and the regular expression specified as the value part must match the value of the request header. Case is not significant for the header name, but it is for the value.
All strings must be matched for this predicate to return
True
. If this predicate returnsFalse
, route matching continues.accept
A media type that will be matched against the
Accept
HTTP request header. If this value is specified, it may be a specific media type such astext/html
, or a list of the same. If the media type is acceptable by theAccept
header of the request, or if theAccept
header isn't set at all in the request, this predicate will match. If this does not match theAccept
header of the request, route matching continues.If
accept
is not specified, theHTTP_ACCEPT
HTTP header is not taken into consideration when deciding whether or not to select the route.Unlike the
accept
argument topyramid.config.Configurator.add_view()
, this value is strictly a predicate and supportspyramid.config.not_()
.バージョン 1.10 で変更: Specifying a media range is deprecated due to changes in WebOb and ambiguities that occur when trying to match ranges against ranges in the
Accept
header. Support will be removed in Pyramid 2.0. Use a list of specific media types to match more than one type.バージョン 2.0 で変更: Removed support for media ranges.
is_authenticated
This value, if specified, must be either
True
orFalse
. If it is specified andTrue
, only a request from an authenticated user, as determined by the security policy in use, will satisfy the predicate. If it is specified andFalse
, only a request from a user who is not authenticated will satisfy the predicate.バージョン 2.0 で追加.
effective_principals
If specified, this value should be a principal identifier or a sequence of principal identifiers. If the
pyramid.request.Request.effective_principals
property indicates that every principal named in the argument list is present in the current request, this predicate will return True; otherwise it will return False. For example:effective_principals=pyramid.authorization.Authenticated
oreffective_principals=('fred', 'group:admins')
.バージョン 1.4a4 で追加.
バージョン 2.0 で非推奨: Use
is_authenticated
or a custom predicate.custom_predicates
バージョン 1.5 で非推奨: 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
andrequest
and should return eitherTrue
orFalse
after doing arbitrary evaluation of the info and/or the request. If all custom and non-custom predicate callables returnTrue
the associated route will be considered viable for a given request. If any predicate callable returnsFalse
, route matching continues. Note that the valueinfo
passed to a custom route predicate is a dictionary containing matching information; see Custom Route Predicates for more information aboutinfo
.**predicates
Pass extra keyword parameters to use custom predicates registered via
pyramid.config.Configurator.add_route_predicate()
. More than one custom predicate can be used at the same time. See View and Route Predicates for more information about custom predicates.バージョン 1.4 で追加.
- add_static_view(name, path, cache_max_age=3600, permission=NO_PERMISSION_REQUIRED)¶
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 theExpires
andCache-Control
headers for static assets served. Note that this argument has no effect when thename
is a url prefix. By default, this argument isNone
, meaning that no particular Expires or Cache-Control headers are set in the response.The
content_encodings
keyword argument is a list of alternative file encodings supported in theAccept-Encoding
HTTP Header. Alternative files are found using file extensions defined inmimetypes.encodings_map
. An encoded asset will be returned with theContent-Encoding
header set to the selected encoding. If the asset contains alternative encodings then theAccept-Encoding
value will be added to the response'sVary
header. By default, the list is empty and no alternatives will be supported.The
permission
keyword argument is used to specify the permission required by a user to execute the static view. By default, it is the stringpyramid.security.NO_PERMISSION_REQUIRED
, 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. Ifpermission
is specified, the security checking will be performed against the default root factory ACL.Any other keyword arguments sent to
add_static_view
are passed on topyramid.config.Configurator.add_route()
(e.g.factory
, perhaps to define a custom factory with a custom ACL for this static view).Usage
The
add_static_view
function is typically used in conjunction with thepyramid.request.Request.static_url()
method.add_static_view
adds a view which renders a static asset when some URL is visited;pyramid.request.Request.static_url()
generates a URL to that asset.The
name
argument toadd_static_view
is usually a simple URL prefix (e.g.'images'
). When this is the case, thepyramid.request.Request.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.request.Request.static_url()
:request.static_url('mypackage:images/logo.png')
When
add_static_view
is called with aname
argument that represents a URL prefix, as it is above, subsequent calls topyramid.request.Request.static_url()
with paths that start with thepath
argument passed toadd_static_view
will generate a URL something likehttp://<Pyramid app URL>/images/logo.png
, which will cause thelogo.png
file in theimages
subdirectory of themypackage
package to be served.add_static_view
can alternately be used with aname
argument which is a URL, causing static assets to be served from an external webserver. This happens when thename
argument is a fully qualified URL (e.g. starts withhttp://
or similar). In this mode, thename
is used as the prefix of the full URL when generating a URL usingpyramid.request.Request.static_url()
. Furthermore, if a protocol-relative URL (e.g.//example.com/images
) is used as thename
argument, the generated URL will use the protocol of the request (http or https, respectively).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.request.Request.static_url()
for that static view will be prefixed withhttp://example.com/images
(the external webserver listening onexample.com
must be itself configured to respond properly to such a request.):static_url('mypackage:images/logo.png', request)
See Serving Static Assets for more information.
バージョン 2.0 で変更: Added the
content_encodings
argument.
- 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=None, accept=None, header=None, path_info=None, custom_predicates=(), context=None, decorator=None, mapper=None, http_cache=None, match_param=None, require_csrf=None, exception_only=False, **view_options)¶
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 arenderer
argument is passed, and aview
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
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. This is often a string like
view
oredit
.If
permission
is omitted, a default permission may be used for this view registration if one was named as thepyramid.config.Configurator
constructor'sdefault_permission
argument, or ifpyramid.config.Configurator.set_default_permission()
was used prior to this view registration. Pass the valuepyramid.security.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
This knob is most useful when the view definition is a class.
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. Theattr
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 namedindex
and you wanted to use this method instead of the class'__call__
method to return the response, you'd sayattr="index"
in the view configuration for the 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
) naming a renderer implementation. If therenderer
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 therenderer
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 formsome.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 unmodified).http_cache
バージョン 1.1 で追加.
When you supply an
http_cache
value to a view configuration, theExpires
andCache-Control
headers of a response generated by the associated view callable are modified. The value forhttp_cache
may be one of the following:A nonzero integer. If it's a nonzero integer, it's treated as a number of seconds. This number of seconds will be used to compute the
Expires
header and theCache-Control: max-age
parameter of responses to requests which call this view. For example:http_cache=3600
instructs the requesting browser to 'cache this response for an hour, please'.A
datetime.timedelta
instance. If it's adatetime.timedelta
instance, it will be converted into a number of seconds, and that number of seconds will be used to compute theExpires
header and theCache-Control: max-age
parameter of responses to requests which call this view. For example:http_cache=datetime.timedelta(days=1)
instructs the requesting browser to 'cache this response for a day, please'.Zero (
0
). If the value is zero, theCache-Control
andExpires
headers present in all responses from this view will be composed such that client browser cache (and any intermediate caches) are instructed to never cache the response.A two-tuple. If it's a two tuple (e.g.
http_cache=(1, {'public':True})
), the first value in the tuple may be a nonzero integer or adatetime.timedelta
instance; in either case this value will be used as the number of seconds to cache the response. The second value in the tuple must be a dictionary. The values present in the dictionary will be used as input to theCache-Control
response header. For example:http_cache=(3600, {'public':True})
means 'cache for an hour, and addpublic
to the Cache-Control header of the response'. All keys and values supported by thewebob.cachecontrol.CacheControl
interface may be added to the dictionary. Supplying{'public':True}
is equivalent to callingresponse.cache_control.public = True
.
Providing a non-tuple value as
http_cache
is equivalent to callingresponse.cache_expires(value)
within your view's body.Providing a two-tuple value as
http_cache
is equivalent to callingresponse.cache_expires(value[0], **value[1])
within your view's body.If you wish to avoid influencing, the
Expires
header, and instead wish to only influenceCache-Control
headers, pass a tuple ashttp_cache
with the first element ofNone
, e.g.:(None, {'public':True})
.If you wish to prevent a view that uses
http_cache
in its configuration from having its caching response headers changed by this machinery, setresponse.cache_control.prevent_auto = True
before returning the response from the view. This effectively disables any HTTP caching done byhttp_cache
for that response.require_csrf
バージョン 1.7 で追加.
A boolean option or
None
. Default:None
.If this option is set to
True
then CSRF checks will be enabled for requests to this view. The required token or header default tocsrf_token
andX-CSRF-Token
, respectively.CSRF checks only affect "unsafe" methods as defined by RFC2616. By default, these methods are anything except
GET
,HEAD
,OPTIONS
, andTRACE
.The defaults here may be overridden by
pyramid.config.Configurator.set_default_csrf_options()
.This feature requires a configured session factory.
If this option is set to
False
then CSRF checks will be disabled regardless of the defaultrequire_csrf
setting passed toset_default_csrf_options
.See Checking CSRF Tokens Automatically for more information.
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 therequest.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 Configuration. The "best" wrapper view will be found based on the lookup ordering: "under the hood" this wrapper view is looked up viapyramid.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, or an iterable of the aforementioned) which will be used to decorate the registered view callable. The decorator function(s) will be called with the view callable as a single argument. The view callable it is passed will accept
(context, request)
. The decorator(s) must return a replacement view callable which also accepts(context, request)
.If decorator is an iterable, the callables will be combined and used in the order provided as a decorator. For example:
@view_config(..., decorator=(decorator2, decorator1)) def myview(request): ....
Is similar to doing:
@view_config(...) @decorator2 @decorator1 def myview(request): ...
Except with the existing benefits of
decorator=
(having a common decorator syntax for all view calling conventions and not having to think about preserving function attributes such as__name__
and__module__
within decorator logic).An important distinction is that each decorator will receive a response object implementing
pyramid.interfaces.IResponse
instead of the raw value returned from the view callable. All decorators in the chain must return a response object or raise an exception:def log_timer(wrapped): def wrapper(context, request): start = time.time() response = wrapped(context, request) duration = time.time() - start response.headers['X-View-Time'] = '%.3f' % (duration,) log.info('view took %.3f seconds', duration) return response return wrapper
バージョン 1.4a4 で変更: Passing an iterable.
mapper
A Python object or dotted Python name which refers to a view mapper, or
None
. By default it isNone
, 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.accept
A media type that will be matched against the
Accept
HTTP request header. If this value is specified, it must be a specific media type such astext/html
ortext/html;level=1
. If the media type is acceptable by theAccept
header of the request, or if theAccept
header isn't set at all in the request, this predicate will match. If this does not match theAccept
header of the request, view matching continues.If
accept
is not specified, theHTTP_ACCEPT
HTTP header is not taken into consideration when deciding whether or not to invoke the associated view callable.The
accept
argument is technically not a predicate and does not support wrapping withpyramid.config.not_()
.See Accept Header Content Negotiation for more information.
バージョン 1.10 で変更: Specifying a media range is deprecated and will be removed in Pyramid 2.0. Use explicit media types to avoid any ambiguities in content negotiation.
バージョン 2.0 で変更: Removed support for media ranges.
exception_only
バージョン 1.8 で追加.
When this value is
True
, thecontext
argument must be a subclass ofException
. This flag indicates that only an exception view should be created, and that this view should not match if the traversal context matches thecontext
argument. If thecontext
is a subclass ofException
and this value isFalse
(the default), then a view will be registered to match the traversal context as well.Predicate Arguments
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
asfor_
(an older, still-supported spelling). If the view should only match when handling exceptions, then set theexception_only
toTrue
.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.request_type
request_method
This value can be either a string (such as
"GET"
,"POST"
,"PUT"
,"DELETE"
,"HEAD"
or"OPTIONS"
) representing an HTTPREQUEST_METHOD
, or a tuple containing one or more of these strings. A view declaration with this argument ensures that the view will only be called when themethod
attribute of the request (aka theREQUEST_METHOD
of the WSGI environment) matches a supplied value. Note that use ofGET
also implies that the view will respond toHEAD
as of Pyramid 1.4.バージョン 1.2 で変更: The ability to pass a tuple of items as
request_method
. Previous versions allowed only a string.request_param
This value can be any string or any sequence of strings. 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 HTTPGET
orPOST
variable) that has a name which matches the supplied value (if the value is a string) or values (if the value is a tuple). If any value supplied has a=
sign in it, e.g.request_param="foo=123"
, then the key (foo
) must both exist in therequest.params
dictionary, and the value must match the right hand side of the expression (123
) for the view to "match" the current request.match_param
バージョン 1.2 で追加.
This value can be a string of the format "key=value" or a tuple containing one or more of these strings.
A view declaration with this argument ensures that the view will only be called when the request has key/value pairs in its matchdict that equal those supplied in the predicate. e.g.
match_param="action=edit"
would require theaction
parameter in the matchdict match the right hand side of the expression (edit
) for the view to "match" the current request.If the
match_param
is a tuple, every key/value pair must match for the predicate to pass.containment
This value should be a Python class or interface (or a dotted Python name) that an object in the lineage of the context 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
orFalse
. If this value is specified and isTrue
, the request must possess anHTTP_X_REQUESTED_WITH
(akaX-Requested-With
) header that has the valueXMLHttpRequest
for this view to be found and called. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries.header
This argument can be a string or an iterable of strings for HTTP headers. The matching is determined as follow:
If a string does not contain a
:
(colon), it will be considered to be a header name (exampleIf-Modified-Since
). In this case, the header specified by the name must be present in the request for this string to match. Case is not significant.If a string contains a colon, it will be considered a name/value pair (for example
User-Agent:Mozilla/.*
orHost:localhost
), where the value part is a regular expression. The header specified by the name must be present in the request and the regular expression specified as the value part must match the value of the request header. Case is not significant for the header name, but it is for the value.
All strings must be matched for this predicate to return
True
. If this predicate returnsFalse
, view 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 beTrue
.physical_path
If specified, this value should be a string or a tuple representing the physical path of the context found via traversal for this predicate to match as true. For example:
physical_path='/'
orphysical_path='/a/b/c'
orphysical_path=('', 'a', 'b', 'c')
. This is not a path prefix match or a regex, it's a whole-path match. It's useful when you want to always potentially show a view when some object is traversed to, but you can't be sure about what kind of object it will be, so you can't use thecontext
predicate. The individual path elements in between slash characters or in tuple elements should be the Unicode representation of the name of the resource and should not be encoded in any way.バージョン 1.4a3 で追加.
is_authenticated
This value, if specified, must be either
True
orFalse
. If it is specified andTrue
, only a request from an authenticated user, as determined by the security policy in use, will satisfy the predicate. If it is specified andFalse
, only a request from a user who is not authenticated will satisfy the predicate.バージョン 2.0 で追加.
effective_principals
If specified, this value should be a principal identifier or a sequence of principal identifiers. If the
pyramid.request.Request.effective_principals
property indicates that every principal named in the argument list is present in the current request, this predicate will return True; otherwise it will return False. For example:effective_principals=pyramid.authorization.Authenticated
oreffective_principals=('fred', 'group:admins')
.バージョン 1.4a4 で追加.
バージョン 2.0 で非推奨: Use
is_authenticated
or a custom predicate.custom_predicates
バージョン 1.5 で非推奨: This value should be a sequence of references to custom predicate callables. Each custom predicate callable should accept two arguments:
context
andrequest
and should return eitherTrue
orFalse
after doing arbitrary evaluation of the context and/or the request. The ability to register custom view predicates viapyramid.config.Configurator.add_view_predicate()
obsoletes this argument, but it is kept around for backwards compatibility.**view_options
Pass extra keyword parameters to use custom predicates or set a value for a view deriver. See
pyramid.config.Configurator.add_view_predicate()
andpyramid.config.Configurator.add_view_deriver()
. See View and Route Predicates for more information about custom predicates and View Derivers for information about view derivers.バージョン 2.0 で変更: Removed support for the
check_csrf
predicate.
- add_notfound_view(view=None, attr=None, renderer=None, wrapper=None, route_name=None, request_type=None, request_method=None, request_param=None, containment=None, xhr=None, accept=None, header=None, path_info=None, custom_predicates=(), decorator=None, mapper=None, match_param=None, append_slash=False, **view_options)¶
Add a default Not Found View to the current configuration state. The view will be called when Pyramid or application code raises an
pyramid.httpexceptions.HTTPNotFound
exception (e.g., when a view cannot be found for the request). The simplest example is:def notfound(request): return Response('Not Found', status='404 Not Found') config.add_notfound_view(notfound)
If
view
argument is not provided, the view callable defaults todefault_exceptionresponse_view()
.All arguments except
append_slash
have the same meaning aspyramid.config.Configurator.add_view()
and each predicate argument restricts the set of circumstances under which this notfound view will be invoked. Unlikepyramid.config.Configurator.add_view()
, this method will raise an exception if passedname
,permission
,require_csrf
,context
,for_
, orexception_only
keyword arguments. These argument values make no sense in the context of a Not Found View.If
append_slash
isTrue
, when this Not Found View is invoked, and the current path info does not end in a slash, the notfound logic will attempt to find a route that matches the request's path info suffixed with a slash. If such a route exists, Pyramid will issue a redirect to the URL implied by the route; if it does not, Pyramid will return the result of the view callable provided asview
, as normal.If the argument provided as
append_slash
is not a boolean but instead implementsIResponse
, the append_slash logic will behave as ifappend_slash=True
was passed, but the provided class will be used as the response class instead of the defaultHTTPTemporaryRedirect
response class when a redirect is performed. For example:from pyramid.httpexceptions import HTTPMovedPermanently config.add_notfound_view(append_slash=HTTPMovedPermanently)
The above means that a redirect to a slash-appended route will be attempted, but instead of
HTTPTemporaryRedirect
being used,HTTPMovedPermanently will be used
for the redirect response if a slash-appended route is found.HTTPTemporaryRedirect
class is used as default response, which is equivalent toHTTPFound
with addition of redirecting with the same HTTP method (useful when doing POST requests).バージョン 1.3 で追加.
バージョン 1.6 で変更: The
append_slash
argument was modified to allow any object that implements theIResponse
interface to specify the response class used when a redirect is performed.バージョン 1.8 で変更: The view is created using
exception_only=True
.
- add_forbidden_view(view=None, attr=None, renderer=None, wrapper=None, route_name=None, request_type=None, request_method=None, request_param=None, containment=None, xhr=None, accept=None, header=None, path_info=None, custom_predicates=(), decorator=None, mapper=None, match_param=None, **view_options)¶
Add a forbidden view to the current configuration state. The view will be called when Pyramid or application code raises a
pyramid.httpexceptions.HTTPForbidden
exception and the set of circumstances implied by the predicates provided are matched. The simplest example is:def forbidden(request): return Response('Forbidden', status='403 Forbidden') config.add_forbidden_view(forbidden)
If
view
argument is not provided, the view callable defaults todefault_exceptionresponse_view()
.All arguments have the same meaning as
pyramid.config.Configurator.add_view()
and each predicate argument restricts the set of circumstances under which this forbidden view will be invoked. Unlikepyramid.config.Configurator.add_view()
, this method will raise an exception if passedname
,permission
,require_csrf
,context
,for_
, orexception_only
keyword arguments. These argument values make no sense in the context of a forbidden exception view.バージョン 1.3 で追加.
バージョン 1.8 で変更: The view is created using
exception_only=True
.
- add_exception_view(view=None, context=None, **view_options)¶
Add an exception view for the specified
exception
to the current configuration state. The view will be called when Pyramid or application code raises the given exception.This method accepts almost all of the same arguments as
pyramid.config.Configurator.add_view()
except forname
,permission
,for_
,require_csrf
, andexception_only
.By default, this method will set
context=Exception
, thus registering for most default Python exceptions. Any subclass ofException
may be specified.バージョン 1.8 で追加.
Adding an Event Subscriber
- add_subscriber(subscriber, iface=None, **predicates)¶
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 objectevent
whenever Pyramid emits an event associated with theiface
, 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.Any number of predicate keyword arguments may be passed in
**predicates
. Each predicate named will narrow the set of circumstances in which the subscriber will be invoked. Each named predicate must have been registered viapyramid.config.Configurator.add_subscriber_predicate()
before it can be used. See Subscriber Predicates for more information.バージョン 1.4 で追加: The
**predicates
argument.
Using Security
- set_security_policy(policy)¶
Override the Pyramid security policy in the current configuration. The
policy
argument must be an instance of a security policy or a dotted Python name that points at an instance of a security policy.注釈
Using the
security_policy
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
- set_authentication_policy(policy)¶
バージョン 2.0 で非推奨: Authentication policies have been replaced by security policies. See Upgrading Authentication/Authorization for more information.
Override the Pyramid authentication policy in the current configuration. The
policy
argument must be an instance of an authentication policy or a dotted Python name that points at an instance of an authentication policy.注釈
Using the
authentication_policy
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
- set_authorization_policy(policy)¶
バージョン 2.0 で非推奨: Authentication policies have been replaced by security policies. See Upgrading Authentication/Authorization for more information.
Override the Pyramid authorization policy in the current configuration. The
policy
argument must be an instance of an authorization policy or a dotted Python name that points at an instance of an authorization policy.注釈
Using the
authorization_policy
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
- set_default_csrf_options(require_csrf=True, token='csrf_token', header='X-CSRF-Token', safe_methods=('GET', 'HEAD', 'OPTIONS', 'TRACE'), check_origin=True, allow_no_origin=False, callback=None)¶
Set the default CSRF options used by subsequent view registrations.
require_csrf
controls whether CSRF checks will be automatically enabled on each view in the application. This value is used as the fallback whenrequire_csrf
is left at the default ofNone
onpyramid.config.Configurator.add_view()
.token
is the name of the CSRF token used in the body of the request, accessed viarequest.POST[token]
. Default:csrf_token
.header
is the name of the header containing the CSRF token, accessed viarequest.headers[header]
. Default:X-CSRF-Token
.If
token
orheader
are set toNone
they will not be used for checking CSRF tokens.safe_methods
is an iterable of HTTP methods which are expected to not contain side-effects as defined by RFC2616. Safe methods will never be automatically checked for CSRF tokens. Default:('GET', 'HEAD', 'OPTIONS', TRACE')
.check_origin
is a boolean. IfFalse
, theOrigin
andReferer
headers will not be validated as part of automated CSRF checks.allow_no_origin
is a boolean. IfTrue
, a request lacking both anOrigin
andReferer
header will pass the CSRF check. This option has no effect ifcheck_origin
isFalse
.If
callback
is set, it must be a callable accepting(request)
and returningTrue
if the request should be checked for a valid CSRF token. This callback allows an application to support alternate authentication methods that do not rely on cookies which are not subject to CSRF attacks. For example, if a request is authenticated using theAuthorization
header instead of a cookie, this may returnFalse
for that request so that clients do not need to send theX-CSRF-Token
header. The callback is only tested for non-safe methods as defined bysafe_methods
.バージョン 1.7 で追加.
バージョン 1.8 で変更: Added the
callback
option.バージョン 2.0 で変更: Added the
allow_no_origin
andcheck_origin
options.
- set_csrf_storage_policy(policy)¶
Set the CSRF storage policy used by subsequent view registrations.
policy
is a class that implements thepyramid.interfaces.ICSRFStoragePolicy()
interface and defines how to generate and persist CSRF tokens.
- set_default_permission(permission)¶
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.
警告
If a default permission is in effect, view configurations meant to create a truly anonymously accessible view (even exception view views) must use the value of the permission importable as
pyramid.security.NO_PERMISSION_REQUIRED
. When this string is used as thepermission
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.
注釈
Using the
default_permission
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
- 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 viaadd_view
already end up in there). For example:config = Configurator() config.add_permission('view')
Extending the Request Object
- add_request_method(callable=None, name=None, property=False, reify=False)¶
Add a property or method to the request object.
When adding a method to the request,
callable
may be any function that receives the request object as the first parameter. Ifname
isNone
then it will be computed from the name of thecallable
.When adding a property to the request,
callable
can either be a callable that accepts the request as its single positional parameter, or it can be a property descriptor. Ifcallable
is a property descriptor, it has to be an instance of a class which is a subclass ofproperty
. Ifname
isNone
, the name of the property will be computed from the name of thecallable
.If the
callable
is a property descriptor aValueError
will be raised ifname
isNone
orreify
isTrue
.See
pyramid.request.Request.set_property()
for more details onproperty
vsreify
. Whenreify
isTrue
, the value ofproperty
is assumed to also beTrue
.In all cases,
callable
may also be a dotted Python name which refers to either a callable or a property descriptor.If
callable
isNone
then the method is only used to assist in conflict detection between different addons requesting the same attribute on the request object.This is the recommended method for extending the request object and should be used in favor of providing a custom request factory via
pyramid.config.Configurator.set_request_factory()
.バージョン 1.4 で追加.
Using I18N
- add_translation_dirs(*specs, **kw)¶
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')
The translation directories are defined as a list in which translations defined later have precedence over translations defined earlier.
By default, consecutive calls to
add_translation_dirs
will add directories to the start of the list. This means later calls toadd_translation_dirs
will have their translations trumped by earlier calls. If you explicitly need this call to trump an earlier call then you may setoverride
toTrue
.If multiple specs are provided in a single call to
add_translation_dirs
, the directories will be inserted in the order they're provided (earlier items are trumped by later items).バージョン 1.8 で変更: The
override
parameter was added to allow a later call toadd_translation_dirs
to override an earlier call, inserting folders at the beginning of the translation directory list.
- 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. 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.
注釈
Using the
locale_negotiator
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
Overriding Assets
- override_asset(to_override, override_with)¶
Add a Pyramid asset override to the current configuration state.
to_override
is an asset specification to the asset being overridden.override_with
is an asset specification to the asset that is performing the override. This may also be an absolute path.See Static Assets for more information about asset overrides.
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 thepyramid.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 thepyramid.config.Configurator
constructor.注釈
the
pyramid.registry.Registry.settings
API performs the same duty.
Hooking Pyramid Behavior
- add_accept_view_order(value, weighs_more_than=None, weighs_less_than=None)¶
Specify an ordering preference for the
accept
view option used during view lookup.By default, if two views have different
accept
options and a request specifiesAccept: */*
or omits the header entirely then it is random which view will be selected. This method provides a way to specify a server-side, relative ordering between accept media types.value
should be a media type as specified by RFC 7231#section-5.3.2. For example,text/plain;charset=utf8
,application/json
ortext/html
.weighs_more_than
andweighs_less_than
control the ordering of media types. Each value may be a string or a list of strings. If all options forweighs_more_than
(orweighs_less_than
) cannot be found, it is an error.Earlier calls to
add_accept_view_order
are given higher priority over later calls, assuming similar constraints but standard conflict resolution mechanisms can be used to override constraints.See Accept Header Content Negotiation for more information.
バージョン 1.10 で追加.
- add_renderer(name, factory)¶
Add a Pyramid renderer factory to the current configuration state.
The
name
argument is the renderer name. UseNone
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.
- add_resource_url_adapter(adapter, resource_iface=None)¶
バージョン 1.3 で追加.
When you add a traverser as described in Changing the Traverser, it's convenient to continue to use the
pyramid.request.Request.resource_url()
API. However, since the way traversal is done may have been modified, the URLs thatresource_url
generates by default may be incorrect when resources are returned by a custom traverser.If you've added a traverser, you can change how
resource_url()
generates a URL for a specific type of resource by calling this method.The
adapter
argument represents a class that implements theIResourceURL
interface. The class constructor should accept two arguments in its constructor (the resource and the request) and the resulting instance should provide the attributes detailed in that interface (virtual_path
andphysical_path
, in particular).The
resource_iface
argument represents a class or interface that the resource should possess for this url adapter to be used whenpyramid.request.Request.resource_url()
looks up a resource url adapter. Ifresource_iface
is not passed, or it is passed asNone
, the url adapter will be used for every type of resource.See Changing How pyramid.request.Request.resource_url() Generates a URL for more information.
- add_response_adapter(adapter, type_or_iface)¶
When an object of type (or interface)
type_or_iface
is returned from a view callable, Pyramid will use the adapteradapter
to convert it into an object which implements thepyramid.interfaces.IResponse
interface. Ifadapter
is None, an object returned of type (or interface)type_or_iface
will itself be used as a response object.adapter
andtype_or_interface
may be Python objects or strings representing dotted names to importable Python global objects.See Changing How Pyramid Treats View Responses for more information.
- add_traverser(adapter, iface=None)¶
The superdefault traversal algorithm that Pyramid uses is explained in The Traversal Algorithm. Though it is rarely necessary, this default algorithm can be swapped out selectively for a different traversal pattern via configuration. The section entitled Changing the Traverser details how to create a traverser class.
For example, to override the superdefault traverser used by Pyramid, you might do something like this:
from myapp.traversal import MyCustomTraverser config.add_traverser(MyCustomTraverser)
This would cause the Pyramid superdefault traverser to never be used; instead all traversal would be done using your
MyCustomTraverser
class, no matter which object was returned by the root factory of this application. Note that we passed no arguments to theiface
keyword parameter. The default value ofiface
,None
represents that the registered traverser should be used when no other more specific traverser is available for the object returned by the root factory.However, more than one traversal algorithm can be active at the same time. The traverser used can depend on the result of the root factory. For instance, if your root factory returns more than one type of object conditionally, you could claim that an alternate traverser adapter should be used against one particular class or interface returned by that root factory. When the root factory returned an object that implemented that class or interface, a custom traverser would be used. Otherwise, the default traverser would be used. The
iface
argument represents the class of the object that the root factory might return or an interface that the object might implement.To use a particular traverser only when the root factory returns a particular class:
config.add_traverser(MyCustomTraverser, MyRootClass)
When more than one traverser is active, the "most specific" traverser will be used (the one that matches the class or interface of the value returned by the root factory most closely).
Note that either
adapter
oriface
can be a dotted Python name or a Python object.See Changing the Traverser for more information.
- add_tween(tween_factory, under=None, over=None)¶
バージョン 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.
注釈
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
andover
arguments allow the caller ofadd_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 thepyramid.tweens
configuration value is not set). Allowable values forunder
orover
(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
, orpyramid.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 namemyapp.tfactory
directly 'above' (inptweens
order) the main Pyramid request handler. Likewise, callingadd_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
(orover
) 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
norunder
is equivalent to specifyingunder=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
, andover
arguments are ignored when an explicit tween chain is specified using thepyramid.tweens
configuration value.For more information, see Registering Tweens.
- add_route_predicate(name, factory, weighs_more_than=None, weighs_less_than=None)¶
Adds a route predicate factory. The view predicate can later be named as a keyword argument to
pyramid.config.Configurator.add_route()
.name
should be the name of the predicate. It must be a valid Python identifier (it will be used as a keyword argument toadd_route
).factory
should be a predicate factory or dotted Python name which refers to a predicate factory.See View and Route Predicates for more information.
バージョン 1.4 で追加.
- add_subscriber_predicate(name, factory, weighs_more_than=None, weighs_less_than=None)¶
バージョン 1.4 で追加.
Adds a subscriber predicate factory. The associated subscriber predicate can later be named as a keyword argument to
pyramid.config.Configurator.add_subscriber()
in the**predicates
anonymous keyword argument dictionary.name
should be the name of the predicate. It must be a valid Python identifier (it will be used as a**predicates
keyword argument toadd_subscriber()
).factory
should be a predicate factory or dotted Python name which refers to a predicate factory.See Subscriber Predicates for more information.
- add_view_predicate(name, factory, weighs_more_than=None, weighs_less_than=None)¶
バージョン 1.4 で追加.
Adds a view predicate factory. The associated view predicate can later be named as a keyword argument to
pyramid.config.Configurator.add_view()
in thepredicates
anonyous keyword argument dictionary.name
should be the name of the predicate. It must be a valid Python identifier (it will be used as a keyword argument toadd_view
by others).factory
should be a predicate factory or dotted Python name which refers to a predicate factory.See View and Route Predicates for more information.
- add_view_deriver(deriver, name=None, under=None, over=None)¶
バージョン 1.7 で追加.
Add a view deriver to the view pipeline. View derivers are a feature used by extension authors to wrap views in custom code controllable by view-specific options.
deriver
should be a callable conforming to thepyramid.interfaces.IViewDeriver
interface.name
should be the name of the view deriver. There are no restrictions on the name of a view deriver. If left unspecified, the name will be constructed from the name of thederiver
.The
under
andover
options can be used to control the ordering of view derivers by providing hints about where in the view pipeline the deriver is used. Each option may be a string or a list of strings. At least one view deriver in each, the over and under directions, must exist to fully satisfy the constraints.under
means closer to the user-defined view callable, andover
means closer to view pipeline ingress.The default value for
over
isrendered_view
andunder
isdecorated_view
. This places the deriver somewhere between the two in the view pipeline. If the deriver should be placed elsewhere in the pipeline, such as abovedecorated_view
, then you MUST also specifyunder
to something earlier in the order, or aCyclicDependencyError
will be raised when trying to sort the derivers.See View Derivers for more information.
- set_execution_policy(policy)¶
Override the Pyramid execution policy in the current configuration. The
policy
argument must be an instance of anpyramid.interfaces.IExecutionPolicy
or a dotted Python name that points at an instance of an execution policy.
- set_request_factory(factory)¶
The object passed as
factory
should be an object (or a dotted Python name which refers to an object) which will be used by the Pyramid router to create all request objects. This factory object must have the same methods and attributes as thepyramid.request.Request
class (particularly__call__
, andblank
).See
pyramid.config.Configurator.add_request_method()
for a less intrusive way to extend the request objects with custom methods and properties.注釈
Using the
request_factory
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
- set_root_factory(factory)¶
Add a root factory to the current configuration state. If the
factory
argument isNone
a default root factory will be registered.注釈
Using the
root_factory
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
- set_session_factory(factory)¶
Configure the application with a session factory. If this method is called, the
factory
argument must be a session factory callable or a dotted Python name to that factory.注釈
Using the
session_factory
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
- set_view_mapper(mapper)¶
Setting a view mapper makes it possible to make use of view callable objects which implement different call signatures than the ones supported by Pyramid as described in its narrative documentation.
The
mapper
argument should be an object implementingpyramid.interfaces.IViewMapperFactory
or a dotted Python name to such an object. The providedmapper
will become the default view mapper to be used by all subsequent view configuration registrations.参考
See also Using a View Mapper.
注釈
Using the
default_view_mapper
argument to thepyramid.config.Configurator
constructor can be used to achieve the same purpose.
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 ifautocommit
isTrue
).警告
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 beNone
, 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
andkw
are tuple and dict objects respectively, which are passed tocallable
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 isTrue
).introspectables
is a sequence of introspectable objects (or the empty sequence if no introspectable objects are associated with this action). If this configurator'sintrospection
attribute isFalse
, these introspectables will be ignored.extra
provides a facility for inserting extra keys and values into an action dictionary.
- add_directive(name, directive, action_wrap=True)[ソース]¶
Add a directive method to the configurator.
警告
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 makesome.callable
accessible asconfig.somename
.some.callable
should be a function which acceptsconfig
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 asadd_view
,add_route
, etc.The
action_wrap
argument should beTrue
for directives which performconfig.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 toadd_directive
will override earlier calls.
- with_package(package)[ソース]¶
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.警告
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 throughderive_view
normalizes it to a callable which accepts two arguments:context
andrequest
.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 providedview
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. Ifattr
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 arenderer
argument is not supplied, the user-supplied view must itself return a response object.
Utility Methods
- absolute_asset_spec(relative_spec)[ソース]¶
Resolve the potentially relative asset specification string passed as
relative_spec
into an absolute asset specification string and return the string. Use thepackage
of this configurator as the package to which the asset specification will be considered relative when generating an absolute asset specification. If the providedrelative_spec
argument is already absolute, or if therelative_spec
is not a string, it is simply returned.
- maybe_dotted(dotted)[ソース]¶
Resolve the dotted Python name
dotted
to a global Python object. Ifdotted
is not a string, return it without attempting to do any name resolution. Ifdotted
is a relative dotted name (e.g..foo.bar
, consider it relative to thepackage
argument supplied to this Configurator's constructor.
ZCA-Related APIs
- hook_zca()¶
Call
zope.component.getSiteManager.sethook()
with the argumentpyramid.threadlocal.get_current_registry
, causing the Zope Component Architecture 'global' APIs such aszope.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 ofpyramid.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>)[ソース]¶
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. Usesetup_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 alatemplates/foo.pt
or an asset specification) and return the renderer object. If therenderer
argument is None, a 'dummy' renderer will be used. This function is useful when testing code that calls thepyramid.renderers.render()
function orpyramid.renderers.render_to_response()
function or any otherrender_*
orget_*
API of thepyramid.renderers
module.Note that calling this method for with a
path
argument representing a renderer factory type (e.g. forfoo.pt
usually implies thechameleon_zpt
renderer factory) clobbers any existing renderer factory registered for that type.注釈
This method is also available under the alias
testing_add_template
(an older name for it).
- testing_add_subscriber(event_iface=None)¶
Unit/integration testing helper: Registers a subscriber which listens for events of the type
event_iface
. This method returns a list object which is appended to by the subscriber whenever an event is captured.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 callpyramid.registry.Registry.notify()
, orzope.component.event.dispatch()
.The default value of
event_iface
(None
) implies a subscriber registered for any kind of event.
- 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
orfoo/bar
), the corresponding value will be returned tofind_resource
(and thus to your code) whenpyramid.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
, orpyramid.request.Request.has_permission()
,The behavior of the registered security policy depends on the arguments passed to this method.
- パラメータ
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.
バージョン 1.4 で追加: The
remember_result
argument.バージョン 1.4 で追加: The
forget_result
argument.バージョン 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).バージョン 1.3 で追加.
- introspector¶
The introspector related to this configuration. It is an instance implementing the
pyramid.interfaces.IIntrospector
interface.バージョン 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 alast
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)[ソース]¶
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:バージョン 1.5 で追加.
- PHASE0_CONFIG¶
- PHASE1_CONFIG¶
- PHASE2_CONFIG¶
- PHASE3_CONFIG¶