pyramid.request¶
- class Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)[ソース]¶
A subclass of the WebOb Request class. An instance of this class is created by the router and is provided to a view callable (and to other subsystems) as the
requestargument.The documentation below (save for the
add_response_callbackandadd_finished_callbackmethods, 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
contextattribute 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
registryattribute 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
rootattribute 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
subpathattribute 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
traversedattribute 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_nameattribute 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_rootattribute 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_pathattribute 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
exceptionattribute of the request within a exception view, a response callback or a finished callback. If no exception occurred, the value ofrequest.exceptionwill beNonewithin 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_infoattribute of the request within a exception view, a response callback or a finished callback. If no exception occurred, the value ofrequest.exc_infowill beNonewithin response and finished callbacks.
- response¶
This attribute is actually a "reified" property which returns an instance of the
pyramid.response.Responseclass. 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 sameResponseobject.The
request.responseAPI 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.responseAPI 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.responsein 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.sessionattribute will cause apyramid.exceptions.ConfigurationErrorto be raised.
- matchdict¶
If a route has matched during this request, this attribute will be a dictionary containing the values matched by the URL pattern associated with the route. If a route has not matched during this request, the value of this attribute will be
None. See The Matchdict.
- matched_route¶
If a route has matched during this request, this attribute will be an object representing the route matched by the URL pattern associated with the route. If a route has not matched during this request, the value of this attribute will be
None. See The Matched Route.
- authenticated_userid¶
A property which returns the userid of the currently authenticated user or
Noneif there is no security policy in effect or there is no currently authenticated user.
- unauthenticated_userid¶
バージョン 2.0 で非推奨:
unauthenticated_useridhas been deprecated in version 2.0. Useauthenticated_useridoridentityinstead. See Upgrading Authentication/Authorization for more information.A property which returns a value which represents the claimed (not verified) userid of the credentials present in the request.
Noneif 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¶
バージョン 2.0 で非推奨: The new security policy has removed the concept of principals. See Upgrading Authentication/Authorization for more information.
A property which returns the list of 'effective' principal identifiers for this request. This list typically includes the userid of the currently authenticated user if a user is currently authenticated, but this depends on the authentication policy in effect. If no authentication policy is in effect, this will return a sequence containing only the
pyramid.authorization.Everyoneprincipal.
- invoke_subrequest(request, use_tweens=False)¶
バージョン 1.4a1 で追加.
Obtain a response object from the Pyramid application based on information in the
requestobject provided. Therequestobject must be an object that implements the Pyramid request interface (such as apyramid.request.Requestinstance). Ifuse_tweensisTrue, the request will be sent to the tween in the tween stack closest to the request ingress. Ifuse_tweensisFalse, 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
registryattribute (the current Pyramid registry) and ainvoke_subrequestattribute (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
NewRequestevent to be sent at the beginning of request processing.causes a
ContextFoundevent 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
NewResponseevent to be sent if a response is obtained.Calls any finished callback functions defined within the request's lifetime.
invoke_subrequestisn'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. thepshellenvironment.参考
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_infoIf 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.requestIf 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.secureIf the exception view should not be rendered if the current user does not have the appropriate permission, this should be
True. Default:True.reraiseA boolean indicating whether the original error should be reraised if a response object could not be created. If
Falsethen anpyramid.httpexceptions.HTTPNotFound`exception will be raised. Default:False.If a response is generated then
request.exceptionandrequest.exc_infowill be left at the values used to render the response. Otherwise the previous values forrequest.exceptionandrequest.exc_infowill be restored.バージョン 1.7 で追加.
バージョン 1.9 で変更: The
request.exceptionandrequest.exc_infoproperties 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
reraiseargument.
- has_permission(permission, context=None)¶
Given a permission and an optional context, returns an instance of
pyramid.security.Allowedif 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 security policy. Returnspyramid.security.Allowedunconditionally if no security policy has been registered for this request. Ifcontextis not supplied or is supplied asNone, the context used is therequest.contextattribute.- パラメータ
- 戻り値
Either
pyramid.security.Allowedorpyramid.security.Denied.
- add_response_callback(callback)¶
Add a callback to the set of callbacks to be called by the router at a point after a response object is successfully created. Pyramid does not have a global response object: this functionality allows an application to register an action to be performed against the response once one is created.
A 'callback' is a callable which accepts two positional parameters:
requestandresponse. 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.NewResponseevent is sent.Errors raised by callbacks are not handled specially. They will be propagated to the caller of the Pyramid router application.
参考
See also Using Response Callbacks.
- add_finished_callback(callback)¶
Add a callback to the set of callbacks to be called unconditionally by the router at the very end of request processing.
callbackis 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 therequestprovided to a finished callback will have no meaningful effect, because response processing will have already occurred, and the request's scope will expire almost immediately after all finished callbacks have been processed.Errors raised by finished callbacks are not handled specially. They will be propagated to the caller of the Pyramid router application.
参考
See also Using Finished Callbacks.
- route_url(route_name, *elements, **kw)¶
Generates a fully qualified URL for a named Pyramid route configuration.
Use the route's
nameas 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
KeyErrorexception 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
:segmentarguments 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
*remainderarguments can be passed as strings or tuples of Unicode/string values. If a tuple is passed as a*remainderreplacement 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*remainderreplacement value, it is tacked on to the URL after being URL-quoted-except-for-embedded-slashes.If
_queryis provided, it will be used to compose a query string that will be tacked on to the end of the URL. The value of_querymay 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-urlencodedformat. A non-x-www-form-urlencodedquery string may be used by passing a string value as_queryin 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=vform 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.注釈
Python data structures that are passed as
_querywhich are sequences or dictionaries are turned into a string under the same rules as when run throughurllib.urlencode()with thedoseqargument 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
_anchoris 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_anchoris passed asfooand the route URL ishttp://example.com/route/url, the resulting generated URL will behttp://example.com/route/url#foo).注釈
If
_anchoris passed as a string, it should be UTF-8 encoded. If_anchoris passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL.If both
_anchorand_queryare 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_portis 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
_schemeis passed ashttps, and_portis not passed, the_portvalue is assumed to have been passed as443. Likewise, if_schemeis passed ashttpand_portis not passed, the_portvalue is assumed to have been passed as80. To avoid this behavior, always explicitly pass_portwhenever you pass_scheme.If a keyword
_app_urlis present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an_app_urlofhttp://example.com:8080/foowould cause the URLhttp://example.com:8080/foo/fleeb/flubto be returned from this function if the expansion of the route pattern associated with theroute_nameexpanded to/fleeb/flub. If_app_urlis not specified, the result ofrequest.application_urlwill be used as the prefix (the default).If both
_app_urland any of_scheme,_host, or_portare passed,_app_urltakes precedence and any values passed for_scheme,_host, and_portwill be ignored.This function raises a
KeyErrorif the URL cannot be generated due to missing replacement names. Extra replacement names are ignored.If the route object which matches the
route_nameargument has a pregenerator, the*elementsand**kwarguments passed to this function might be augmented or changed.バージョン 1.5 で変更: Allow the
_queryoption to be a string to enable alternative encodings.The
_anchoroption will be escaped instead of using its raw string representation.バージョン 1.9 で変更: If
_queryor_anchorare falsey (such asNoneor 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.注釈
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_urlpassed within the**kwvalues toroute_pathwill 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_urldoes not named_route_name.The route name used to generate a URL is taken from either the
_route_namekeyword argument or the name of the route which is currently associated with the request if_route_namewas not passed. Keys and values from the current request matchdict are combined with thekwarguments 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_namekeyword 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 thefooactionroute. 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.注釈
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_urlpassed within the**kwvalues tocurrent_route_pathwill 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
pathargument points at a file or directory on disk which a URL should be generated for. Thepathmay 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
**kwargument is the same as the purpose of thepyramid.request.Request.route_url()**kwargument. 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*kwwhen generating a static asset URL.This function raises a
ValueErrorif a static view definition cannot be found which matches the path specification.
- static_path(path, **kw)¶
Generates a path (aka a 'relative URL', a URL minus the host, scheme, and port) for a static resource.
This function accepts the same argument as
pyramid.request.Request.static_url()and performs the same duty. It just omits the host, port, and scheme information in the return value; only the script_name, path, query parameters, and anchor data are present in the returned string.Example:
request.static_path('mypackage:static/foo.css') => /static/foo.css
注釈
Calling
request.static_path(apath)is the same as 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_urlpassed within the**kwvalues tostatic_pathwill 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_HOSTorSERVER_NAMEin 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
elementsmust be strings Unicode objects, or integer objects. These will be joined by slashes and appended to the generated resource URL. Each of the elements passed in is URL-quoted before being appended; if any element is Unicode, it will converted to a UTF-8 bytestring before being URL-quoted. If any element is an integer, it will be converted to its string representation before being URL-quoted.警告
if no
elementsarguments are specified, the resource URL will end with a trailing slash. If anyelementsare used, the generated URL will not end in a trailing slash.If
queryis provided, it will be used to compose a query string that will be tacked on to the end of the URL. The value ofquerymay 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-urlencodedformat. A non-x-www-form-urlencodedquery string may be used by passing a string value asqueryin 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=vform 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.注釈
Python data structures that are passed as
querywhich are sequences or dictionaries are turned into a string under the same rules as when run throughurllib.urlencode()with thedoseqargument 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
anchoris present, its string representation will be used as a named anchor in the generated URL (e.g. ifanchoris passed asfooand the resource URL ishttp://example.com/resource/url, the resulting generated URL will behttp://example.com/resource/url#foo).注釈
If
anchoris passed as a string, it should be UTF-8 encoded. Ifanchoris passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL.If both
anchorandqueryare 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, orportis 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
schemeis passed ashttps, and an explicitportis not passed, theportvalue is assumed to have been passed as443. Likewise, ifschemeis passed ashttpandportis not passed, theportvalue is assumed to have been passed as80. To avoid this behavior, always explicitly passportwhenever you passscheme.If a keyword argument
app_urlis 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/barwill 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/barwill return/baz/bar.If
app_urlis passed and any ofscheme,port, orhostare also passed,app_urlwill take precedence and the values passed forscheme,host, and/orportwill be ignored.If the
resourcepassed 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 Overriding Resource URL Generation.
If
route_nameis passed, this function will delegate its URL production to theroute_urlfunction. 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_nameif the route being named has a*remainderstararg 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
traversewhenroute_urlis called. You can influence this by passing a differentroute_remainder_namevalue if the route has a different*starargvalue at its end. For example if the route pattern you want to replace has a*subpathstararg ala/foo*subpath:request.resource_url( resource, route_name='myroute', route_remainder_name='subpath' )
If
route_nameis 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_kworroute_remainder_nameis passed, butroute_nameis not passed, bothroute_kwandroute_remainder_namewill be ignored. Ifroute_nameis passed, the__resource_url__method of the resource passed is ignored unconditionally. This feature is incompatible with resources which generate their own URLs.注釈
If the resource used is the result of a traversal, it must be location-aware. The resource can also be the context of a URL dispatch; contexts found this way do not need to be location-aware.
注釈
If a 'virtual root path' is present in the request environment (the value of the WSGI environ key
HTTP_X_VHM_ROOT), and the resource was obtained via traversal, the URL path will not include the virtual root prefix (it will be stripped off the left hand side of the generated URL).注釈
For backwards compatibility purposes, this method is also aliased as the
model_urlmethod of request.バージョン 1.3 で変更: Added the
app_urlkeyword argument.バージョン 1.5 で変更: Allow the
queryoption to be a string to enable alternative encodings.The
anchoroption will be escaped instead of using its raw string representation.Added the
route_name,route_kw, androute_remainder_namekeyword arguments.バージョン 1.9 で変更: If
queryoranchorare falsey (such asNoneor an empty string) they will not be included in the generated url.
- resource_path(resource, *elements, **kw)¶
Generates a path (aka a 'relative URL', a URL minus the host, scheme, and port) for a resource.
This function accepts the same argument as
pyramid.request.Request.resource_url()and performs the same duty. It just omits the host, port, and scheme information in the return value; only the script_name, path, query parameters, and anchor data are present in the returned string.注釈
Calling
request.resource_path(resource)is the same as 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_urlpassed within the**kwvalues toroute_pathwill be ignored.scheme,host, andportare also ignored.
- set_property(callable, name=None, reify=False)¶
Add a callable or a property descriptor to the request instance.
Properties, unlike attributes, are lazily evaluated by executing an underlying callable when accessed. They can be useful for adding features to an object without any cost if those features go unused.
A property may also be reified via the
pyramid.decorator.reifydecorator 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.callablecan either be a callable that accepts the request as its single positional parameter, or it can be a property descriptor.If the
callableis a property descriptor aValueErrorwill be raised ifnameisNoneorreifyisTrue.If
nameis 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.dbis accessed many times.This pattern provides a way to augment the
requestobject without having to subclass it, which can be useful for extension authors.バージョン 1.3 で追加.
- locale_name¶
The locale name of the current request as computed by the locale negotiator.
バージョン 1.5 で追加.
- property GET¶
Return a MultiDict containing all the variables from the QUERY_STRING.
- property POST¶
Return a MultiDict containing all the variables from a form request. Returns an empty dict-like object for non-form requests.
Form requests are typically POST requests, however any other requests with an appropriate Content-Type are also supported.
- property accept¶
Property representing the
Acceptheader.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-Charsetheader.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-Encodingheader.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-Languageheader.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
Authorizationheader (HTTP spec section 14.8). Converts it usingparse_authandserialize_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.inputkey 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_FORheader 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_FORheader is present in the environ at all, this attribute will return the value of theREMOTE_ADDRheader. If theREMOTE_ADDRheader is unset, this attribute will return the valueNone.警告
It is possible for user agents to put someone else's IP or just any string in
HTTP_X_FORWARDED_FORas 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_FORhas 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-Lengthheader (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
Dateheader (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_HOSTvalue in the environment if it exists, or theSERVER_NAMEvalue in the environment if it doesn't. For example, if the environment contains anHTTP_HOSTvalue offoo.example.com:8000,request.domainwill 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.bodyattributes.This will use
self.ResponseClassto figure out the class of the response object to return.If
applicationis 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_HOSTheader exists in the WSGI environ, this attribute returns the port number present in that header. If theHTTP_HOSTheader 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_HOSTheader is present in the environ at all, this attribute will return the value of theSERVER_PORTheader (which is guaranteed to be present).
- property host_url¶
The URL through the host (no path)
- property http_version¶
Gets and sets the
SERVER_PROTOCOLkey in the environment.
- property identity¶
Return an opaque object identifying the current user or
Noneif no user is authenticated or there is no security policy in effect.
- property if_match¶
Gets and sets the
If-Matchheader (HTTP spec section 14.24). Converts it as a Etag.
- property if_modified_since¶
Gets and sets the
If-Modified-Sinceheader (HTTP spec section 14.25). Converts it using HTTP date.
- property if_none_match¶
Gets and sets the
If-None-Matchheader (HTTP spec section 14.26). Converts it as a Etag.
- property if_range¶
Gets and sets the
If-Rangeheader (HTTP spec section 14.27). Converts it using IfRange object.
- property if_unmodified_since¶
Gets and sets the
If-Unmodified-Sinceheader (HTTP spec section 14.28). Converts it using HTTP date.
- property is_authenticated¶
Return
Trueif a user is authenticated for this request.
- property is_body_readable¶
webob.is_body_readable is a flag that tells us that we can read the input stream even though CONTENT_LENGTH is missing.
- property is_body_seekable¶
Gets and sets the
webob.is_body_seekablekey in the environment.
- is_response(ob)[ソース]¶
Return
Trueif the object passed asobis a valid response object,Falseotherwise.
- property is_xhr¶
Is X-Requested-With header present and equal to
XMLHttpRequest?Note: this isn't set by every XMLHttpRequest request, it is only set if you are using a Javascript library that sets it (or you set the header yourself manually). Currently Prototype and jQuery are known to set this header.
- property json¶
Access the body of the request as JSON
- property json_body¶
Access the body of the request as JSON
- make_body_seekable()¶
This forces
environ['wsgi.input']to be seekable. That means that, the content is copied into a BytesIO or temporary file and flagged as seekable, so that it will not be unnecessarily copied again.After calling this method the .body_file is always seeked to the start of file and .content_length is not None.
The choice to copy to BytesIO is made from
self.request_body_tempfile_limit
- make_tempfile()¶
Create a tempfile to store big request body. This API is not stable yet. A 'size' argument might be added.
- property max_forwards¶
Gets and sets the
Max-Forwardsheader (HTTP spec section 14.31). Converts it using int.
- property method¶
Gets and sets the
REQUEST_METHODkey 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_INFOkey 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
patternargument 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
Pragmaheader (HTTP spec section 14.32).
- property query_string¶
Gets and sets the
QUERY_STRINGkey in the environment.
- property range¶
Gets and sets the
Rangeheader (HTTP spec section 14.35). Converts it using Range object.
- property referer¶
Gets and sets the
Refererheader (HTTP spec section 14.36).
- property referrer¶
Gets and sets the
Refererheader (HTTP spec section 14.36).
- relative_url(other_url, to_application=False)¶
Resolve other_url relative to the request URL.
If
to_applicationis True, then resolve it relative to the URL with only SCRIPT_NAME
- property remote_addr¶
Gets and sets the
REMOTE_ADDRkey in the environment.
- property remote_host¶
Gets and sets the
REMOTE_HOSTkey in the environment.
- property remote_user¶
Gets and sets the
REMOTE_USERkey in the environment.
- remove_conditional_headers(remove_encoding=True, remove_range=True, remove_match=True, remove_modified=True)¶
Remove headers that make the request conditional.
These headers can cause the response to be 304 Not Modified, which in some cases you may not want to be possible.
This does not remove headers like If-Match, which are used for conflict detection.
- request_iface = <InterfaceClass pyramid.interfaces.IRequest>¶
- property scheme¶
Gets and sets the
wsgi.url_schemekey in the environment.
- property script_name¶
Gets and sets the
SCRIPT_NAMEkey in the environment.
- send(application=None, catch_exc_info=False)¶
Like
.call_application(application), except returns a response object with.status,.headers, and.bodyattributes.This will use
self.ResponseClassto figure out the class of the response object to return.If
applicationis not given, this will send the request toself.make_default_send_app()
- property server_name¶
Gets and sets the
SERVER_NAMEkey in the environment.
- property server_port¶
Gets and sets the
SERVER_PORTkey 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_INFOkey in the environment.
- property url¶
The full request URL, including QUERY_STRING
- property url_encoding¶
Gets and sets the
webob.url_encodingkey in the environment.
- property urlargs¶
Return any positional variables matched in the URL.
Takes values from
environ['wsgiorg.routing_args']. Systems likeroutesset this value.
- property urlvars¶
Return any named variables matched in the URL.
Takes values from
environ['wsgiorg.routing_args']. Systems likeroutesset this value.
- property uscript_name¶
Gets and sets the
SCRIPT_NAMEkey in the environment.
- property user_agent¶
Gets and sets the
User-Agentheader (HTTP spec section 14.43).
注釈
For information about the API of a multidict structure (such as
that used as request.GET, request.POST, and request.params),
see pyramid.interfaces.IMultiDict.
- apply_request_extensions(request)[ソース]¶
Apply request extensions (methods and properties) to an instance of
pyramid.interfaces.IRequest. This method is dependent on therequestcontaining a properly initialized registry.After invoking this method, the
requestshould have the methods and properties that were defined usingpyramid.config.Configurator.add_request_method().
- class RequestLocalCache(creator=None)[ソース]¶
A store that caches values during for the lifecycle of a request.
Wrapping Functions
Instantiate and use it to decorate functions that accept a request parameter. The result is cached and returned in subsequent invocations of the function.
@RequestLocalCache() def get_user(request): result = ... # do some expensive computations return result value = get_user(request) # manipulate the cache directly get_user.cache.clear(request)
The cache instance is attached to the resulting function as the
cacheattribute such that the function may be used to manipulate the cache.Wrapping Methods
A method can be used as the creator function but it needs to be bound to an instance such that it only accepts one argument - the request. An easy way to do this is to bind the creator in the constructor and then use
get_or_create():class SecurityPolicy: def __init__(self): self.identity_cache = RequestLocalCache(self.load_identity) def load_identity(self, request): result = ... # do some expensive computations return result def identity(self, request): return self.identity_cache.get_or_create(request)
The cache maintains a weakref to each request and will release the cached values when the request is garbage-collected. However, in most scenarios, it will release resources earlier via
pyramid.request.Request.add_finished_callback().バージョン 2.0 で追加.
- get(request, default=NO_VALUE)[ソース]¶
Return the value from the cache.
The cached value is returned or
default.
- get_or_create(request, creator=None)[ソース]¶
Return the value from the cache. Compute if necessary.
If no value is cached then execute the creator, cache the result, and return it.
The creator may be passed in as an argument or bound to the cache by decorating a function or supplied as a constructor argument.