pyramid.request

class Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)[source]

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 http://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

New in version 1.5.

A property which returns the userid of the currently authenticated user or None if there is no authentication policy in effect or there is no currently authenticated user. This differs from unauthenticated_userid, because the effective authentication policy will have ensured that a record associated with the userid exists in persistent storage; if it has not, this value will be None.

unauthenticated_userid

New in version 1.5.

A property which returns a value which represents the claimed (not verified) user id 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

New in version 1.5.

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

invoke_subrequest(request, use_tweens=False)

New in version 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() or set_request_property()) 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

See also Invoking a Subrequest.

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 authentication and authorization policies. Returns pyramid.security.Allowed unconditionally if no authentication 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.

Parameters:
  • permission (unicode, str) -- Does this request have the given permission?
  • context (object) -- A resource object or None
Returns:

pyramid.security.PermitsResult

New in version 1.5.

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 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

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
2
3
4
5
6
7
8
9
import transaction

def commit_callback(request):
    '''commit or abort the transaction associated with request'''
    if request.exception is not None:
        transaction.abort()
    else:
        transaction.commit()
request.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

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 no _query keyword argument is provided, the request query string will be returned in the URL. If it is present, it will be used to compose a query string that will be tacked on to the end of the URL, replacing any request query string. 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 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.

Note

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.

Changed in version 1.5: Allow the _query option to be a string to enable alternative encodings.

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

Note

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.

Changed in version 1.5: The _anchor option will be escaped instead of using its raw string representation.

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.

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.

Note

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.

Note

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

Note

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 :meth:`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.

Warning

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 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 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 :func:pyramid.url.urlencode function. This will produce a query string in the x-www-form-urlencoded encoding. 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.

Note

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.

Changed in version 1.5: Allow the query option to be a string to enable alternative encodings.

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

Note

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.

Changed in version 1.5: The anchor option will be escaped instead of using its raw string representation.

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.

New in version 1.3: app_url

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.

New in version 1.5: route_name, route_kw, and route_remainder_name

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:

remainder_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:

remainder_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.

Note

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.

Note

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

Note

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

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.

Note

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.

json_body

This property will return the JSON-decoded variant of the request body. If the request body is not well-formed JSON, or there is no body associated with this request, this property will raise an exception.

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.

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

@subscriber(NewRequest)
def new_request(event):
    request = event.request
    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.

New in version 1.3.

localizer

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

New in version 1.5.

locale_name

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

New in version 1.5.

GET

Return a MultiDict containing all the variables from the QUERY_STRING.

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 PUT & PATCH requests with an appropriate Content-Type are also supported.

accept

Gets and sets the Accept header (HTTP spec section 14.1).

accept_charset

Gets and sets the Accept-Charset header (HTTP spec section 14.2).

accept_encoding

Gets and sets the Accept-Encoding header (HTTP spec section 14.3).

accept_language

Gets and sets the Accept-Language header (HTTP spec section 14.4).

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.

authorization

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

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__.

body

Return the content of the request body.

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

body_file_raw

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

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.

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.

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.

Warning

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.

content_length

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

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.

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 in-place, either into a BytesIO object 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.

date

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

domain

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

domain = request.host
if ':' in domain:
    domain = domain.split(':', 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.

from_bytes(b)

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

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()

headers

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

host

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

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

host_url

The URL through the host (no path)

http_version

Gets and sets the SERVER_PROTOCOL key in the environment.

if_match

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

if_modified_since

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

if_none_match

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

if_range

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

if_unmodified_since

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

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. This allows FakeCGIBody to work and can be used by servers to support chunked encoding in requests. For background see https://bitbucket.org/ianb/webob/issue/6

is_body_seekable

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

is_response(ob)[source]

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

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.

json

Access the body of the request as JSON

localizer

Convenience property to return a localizer

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.

max_forwards

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

method

Gets and sets the REQUEST_METHOD key in the environment.

params

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

path

The path of the request, without host or query string

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.

path_qs

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

path_url

The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING

pragma

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

query_string

Gets and sets the QUERY_STRING key in the environment.

range

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

referer

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

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

remote_addr

Gets and sets the REMOTE_ADDR key in the environment.

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.

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. Subsequent accesses will return the same Response object.

The request.response API 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()) within a view that uses a renderer. Mutations to this response object will be preserved in the response sent to the client.

scheme

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

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()

server_name

Gets and sets the SERVER_NAME key in the environment.

server_port

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

session

Obtain the session object associated with this request. If a session factory has not been registered during application configuration, a pyramid.exceptions.ConfigurationError will be raised

text

Get/set the text value of the body

upath_info

Gets and sets the PATH_INFO key in the environment.

url

The full request URL, including QUERY_STRING

url_encoding

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

urlargs

Return any positional variables matched in the URL.

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

urlvars

Return any named variables matched in the URL.

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

uscript_name

Gets and sets the SCRIPT_NAME key in the environment.

user_agent

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

Note

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.