pyramid.request

class Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)[ソース]

A subclass of the WebOb Request class. An instance of this class is created by the router and is provided to a view callable (and to other subsystems) as the request argument.

The documentation below (save for the add_response_callback and add_finished_callback methods, which are defined in this subclass itself, and the attributes context, registry, root, subpath, traversed, view_name, virtual_root , and virtual_root_path, each of which is added to the request by the router at request ingress time) are autogenerated from the WebOb source code used when this documentation was generated.

Due to technical constraints, we can't yet display the WebOb version number from which this documentation is autogenerated, but it will be the 'prevailing WebOb version' at the time of the release of this Pyramid version. See https://webob.org/ for further information.

context

The context will be available as the context attribute of the request object. It will be the context object implied by the current request. See Traversal for information about context objects.

registry

The application registry will be available as the registry attribute of the request object. See Using the Zope Component Architecture in Pyramid for more information about the application registry.

root

The root object will be available as the root attribute of the request object. It will be the resource object at which traversal started (the root). See Traversal for information about root objects.

subpath

The traversal subpath will be available as the subpath attribute of the request object. It will be a sequence containing zero or more elements (which will be Unicode objects). See Traversal for information about the subpath.

traversed

The "traversal path" will be available as the traversed attribute of the request object. It will be a sequence representing the ordered set of names that were used to traverse to the context, not including the view name or subpath. If there is a virtual root associated with the request, the virtual root path is included within the traversal path. See Traversal for more information.

view_name

