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

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

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

Добавлен: 02.01.2026

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

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

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

response

This attribute is actually a “reified” property which returns an instance of the pyramid.response.Response class. The response object returned does not exist until this attribute is accessed. Once it is accessed, subsequent accesses to this request object will return the same Response object.

The request.response API can is used by renderers. A render obtains the response object it will return from a view that uses that renderer by accessing request.response. Therefore, it’s possible to use the request.response API to set up a response object with “the right” attributes (e.g. by calling request.response.set_cookie(...) or request.response.content_type = ’text/plain’, etc) within a view that uses a renderer. For example, within a view that uses a renderer:

response = request.response response.set_cookie(’mycookie’, ’mine, all mine!’)

return {’text’:’Value that will be used by the renderer’}

Mutations to this response object will be preserved in the response sent to the client after rendering. For more information about using request.response in conjunction with a renderer, see Varying Attributes of Rendered Responses.

Non-renderer code can also make use of request.response instead of creating a response “by hand”. For example, in view code:

response = request.response response.body = ’Hello!’ response.content_type = ’text/plain’ return response

Note that the response in this circumstance is not “global”; it still must be returned from the view code if a renderer is not used.

session

If a session factory has been configured, this attribute will represent the current user’s session object. If a session factory has not been configured, requesting the request.session attribute will cause a pyramid.exceptions.ConfigurationError to be raised.

matchdict

If a route has matched during this request, this attribute will be a dictionary containing the values matched by the URL pattern associated with the route. If a route has not matched during this request, the value of this attribute will be None. See The Matchdict.

619

54. PYRAMID.REQUEST

matched_route

If a route has matched during this request, this attribute will be an obect representing the route matched by the URL pattern associated with the route. If a route has not matched during this request, the value of this attribute will be None. See The Matched Route.

add_response_callback(callback)

Add a callback to the set of callbacks to be called by the router at a point after a response object is successfully created. Pyramid does not have a global response object: this functionality allows an application to register an action to be performed against the response once one is created.

A ‘callback’ is a callable which accepts two positional parameters: request and response. For example:

1

2

3

4

def cache_callback(request, response):

’Set the cache_control max_age for the response’ response.cache_control.max_age = 360

request.add_response_callback(cache_callback)

Response callbacks are called in the order they’re added (first-to-most-recently-added). No response callback is called if an exception happens in application code, or if the response object returned by view code is invalid.

All response callbacks are called after the pyramid.events.NewResponse event is sent.

Errors raised by callbacks are not handled specially. They will be propagated to the caller of the Pyramid router application.

See also: Using Response Callbacks.

add_finished_callback(callback)

Add a callback to the set of callbacks to be called unconditionally by the router at the very end of request processing.

callback is a callable which accepts a single positional parameter: request. For example:

1

import transaction

2

 

3

def commit_callback(request):

4

’’’commit or abort the transaction associated with request’’’

5if request.exception is not None:

6transaction.abort()

7else:

8transaction.commit()

9 request.add_finished_callback(commit_callback)

620


Finished callbacks are called in the order they’re added ( firstto most-recently- added). Finished callbacks (unlike response callbacks) are always called, even if an exception happens in application code that prevents a response from being generated.

The set of finished callbacks associated with a request are called very late in the processing of that request; they are essentially the last thing called by the router. They are called after response processing has already occurred in a top-level finally: block within the router request processing code. As a result, mutations performed to the request provided to a finished callback will have no meaningful effect, because response processing will have already occurred, and the request’s scope will expire almost immediately after all finished callbacks have been processed.

Errors raised by finished callbacks are not handled specially. They will be propagated to the caller of the Pyramid router application.

See also: Using Finished Callbacks.

route_url(route_name, *elements, **kw)

Generates a fully qualified URL for a named Pyramid route configuration.

Use the route’s name as the first positional argument. Additional positional arguments (*elements) are appended to the URL as path segments after it is generated.

Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a KeyError exception if the URL cannot be generated for any reason (not enough arguments, for example).

For example, if you’ve defined a route

named “foobar” with the path

