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
andadd_finished_callback
methods, which are defined in this subclass itself, and the attributescontext
,registry
,root
,subpath
,traversed
,view_name
,virtual_root
, andvirtual_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 ofrequest.exception
will beNone
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 theexc_info
attribute of the request within a exception view, a response callback or a finished callback. If no exception occurred, the value ofrequest.exc_info
will beNone
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 sameResponse
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 accessingrequest.response
. Therefore, it's possible to use therequest.response
API to set up a response object with "the right" attributes (e.g. by callingrequest.response.set_cookie(...)
orrequest.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 apyramid.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 fromunauthenticated_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 beNone
.
- unauthenticated_userid¶
New in version 1.5.
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 fromauthenticated_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 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.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. Therequest
object must be an object that implements the Pyramid request interface (such as apyramid.request.Request
instance). Ifuse_tweens
isTrue
, the request will be sent to the tween in the tween stack closest to the request ingress. Ifuse_tweens
isFalse
, 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()
andget_current_registry()
work during a request)Adds a
registry
attribute (the current Pyramid registry) and ainvoke_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. thepshell
environment.See also
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 anpyramid.httpexceptions.HTTPNotFound`
exception will be raised. Default:False
.If a response is generated then
request.exception
andrequest.exc_info
will be left at the values used to render the response. Otherwise the previous values forrequest.exception
andrequest.exc_info
will be restored.New in version 1.7.
Changed in version 1.9: The
request.exception
andrequest.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 ofpyramid.security.Denied
. This method delegates to the current authentication and authorization policies. Returnspyramid.security.Allowed
unconditionally if no authentication policy has been registered for this request. Ifcontext
is not supplied or is supplied asNone
, the context used is therequest.context
attribute.- Parameters:
- Returns:
Either
pyramid.security.Allowed
orpyramid.security.Denied
.
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
andresponse
. 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
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 therequest
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
_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 thepyramid.url.urlencode()
function. This will produce a query string in thex-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 ink=v
form as required byx-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 throughurllib.urlencode()
with thedoseq
argument equal toTrue
. 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 asfoo
and the route URL ishttp://example.com/route/url
, the resulting generated URL will behttp://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.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 ishttp://example.com/a
, the result will behttp://foo.com/a
.Note that if
_scheme
is passed ashttps
, and_port
is not passed, the_port
value is assumed to have been passed as443
. Likewise, if_scheme
is passed ashttp
and_port
is not passed, the_port
value is assumed to have been passed as80
. 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
ofhttp://example.com:8080/foo
would cause the URLhttp://example.com:8080/foo/fleeb/flub
to be returned from this function if the expansion of the route pattern associated with theroute_name
expanded to/fleeb/flub
. If_app_url
is not specified, the result ofrequest.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.Changed in version 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.Changed in version 1.9: If
_query
or_anchor
are falsey (such asNone
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 toroute_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 callingrequest.route_url('route', _app_url=request.script_name)
.pyramid.request.Request.route_path()
is, in fact, implemented in terms ofpyramid.request.Request.route_url()
in just this way. As a result, any_app_url
passed within the**kw
values toroute_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 whichroute_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 thekw
arguments to form a set of defaults namednewkw
. Thenrequest.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 ofrequest.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 ofrequest.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}
namedfooaction
, 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 thefooaction
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 tocurrent_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 callingrequest.current_route_url('route', _app_url=request.script_name)
.pyramid.request.Request.current_route_path()
is, in fact, implemented in terms ofpyramid.request.Request.current_route_url()
in just this way. As a result, any_app_url
passed within the**kw
values tocurrent_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. Thepath
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 thepyramid.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 callingrequest.static_url(apath, _app_url=request.script_name)
.pyramid.request.Request.static_path()
is, in fact, implemented in terms ofpyramid.request.Request.static_url()
in just this way. As a result, any_app_url
passed within the**kw
values tostatic_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
orSERVER_NAME
in the request, plus anySCRIPT_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 anyelements
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 ofquery
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 thepyramid.url.urlencode()
function. This will produce a query string in thex-www-form-urlencoded
format. A non-x-www-form-urlencoded
query string may be used by passing a string value asquery
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 ink=v
form as required byx-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 throughurllib.urlencode()
with thedoseq
argument equal toTrue
. 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. ifanchor
is passed asfoo
and the resource URL ishttp://example.com/resource/url
, the resulting generated URL will behttp://example.com/resource/url#foo
).Note
If
anchor
is passed as a string, it should be UTF-8 encoded. Ifanchor
is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL.If both
anchor
andquery
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
, orport
is passed and is non-None
, the provided value will replace the named portion in the generated URL. For example, if you passhost='foo.com'
, and the URL that would have been generated without the host replacement ishttp://example.com/a
, the result will behttp://foo.com/a
.If
scheme
is passed ashttps
, and an explicitport
is not passed, theport
value is assumed to have been passed as443
. Likewise, ifscheme
is passed ashttp
andport
is not passed, theport
value is assumed to have been passed as80
. To avoid this behavior, always explicitly passport
whenever you passscheme
.If a keyword argument
app_url
is passed and is notNone
, 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, ifapp_url='http://foo'
, then the resulting url of a resource that has a path of/baz/bar
will behttp://foo/baz/bar
. If you want to generate completely relative URLs with no leading scheme, host, port, or initial path, you can passapp_url=''
. Passingapp_url=''
when the resource path is/baz/bar
will return/baz/bar
.If
app_url
is passed and any ofscheme
,port
, orhost
are also passed,app_url
will take precedence and the values passed forscheme
,host
, and/orport
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.See also
See also Overriding Resource URL Generation.
If
route_name
is passed, this function will delegate its URL production to theroute_url
function. Callingresource_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
whenroute_url
is called. You can influence this by passing a differentroute_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 passroute_kw
, which will passed as additional keyword arguments toroute_url
. Sayingresource_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
orroute_remainder_name
is passed, butroute_name
is not passed, bothroute_kw
androute_remainder_name
will be ignored. Ifroute_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.Changed in version 1.3: Added the
app_url
keyword argument.Changed in version 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
, androute_remainder_name
keyword arguments.Changed in version 1.9: If
query
oranchor
are falsey (such asNone
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.Note
Calling
request.resource_path(resource)
is the same as callingrequest.resource_path(resource, app_url=request.script_name)
.pyramid.request.Request.resource_path()
is, in fact, implemented in terms ofpyramid.request.Request.resource_url()
in just this way. As a result, anyapp_url
passed within the**kw
values toroute_path
will be ignored.scheme
,host
, andport
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.
See also
See also Dealing with a JSON-Encoded Request Body.
- 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 settingreify=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 aValueError
will be raised ifname
isNone
orreify
isTrue
.If
name
is None, the name of the property will be computed from the name of thecallable
.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 ifrequest.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.
- 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.
- property accept¶
Property representing the
Accept
header.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.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.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.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 usingparse_auth
andserialize_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 is192.168.1.1, 192.168.1.2
, the value will be192.168.1.1
). If noHTTP_X_FORWARDED_FOR
header is present in the environ at all, this attribute will return the value of theREMOTE_ADDR
header. If theREMOTE_ADDR
header is unset, this attribute will return the valueNone
.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 thatHTTP_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 theSERVER_NAME
value in the environment if it doesn't. For example, if the environment contains anHTTP_HOST
value offoo.example.com:8000
,request.domain
will returnfoo.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 toself.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 theHTTP_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 noHTTP_HOST
header is present in the environ at all, this attribute will return the value of theSERVER_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 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_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)[source]¶
Return
True
if the object passed asob
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
- 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¶
alias of
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 toself.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 likeroutes
set this value.
- property urlvars¶
Return any named variables matched in the URL.
Takes values from
environ['wsgiorg.routing_args']
. Systems likeroutes
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).
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
.
- apply_request_extensions(request)[source]¶
Apply request extensions (methods and properties) to an instance of
pyramid.interfaces.IRequest
. This method is dependent on therequest
containing a properly initialized registry.After invoking this method, the
request
should have the methods and properties that were defined usingpyramid.config.Configurator.add_request_method()
.