The view name will be available as the view_name attribute of the request object. It will be a single string (possibly the empty string if we're rendering a default view). See Traversal for information about view names.

virtual_root

The virtual root will be available as the virtual_root attribute of the request object. It will be the virtual root object implied by the current request. See Virtual Hosting for more information about virtual roots.

virtual_root_path

The virtual root path will be available as the virtual_root_path attribute of the request object. It will be a sequence representing the ordered set of names that were used to traverse to the virtual root object. See Virtual Hosting for more information about virtual roots.

exception

If an exception was raised by a root factory or a view callable, or at various other points where Pyramid executes user-defined code during the processing of a request, the exception object which was caught will be available as the exception attribute of the request within a exception view, a response callback or a finished callback. If no exception occurred, the value of request.exception will be None within response and finished callbacks.

exc_info

If an exception was raised by a root factory or a view callable, or at various other points where Pyramid executes user-defined code during the processing of a request, result of sys.exc_info() will be available as the exc_info attribute of the request within a exception view, a response callback or a finished callback. If no exception occurred, the value of request.exc_info will be None within response and finished callbacks.

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.

matched_route

If a route has matched during this request, this attribute will be an object 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.

authenticated_userid

A property which returns the userid of the currently authenticated user or None if there is no security policy in effect or there is no currently authenticated user.

unauthenticated_userid

バージョン 2.0 で非推奨: unauthenticated_userid has been deprecated in version 2.0. Use authenticated_userid or identity instead. See Upgrading Authentication/Authorization for more information.

A property which returns a value which represents the claimed (not verified) userid of the credentials present in the request. None if there is no authentication policy in effect or there is no user data associated with the current request. This differs from authenticated_userid, because the effective authentication policy will not ensure that a record associated with the userid exists in persistent storage. Even if the userid does not exist in persistent storage, this value will be the value of the userid claimed by the request data.

effective_principals

バージョン 2.0 で非推奨: The new security policy has removed the concept of principals. See Upgrading Authentication/Authorization for more information.

A property which returns the list of 'effective' principal identifiers for this request. This list typically includes the userid of the currently authenticated user if a user is currently authenticated, but this depends on the authentication policy in effect. If no authentication policy is in effect, this will return a sequence containing only the pyramid.authorization.Everyone principal.

invoke_subrequest(request, use_tweens=False)

バージョン 1.4a1 で追加.

Obtain a response object from the Pyramid application based on information in the request object provided. The request object must be an object that implements the Pyramid request interface (such as a pyramid.request.Request instance). If use_tweens is True, the request will be sent to the tween in the tween stack closest to the request ingress. If use_tweens is False, the request will be sent to the main router handler, and no tweens will be invoked.

This function also:

  • manages the threadlocal stack (so that get_current_request() and get_current_registry() work during a request)

  • Adds a registry attribute (the current Pyramid registry) and a invoke_subrequest attribute (a callable) to the request object it's handed.

  • sets request extensions (such as those added via add_request_method()) on the request it's passed.

  • causes a NewRequest event to be sent at the beginning of request processing.

  • causes a ContextFound event to be sent when a context resource is found.

  • Ensures that the user implied by the request passed has the necessary authorization to invoke view callable before calling it.

  • Calls any response callback functions defined within the request's lifetime if a response is obtained from the Pyramid application.

  • causes a NewResponse event to be sent if a response is obtained.

  • Calls any finished callback functions defined within the request's lifetime.

invoke_subrequest isn't actually a method of the Request object; it's a callable added when the Pyramid router is invoked, or when a subrequest is invoked. This means that it's not available for use on a request provided by e.g. the pshell environment.

参考

See also Invoking a Subrequest.

invoke_exception_view(exc_info=None, request=None, secure=True, reraise=False)

Executes an exception view related to the request it's called upon. The arguments it takes are these:

exc_info

If provided, should be a 3-tuple in the form provided by sys.exc_info(). If not provided, sys.exc_info() will be called to obtain the current interpreter exception information. Default: None.

request

If the request to be used is not the same one as the instance that this method is called upon, it may be passed here. Default: None.

secure

If the exception view should not be rendered if the current user does not have the appropriate permission, this should be True. Default: True.

reraise

A boolean indicating whether the original error should be reraised if a response object could not be created. If False then an pyramid.httpexceptions.HTTPNotFound` exception will be raised. Default: False.

If a response is generated then request.exception and request.exc_info will be left at the values used to render the response. Otherwise the previous values for request.exception and request.exc_info will be restored.

バージョン 1.7 で追加.

バージョン 1.9 で変更: The request.exception and request.exc_info properties will reflect the exception used to render the response where previously they were reset to the values prior to invoking the method.

Also added the reraise argument.

has_permission(permission, context=None)

Given a permission and an optional context, returns an instance of pyramid.security.Allowed if the permission is granted to this request with the provided context, or the context already associated with the request. Otherwise, returns an instance of pyramid.security.Denied. This method delegates to the current security policy. Returns pyramid.security.Allowed unconditionally if no security policy has been registered for this request. If context is not supplied or is supplied as None, the context used is the request.context attribute.

パラメータ
  • permission (str) -- Does this request have the given permission?

  • context (object) -- A resource object or None

戻り値

Either pyramid.security.Allowed or pyramid.security.Denied.

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:

1def cache_callback(request, response):
2    'Set the cache_control max_age for the response'
3    response.cache_control.max_age = 360
4request.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 tweens and before 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:

1import transaction
2
3def commit_callback(request):
4    '''commit or abort the transaction associated with request'''
5    if request.exception is not None:
6        transaction.abort()
7    else:
8        transaction.commit()
9request.add_finished_callback(commit_callback)

Finished callbacks are called in the order they're added ( first- to 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

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 _query is provided, it will be used to compose a query string that will be tacked on to the end of the URL. The value of _query may 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 the pyramid.url.urlencode() function. This will produce a query string in the x-www-form-urlencoded format. A non-x-www-form-urlencoded query string may be used by passing a string value as _query in which case it will be URL-quoted (e.g. query="foo bar" will become "foo%20bar"). However, the result will not need to be in k=v form as required by x-www-form-urlencoded. After the query data is turned into a query string, a leading ? is prepended, and the resulting string is appended to the generated URL.

注釈

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 quoted per RFC 3986#section-3.5 and 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).

注釈

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.

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 http://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 passed to this function might be augmented or changed.

バージョン 1.5 で変更: Allow the _query option to be a string to enable alternative encodings.

The _anchor option will be escaped instead of using its raw string representation.

バージョン 1.9 で変更: If _query or _anchor are falsey (such as None or an empty string) they will not be included in the generated url.

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:

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

Will return the string /1/2.

注釈

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.

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.

注釈

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_path() is, in fact, implemented in terms of 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.

static_url(path, **kw)

Generates a fully qualified URL for a static asset. The asset must live within a location defined via the pyramid.config.Configurator.add_static_view() configuration declaration (see Serving Static Assets).

Example:

request.static_url('mypackage:static/foo.css') =>

                        http://example.com/static/foo.css

The path argument points at a file or directory on disk which a URL should be generated for. The path may be either a relative path (e.g. static/foo.css) or an absolute path (e.g. /abspath/to/static/foo.css) or a asset specification (e.g. mypackage:static/foo.css).

The purpose of the **kw argument is the same as the purpose of the pyramid.request.Request.route_url() **kw argument. See the documentation for that function to understand the arguments which you can provide to it. However, typically, you don't need to pass anything as *kw when generating a static asset URL.

This function raises a ValueError if a static view definition cannot be found which matches the path specification.

static_path(path, **kw)

Generates a path (aka a 'relative URL', a URL minus the host, scheme, and port) for a static resource.

This function accepts the same argument as pyramid.request.Request.static_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.

Example:

request.static_path('mypackage:static/foo.css') =>

                        /static/foo.css

注釈

Calling request.static_path(apath) is the same as calling request.static_url(apath, _app_url=request.script_name). pyramid.request.Request.static_path() is, in fact, implemented in terms of pyramid.request.Request.static_url() in just this way. As a result, any _app_url passed within the **kw values to static_path will be ignored.

resource_url(resource, *elements, **kw)

Generate a string representing the absolute URL of the resource object based on the wsgi.url_scheme, HTTP_HOST or SERVER_NAME in the request, plus any SCRIPT_NAME. The overall result of this method is always a UTF-8 encoded string.

Examples:

request.resource_url(resource) =>

                           http://example.com/

request.resource_url(resource, 'a.html') =>

                           http://example.com/a.html

request.resource_url(resource, 'a.html', query={'q':'1'}) =>

                           http://example.com/a.html?q=1

request.resource_url(resource, 'a.html', anchor='abc') =>

                           http://example.com/a.html#abc

request.resource_url(resource, app_url='') =>

                           /

Any positional arguments passed in as elements must be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted.

警告

if no elements arguments are specified, the resource URL will end with a trailing slash. If any elements are used, the generated URL will not end in a trailing slash.

If query is provided, it will be used to compose a query string that will be tacked on to the end of the URL. The value of query may 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 the pyramid.url.urlencode() function. This will produce a query string in the x-www-form-urlencoded format. A non-x-www-form-urlencoded query string may be used by passing a string value as query in which case it will be URL-quoted (e.g. query="foo bar" will become "foo%20bar"). However, the result will not need to be in k=v form as required by x-www-form-urlencoded. After the query data is turned into a query string, a leading ? is prepended, and the resulting string is appended to the generated URL.

注釈

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 resource URL is http://example.com/resource/url, the resulting generated URL will be http://example.com/resource/url#foo).

注釈

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.

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 http://foo.com/a.

If scheme is passed as https, and an explicit 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 argument app_url is passed and is not None, it should be a string that will be used as the port/hostname/initial path portion of the generated URL instead of the default request application URL. For example, if app_url='http://foo', then the resulting url of a resource that has a path of /baz/bar will be http://foo/baz/bar. If you want to generate completely relative URLs with no leading scheme, host, port, or initial path, you can pass app_url=''. Passing app_url='' when the resource path is /baz/bar will return /baz/bar.

If app_url is passed and any of scheme, port, or host are also passed, app_url will take precedence and the values passed for scheme, host, and/or port will be ignored.

If the resource passed in has a __resource_url__ method, it will be used to generate the URL (scheme, host, port, path) for the base resource which is operated upon by this function.

If route_name is passed, this function will delegate its URL production to the route_url function. Calling resource_url(someresource, 'element1', 'element2', query={'a':1}, route_name='blogentry') is roughly equivalent to doing:

traversal_path = request.resource_path(someobject)
url = request.route_url(
          'blogentry',
          'element1',
          'element2',
          _query={'a':'1'},
          traverse=traversal_path,
          )

It is only sensible to pass route_name if the route being named has a *remainder stararg value such as *traverse. The remainder value will be ignored in the output otherwise.

By default, the resource path value will be passed as the name traverse when route_url is called. You can influence this by passing a different route_remainder_name value if the route has a different *stararg value at its end. For example if the route pattern you want to replace has a *subpath stararg ala /foo*subpath:

request.resource_url(
               resource,
               route_name='myroute',
               route_remainder_name='subpath'
               )

If route_name is passed, it is also permissible to pass route_kw, which will passed as additional keyword arguments to route_url. Saying resource_url(someresource, 'element1', 'element2', route_name='blogentry', route_kw={'id':'4'}, _query={'a':'1'}) is roughly equivalent to:

traversal_path = request.resource_path_tuple(someobject)
kw = {'id':'4', '_query':{'a':'1'}, 'traverse':traversal_path}
url = request.route_url(
          'blogentry',
          'element1',
          'element2',
          **kw,
          )

If route_kw or route_remainder_name is passed, but route_name is not passed, both route_kw and route_remainder_name will be ignored. If route_name is passed, the __resource_url__ method of the resource passed is ignored unconditionally. This feature is incompatible with resources which generate their own URLs.

注釈

If the resource used is the result of a traversal, it must be location-aware. The resource can also be the context of a URL dispatch; contexts found this way do not need to be location-aware.

注釈

If a 'virtual root path' is present in the request environment (the value of the WSGI environ key HTTP_X_VHM_ROOT), and the resource was obtained via traversal, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL).

注釈

For backwards compatibility purposes, this method is also aliased as the model_url method of request.

バージョン 1.3 で変更: Added the app_url keyword argument.

バージョン 1.5 で変更: Allow the query option to be a string to enable alternative encodings.

The anchor option will be escaped instead of using its raw string representation.

Added the route_name, route_kw, and route_remainder_name keyword arguments.

バージョン 1.9 で変更: If query or anchor are falsey (such as None or an empty string) they will not be included in the generated url.

resource_path(resource, *elements, **kw)

Generates a path (aka a 'relative URL', a URL minus the host, scheme, and port) for a resource.

This function accepts the same argument as pyramid.request.Request.resource_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.

注釈

Calling request.resource_path(resource) is the same as calling request.resource_path(resource, app_url=request.script_name). pyramid.request.Request.resource_path() is, in fact, implemented in terms of pyramid.request.Request.resource_url() in just this way. As a result, any app_url passed within the **kw values to route_path will be ignored. scheme, host, and port are also ignored.

set_property(callable, name=None, reify=False)

Add a callable or a property descriptor to the request instance.

Properties, unlike attributes, are lazily evaluated by executing an underlying callable when accessed. They can be useful for adding features to an object without any cost if those features go unused.

A property may also be reified via the pyramid.decorator.reify decorator by setting reify=True, allowing the result of the evaluation to be cached. Thus the value of the property is only computed once for the lifetime of the object.

callable can either be a callable that accepts the request as its single positional parameter, or it can be a property descriptor.

If the callable is a property descriptor a ValueError will be raised if name is None or reify is True.

If name is None, the name of the property will be computed from the name of the callable.

 1def _connect(request):
 2    conn = request.registry.dbsession()
 3    def cleanup(request):
 4        # since version 1.5, request.exception is no
 5        # longer eagerly cleared
 6        if request.exception is not None:
 7            conn.rollback()
 8        else:
 9            conn.commit()
10        conn.close()
11    request.add_finished_callback(cleanup)
12    return conn
13
14@subscriber(NewRequest)
15def new_request(event):
16    request = event.request
17    request.set_property(_connect, 'db', reify=True)

The subscriber doesn't actually connect to the database, it just provides the API which, when accessed via request.db, will create the connection. Thanks to reify, only one connection is made per-request even if request.db is accessed many times.

This pattern provides a way to augment the request object without having to subclass it, which can be useful for extension authors.

バージョン 1.3 で追加.

localizer

A localizer which will use the current locale name to translate values.

バージョン 1.5 で追加.

locale_name

The locale name of the current request as computed by the locale negotiator.

バージョン 1.5 で追加.

property GET

Return a MultiDict containing all the variables from the QUERY_STRING.

property POST

Return a MultiDict containing all the variables from a form request. Returns an empty dict-like object for non-form requests.

Form requests are typically POST requests, however any other requests with an appropriate Content-Type are also supported.

ResponseClass

:py:class:`pyramid.response.Response`の別名です。

property accept

Property representing the Accept header.

(RFC 7231, section 5.3.2)

The header value in the request environ is parsed and a new object representing the header is created every time we get the value of the property. (set and del change the header value in the request environ, and do not involve parsing.)

property accept_charset

Property representing the Accept-Charset header.

(RFC 7231, section 5.3.3)

The header value in the request environ is parsed and a new object representing the header is created every time we get the value of the property. (set and del change the header value in the request environ, and do not involve parsing.)

property accept_encoding

Property representing the Accept-Encoding header.

(RFC 7231, section 5.3.4)

The header value in the request environ is parsed and a new object representing the header is created every time we get the value of the property. (set and del change the header value in the request environ, and do not involve parsing.)

property accept_language

Property representing the Accept-Language header.

(RFC 7231, section 5.3.5)

The header value in the request environ is parsed and a new object representing the header is created every time we get the value of the property. (set and del change the header value in the request environ, and do not involve parsing.)

property application_url

The URL including SCRIPT_NAME (no PATH_INFO or query string)

as_bytes(skip_body=False)

Return HTTP bytes representing this request. If skip_body is True, exclude the body. If skip_body is an integer larger than one, skip body only if its length is bigger than that number.

property authorization

Gets and sets the Authorization header (HTTP spec section 14.8). Converts it using parse_auth and serialize_auth.

classmethod blank(path, environ=None, base_url=None, headers=None, POST=None, **kw)

Create a blank request environ (and Request wrapper) with the given path (path should be urlencoded), and any keys from environ.

The path will become path_info, with any query string split off and used.

All necessary keys will be added to the environ, but the values you pass in will take precedence. If you pass in base_url then wsgi.url_scheme, HTTP_HOST, and SCRIPT_NAME will be filled in from that value.

Any extra keyword will be passed to __init__.

property body

Return the content of the request body.

property body_file

Input stream of the request (wsgi.input). Setting this property resets the content_length and seekable flag (unlike setting req.body_file_raw).

property body_file_raw

Gets and sets the wsgi.input key in the environment.

property body_file_seekable

Get the body of the request (wsgi.input) as a seekable file-like object. Middleware and routing applications should use this attribute over .body_file.

If you access this value, CONTENT_LENGTH will also be updated.

property cache_control

Get/set/modify the Cache-Control header (HTTP spec section 14.9)

call_application(application, catch_exc_info=False)

Call the given WSGI application, returning (status_string, headerlist, app_iter)

Be sure to call app_iter.close() if it's there.

If catch_exc_info is true, then returns (status_string, headerlist, app_iter, exc_info), where the fourth item may be None, but won't be if there was an exception. If you don't do this and there was an exception, the exception will be raised directly.

property client_addr

The effective client IP address as a string. If the HTTP_X_FORWARDED_FOR header exists in the WSGI environ, this attribute returns the client IP address present in that header (e.g. if the header value is 192.168.1.1, 192.168.1.2, the value will be 192.168.1.1). If no HTTP_X_FORWARDED_FOR header is present in the environ at all, this attribute will return the value of the REMOTE_ADDR header. If the REMOTE_ADDR header is unset, this attribute will return the value None.

警告

It is possible for user agents to put someone else's IP or just any string in HTTP_X_FORWARDED_FOR as it is a normal HTTP header. Forward proxies can also provide incorrect values (private IP addresses etc). You cannot "blindly" trust the result of this method to provide you with valid data unless you're certain that HTTP_X_FORWARDED_FOR has the correct values. The WSGI server must be behind a trusted proxy for this to be true.

property content_length

Gets and sets the Content-Length header (HTTP spec section 14.13). Converts it using int.

property content_type

Return the content type, but leaving off any parameters (like charset, but also things like the type in application/atom+xml; type=entry)

If you set this property, you can include parameters, or if you don't include any parameters in the value then existing parameters will be preserved.

property cookies

Return a dictionary of cookies as found in the request.

copy()

Copy the request and environment object.

This only does a shallow copy, except of wsgi.input

copy_body()

Copies the body, in cases where it might be shared with another request object and that is not desired.

This copies the body either into a BytesIO object (through setting req.body) or a temporary file.

copy_get()

Copies the request and environment object, but turning this request into a GET along the way. If this was a POST request (or any other verb) then it becomes GET, and the request body is thrown away.

property date

Gets and sets the Date header (HTTP spec section 14.8). Converts it using HTTP date.

property domain

Returns the domain portion of the host value. Equivalent to:

domain = request.host
if ':' in domain and domain[-1] != ']': # Check for ] because of IPv6
    domain = domain.rsplit(':', 1)[0]

This will be equivalent to the domain portion of the HTTP_HOST value in the environment if it exists, or the SERVER_NAME value in the environment if it doesn't. For example, if the environment contains an HTTP_HOST value of foo.example.com:8000, request.domain will return foo.example.com.

Note that this value cannot be set on the request. To set the host value use webob.request.Request.host() instead.

classmethod from_bytes(b)

Create a request from HTTP bytes data. If the bytes contain extra data after the request, raise a ValueError.

classmethod from_file(fp)

Read a request from a file-like object (it must implement .read(size) and .readline()).

It will read up to the end of the request, not the end of the file (unless the request is a POST or PUT and has no Content-Length, in that case, the entire file is read).

This reads the request as represented by str(req); it may not read every valid HTTP request properly.

get_response(application=None, catch_exc_info=False)

Like .call_application(application), except returns a response object with .status, .headers, and .body attributes.

This will use self.ResponseClass to figure out the class of the response object to return.

If application is not given, this will send the request to self.make_default_send_app()

property headers

All the request headers as a case-insensitive dictionary-like object.

property host

Host name provided in HTTP_HOST, with fall-back to SERVER_NAME

property host_port

The effective server port number as a string. If the HTTP_HOST header exists in the WSGI environ, this attribute returns the port number present in that header. If the HTTP_HOST header exists but contains no explicit port number: if the WSGI url scheme is "https" , this attribute returns "443", if the WSGI url scheme is "http", this attribute returns "80" . If no HTTP_HOST header is present in the environ at all, this attribute will return the value of the SERVER_PORT header (which is guaranteed to be present).

property host_url

The URL through the host (no path)

property http_version

Gets and sets the SERVER_PROTOCOL key in the environment.

property identity

Return an opaque object identifying the current user or None if no user is authenticated or there is no security policy in effect.

property if_match

Gets and sets the If-Match header (HTTP spec section 14.24). Converts it as a Etag.

property if_modified_since

Gets and sets the If-Modified-Since header (HTTP spec section 14.25). Converts it using HTTP date.

property if_none_match

Gets and sets the If-None-Match header (HTTP spec section 14.26). Converts it as a Etag.

property if_range

Gets and sets the If-Range header (HTTP spec section 14.27). Converts it using IfRange object.

property if_unmodified_since

Gets and sets the If-Unmodified-Since header (HTTP spec section 14.28). Converts it using HTTP date.

property is_authenticated

Return True if a user is authenticated for this request.

property is_body_readable

webob.is_body_readable is a flag that tells us that we can read the input stream even though CONTENT_LENGTH is missing.

property is_body_seekable

Gets and sets the webob.is_body_seekable key in the environment.

is_response(ob)[ソース]

Return True if the object passed as ob is a valid response object, False otherwise.

property is_xhr

Is X-Requested-With header present and equal to XMLHttpRequest?

Note: this isn't set by every XMLHttpRequest request, it is only set if you are using a Javascript library that sets it (or you set the header yourself manually). Currently Prototype and jQuery are known to set this header.

property json

Access the body of the request as JSON

property json_body

Access the body of the request as JSON

make_body_seekable()

This forces environ['wsgi.input'] to be seekable. That means that, the content is copied into a BytesIO or temporary file and flagged as seekable, so that it will not be unnecessarily copied again.

After calling this method the .body_file is always seeked to the start of file and .content_length is not None.

The choice to copy to BytesIO is made from self.request_body_tempfile_limit

make_tempfile()

Create a tempfile to store big request body. This API is not stable yet. A 'size' argument might be added.

property max_forwards

Gets and sets the Max-Forwards header (HTTP spec section 14.31). Converts it using int.

property method

Gets and sets the REQUEST_METHOD key in the environment.

property params

A dictionary-like object containing both the parameters from the query string and request body.

property path

The path of the request, without host or query string

property path_info

Gets and sets the PATH_INFO key in the environment.

path_info_peek()

Returns the next segment on PATH_INFO, or None if there is no next segment. Doesn't modify the environment.

path_info_pop(pattern=None)

'Pops' off the next segment of PATH_INFO, pushing it onto SCRIPT_NAME, and returning the popped segment. Returns None if there is nothing left on PATH_INFO.

Does not return '' when there's an empty segment (like /path//path); these segments are just ignored.

Optional pattern argument is a regexp to match the return value before returning. If there is no match, no changes are made to the request and None is returned.

property path_qs

The path of the request, without host but with query string

property path_url

The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING

property pragma

Gets and sets the Pragma header (HTTP spec section 14.32).

property query_string

Gets and sets the QUERY_STRING key in the environment.

property range

Gets and sets the Range header (HTTP spec section 14.35). Converts it using Range object.

property referer

Gets and sets the Referer header (HTTP spec section 14.36).

property referrer

Gets and sets the Referer header (HTTP spec section 14.36).

relative_url(other_url, to_application=False)

Resolve other_url relative to the request URL.

If to_application is True, then resolve it relative to the URL with only SCRIPT_NAME

property remote_addr

Gets and sets the REMOTE_ADDR key in the environment.

property remote_host

Gets and sets the REMOTE_HOST key in the environment.

property remote_user

Gets and sets the REMOTE_USER key in the environment.

remove_conditional_headers(remove_encoding=True, remove_range=True, remove_match=True, remove_modified=True)

Remove headers that make the request conditional.

These headers can cause the response to be 304 Not Modified, which in some cases you may not want to be possible.

This does not remove headers like If-Match, which are used for conflict detection.

request_iface = <InterfaceClass pyramid.interfaces.IRequest>
property scheme

Gets and sets the wsgi.url_scheme key in the environment.

property script_name

Gets and sets the SCRIPT_NAME key in the environment.

send(application=None, catch_exc_info=False)

Like .call_application(application), except returns a response object with .status, .headers, and .body attributes.

This will use self.ResponseClass to figure out the class of the response object to return.

If application is not given, this will send the request to self.make_default_send_app()

property server_name

Gets and sets the SERVER_NAME key in the environment.

property server_port

Gets and sets the SERVER_PORT key in the environment. Converts it using int.

property text

Get/set the text value of the body

property upath_info

Gets and sets the PATH_INFO key in the environment.

property url

The full request URL, including QUERY_STRING

property url_encoding

Gets and sets the webob.url_encoding key in the environment.

property urlargs

Return any positional variables matched in the URL.

Takes values from environ['wsgiorg.routing_args']. Systems like routes set this value.

property urlvars

Return any named variables matched in the URL.

Takes values from environ['wsgiorg.routing_args']. Systems like routes set this value.

property uscript_name

Gets and sets the SCRIPT_NAME key in the environment.

property user_agent

Gets and sets the User-Agent header (HTTP spec section 14.43).

注釈

For information about the API of a multidict structure (such as that used as request.GET, request.POST, and request.params), see pyramid.interfaces.IMultiDict.

apply_request_extensions(request)[ソース]

Apply request extensions (methods and properties) to an instance of pyramid.interfaces.IRequest. This method is dependent on the request containing a properly initialized registry.

After invoking this method, the request should have the methods and properties that were defined using pyramid.config.Configurator.add_request_method().

class RequestLocalCache(creator=None)[ソース]

A store that caches values during for the lifecycle of a request.

Wrapping Functions

Instantiate and use it to decorate functions that accept a request parameter. The result is cached and returned in subsequent invocations of the function.

@RequestLocalCache()
def get_user(request):
    result = ...  # do some expensive computations
    return result

value = get_user(request)

# manipulate the cache directly
get_user.cache.clear(request)

The cache instance is attached to the resulting function as the cache attribute such that the function may be used to manipulate the cache.

Wrapping Methods

A method can be used as the creator function but it needs to be bound to an instance such that it only accepts one argument - the request. An easy way to do this is to bind the creator in the constructor and then use get_or_create():

class SecurityPolicy:
    def __init__(self):
        self.identity_cache = RequestLocalCache(self.load_identity)

    def load_identity(self, request):
        result = ...  # do some expensive computations
        return result

    def identity(self, request):
        return self.identity_cache.get_or_create(request)

The cache maintains a weakref to each request and will release the cached values when the request is garbage-collected. However, in most scenarios, it will release resources earlier via pyramid.request.Request.add_finished_callback().

バージョン 2.0 で追加.

clear(request)[ソース]

Delete the value from the cache.

The cached value is returned or NO_VALUE.

get(request, default=NO_VALUE)[ソース]

Return the value from the cache.

The cached value is returned or default.

get_or_create(request, creator=None)[ソース]

Return the value from the cache. Compute if necessary.

If no value is cached then execute the creator, cache the result, and return it.

The creator may be passed in as an argument or bound to the cache by decorating a function or supplied as a constructor argument.

set(request, value)[ソース]

Update the cache with a new value.