{foo}/{bar}/*traverse:

 

 

 

 

 

request.route_url(’foobar’,

 

 

foo=’1’)

=> <KeyError exception>

 

request.route_url(’foobar’,

 

 

foo=’1’,

 

 

bar=’2’)

=> <KeyError exception>

 

request.route_url(’foobar’,

 

 

foo=’1’,

 

 

bar=’2’,

 

 

traverse=(’a’,’b’))

=> http://e.com/1/2/a/b

 

request.route_url(’foobar’,

 

 

foo=’1’,

 

 

bar=’2’,

 

 

traverse=’/a/b’)

=> http://e.com/1/2/a/b

 

 

 

621


54. PYRAMID.REQUEST

Values replacing :segment arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL.

Values replacing *remainder arguments can be passed as strings or tuples of Unicode/string values. If a tuple is passed as a *remainder replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a *remainder replacement value, it is tacked on to the URL after being URL-quoted-except-for-embedded-slashes.

If a keyword argument _query is present, it will be used to compose a query string that will be tacked on to the end of the URL. The value of _query must be a sequence of two-tuples or a data structure with an .items() method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of pyramid.encode.urlencode() function. After the query data is turned into a query string, a leading ? is prepended, and the resulting string is appended to the generated URL.

latex-note.png

Python data structures that are passed as _query which are sequences or dictionaries are turned into a string under the same rules as when run through urllib.urlencode() with the doseq argument equal to True. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value.

If a keyword argument _anchor is present, its string representation will be used as a named anchor in the generated URL (e.g. if _anchor is passed as foo and the route URL is http://example.com/route/url, the resulting generated URL will be http://example.com/route/url#foo).

latex-note.png

If _anchor is passed as a string, it should be UTF-8 encoded. If _anchor is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL.

622

If both _anchor and _query are specified, the anchor element will always follow the query element, e.g. http://example.com?foo=1#bar.

If any of the keyword arguments _scheme, _host, or _port is passed and is non-None, the provided value will replace the named portion in the generated URL. For example, if you pass _host=’foo.com’, and the URL that would have been generated without the host replacement is http://example.com/a, the result will be https://foo.com/a.

Note that if _scheme is passed as https, and _port is not passed, the _port value is assumed to have been passed as 443. Likewise, if _scheme is passed as http and _port is not passed, the _port value is assumed to have been passed as 80. To avoid this behavior, always explicitly pass _port whenever you pass _scheme.

If a keyword _app_url is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an _app_url of http://example.com:8080/foo would cause the URL http://example.com:8080/foo/fleeb/flub to be returned from this function if the expansion of the route pattern associated with the route_name expanded to /fleeb/flub. If _app_url is not specified, the result of request.application_url will be used as the prefix (the default).

If both _app_url and any of _scheme, _host, or _port are passed, _app_url takes precedence and any values passed for _scheme, _host, and _port will be ignored.

This function raises a KeyError if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored.

If the route object which matches the route_name argument has a pregenerator, the *elements and **kw arguments arguments passed to this function might be augmented or changed.

route_path(route_name, *elements, **kw)

Generates a path (aka a ‘relative URL’, a URL minus the host, scheme, and port) for a named Pyramid route configuration.

This function accepts the same argument as pyramid.request.Request.route_url() and performs the same duty. It just omits the host, port, and scheme information in the return value; only the script_name, path, query parameters, and anchor data are present in the returned string.

For example, if you’ve defined a route named ‘foobar’ with the path /{foo}/{bar}, this call to route_path:

623


54. PYRAMID.REQUEST

request.route_path(’foobar’, foo=’1’, bar=’2’)

Will return the string /1/2.

latex-note.png

Calling request.route_path(’route’) is the same as calling request.route_url(’route’, _app_url=request.script_name). pyramid.request.Request.route_path() is, in fact, implemented in terms of pyramid.request.Request.route_url() in just this way. As a result, any

_app_url passed within the **kw values to route_path will be ignored.

current_route_url(*elements, **kw)

Generates a fully qualified URL for a named Pyramid route configuration based on the ‘current route’.

This function supplements pyramid.request.Request.route_url(). It presents an easy way to generate a URL for the ‘current route’ (defined as the route which matched when the request was generated).

The arguments to this method have the same meaning as those with the same names passed to pyramid.request.Request.route_url(). It also understands an extra argument which route_url does not named _route_name.

The route name used to generate a URL is taken from either the _route_name keyword argument or the name of the route which is currently associated with the request if _route_name was not passed. Keys and values from the current request matchdict are combined with the kw arguments to form a set of defaults named newkw. Then request.route_url(route_name, *elements, **newkw) is called, returning a URL.

Examples follow.

 

 

 

 

 

 

 

If the

‘current route’

has

the route

pattern

/foo/{page} and

the

current

url

path is

/foo/1 ,

the

matchdict

will be

{’page’:’1’}.

The

result

of

request.current_route_url() in this situation will be /foo/1.

624


If

the

‘current route’

has

the route pattern

/foo/{page}

and the current

url

path

is /foo/1,

the

matchdict will be

{’page’:’1’}.

The result of

request.current_route_url(page=’2’) in this situation will be /foo/2.

Usage of the _route_name keyword argument: if our routing table defines routes

/foo/{action} named ‘foo’ and /foo/{action}/{page} named fooaction, and the current url pattern is /foo/view (which has matched the /foo/{action} route), we may want to use the matchdict args to generate a URL to the fooaction route. In this scenario, request.current_route_url(_route_name=’fooaction’, page=’5’) Will return string like: /foo/view/5.

current_route_path(*elements, **kw)

Generates a path (aka a ‘relative URL’, a URL minus the host, scheme, and port) for the Pyramid route configuration matched by the current request.

This function accepts the same argument as pyramid.request.Request.current_route_url( and performs the same duty. It just omits the host, port, and scheme information in the

return value; only the script_name, path, query parameters, and anchor data are present in the returned string.

For example, if the route matched by the current request has the pattern /{foo}/{bar}, this call to current_route_path:

request.current_route_path(foo=’1’, bar=’2’)

Will return the string /1/2.

 

 

 

 

 

 

latex-note.png

 

 

 

 

Calling

request.current_route_path(’route’)

 

 

is the same as calling

request.current_route_url(’route’,

 

 

_app_url=request.script_name). pyramid.request.Request.current

_route_pa

 

is, in fact, implemented in terms of :meth:‘pyramid.request.Request.current_route_url

 

 

in just this way. As a result, any _app_url passed within the **kw values to

 

 

current_route_path will be ignored.

 

 

 

 

 

 

625