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

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

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

Добавлен: 02.01.2026

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

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

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

44. PYRAMID.CONFIG

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

1

2

3

4

5

from pyramid.config import Configurator

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

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

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

1

2

3

4

5

6

7

8

from pyramid.config import Configurator

def included(config): config.add_route(’show_users’, ’/show’)

def main(global_config, **settings): config = Configurator()

config.include(included, route_prefix=’/users’)

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

The route_prefix parameter is new as of Pyramid 1.2.

make_wsgi_app()

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

524


scan(package=None, categories=None, 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). 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 Pyramidrelated decorators such as pyramid.view.view_config. See the Venusian documentation for more information about limiting a scan by using an explicit set of categories.

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

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

latex-note.png

the ignore argument is new in Pyramid 1.3.

To perform a scan, Pyramid creates a Venusian Scanner object. The kw argument represents a set of keyword arguments to pass to the Venusian Scanner object’s constructor. See the venusian documentation (its Scanner class) for more

525

44. PYRAMID.CONFIG

information about the constructor. By default, the only keyword arguments passed to the Scanner constructor are {’config’:self} where self is this configurator object. This services the requirement of all built-in Pyramid decorators, but extension systems may require additional arguments. Providing this argument is not often necessary; it’s an advanced usage.

latex-note.png

the **kw argument is new in Pyramid 1.1

Adding Routes and Views

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

path=None, pregenerator=None, static=False)

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

Non-Predicate Arguments

name

The name of the route, e.g. myroute. This attribute is required. It must

be unique among all defined routes in a given application.

 

factory

 

A Python object (often a function or a class) or a dotted

Python

name which refers to the same object that will generate

a Pyra-

mid 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

526


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

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

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

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

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

pregenerator

 

This option

should be a callable object that implements

the

pyramid.interfaces.IRoutePregenerator

interface.

A pregenerator is a callable called by the

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

527


44. PYRAMID.CONFIG

static

If static is True, this route will never match an incoming request; it will only be useful for URL generation. By default, static is False. See Static Routes.

latex-note.png

New in Pyramid 1.1.

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.

latex-note.png

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

xhr

This value should be either True or False. If this value is specified and is True, the request must possess an HTTP_X_REQUESTED_WITH

(aka X-Requested-With) header for this route to match. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries. If this predicate returns False, route matching continues.

request_method

A string representing an HTTP method name, e.g. GET, POST, HEAD, DELETE, PUT 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 returns False, route matching continues.

528

latex-note.png

The ability to pass a tuple of items as request_method is new as of Pyramid 1.2. 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 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_param="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

529


44. PYRAMID.CONFIG

text/plain, a wildcard mimetype match token in the form text/* or a match-all wildcard mimetype match token in the form */*. If any of the forms matches the Accept header of the request, this predicate will be true. If this predicate returns False, route matching continues.

custom_predicates

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

View-Related Arguments

latex-warning.png

The arguments described below have been deprecated as of Pyramid 1.1. Do not use these for new development; they should only be used to support older code bases which depend upon them. Use a separate call to pyramid.config.Configurator.add_view() to associate a view with a route using the route_name argument.

view

latex-warning.png

Deprecated as of Pyramid 1.1.

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

530

view_context

latex-warning.png

Deprecated as of Pyramid 1.1.

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

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

This attribute can also be spelled as for_ or view_for. view_permission

latex-warning.png

Deprecated as of Pyramid 1.1.

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

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

This argument can also be spelled as permission. view_renderer

latex-warning.png

Deprecated as of Pyramid 1.1.

531