doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
class werkzeug.routing.MapAdapter(map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args=None)
Returned by Map.bind() or Map.bind_to_environ() and does the URL matching and building based on runtime information. Parameters
map (werkzeug.routing.Map) β
server_name (str) β
script_name (str) β
subdomain (Optional[str]) β
url_scheme (str) β
path_info (str) β
default_method (str) β
query_args (Optional[Union[Mapping[str, Any], str]]) β
allowed_methods(path_info=None)
Returns the valid methods that match for a given path. Changelog New in version 0.7. Parameters
path_info (Optional[str]) β Return type
Iterable[str]
build(endpoint, values=None, method=None, force_external=False, append_unknown=True, url_scheme=None)
Building URLs works pretty much the other way round. Instead of match you call build and pass it the endpoint and a dict of arguments for the placeholders. The build function also accepts an argument called force_external which, if you set it to True will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain. >>> m = Map([
... Rule('/', endpoint='index'),
... Rule('/downloads/', endpoint='downloads/index'),
... Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.build("index", {})
'/'
>>> urls.build("downloads/show", {'id': 42})
'/downloads/42'
>>> urls.build("downloads/show", {'id': 42}, force_external=True)
'http://example.com/downloads/42'
Because URLs cannot contain non ASCII data you will always get bytes back. Non ASCII characters are urlencoded with the charset defined on the map instance. Additional values are converted to strings and appended to the URL as URL querystring parameters: >>> urls.build("index", {'q': 'My Searchstring'})
'/?q=My+Searchstring'
When processing those additional values, lists are furthermore interpreted as multiple values (as per werkzeug.datastructures.MultiDict): >>> urls.build("index", {'q': ['a', 'b', 'c']})
'/?q=a&q=b&q=c'
Passing a MultiDict will also add multiple values: >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b'))))
'/?p=z&q=a&q=b'
If a rule does not exist when building a BuildError exception is raised. The build method accepts an argument called method which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified. Parameters
endpoint (str) β the endpoint of the URL to build.
values (Optional[Mapping[str, Any]]) β the values for the URL to build. Unhandled values are appended to the URL as query parameters.
method (Optional[str]) β the HTTP method for the rule if there are different URLs for different methods on the same endpoint.
force_external (bool) β enforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL.
append_unknown (bool) β unknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those.
url_scheme (Optional[str]) β Scheme to use in place of the bound url_scheme. Return type
str Changed in version 2.0: Added the url_scheme parameter. Changelog New in version 0.6: Added the append_unknown parameter.
dispatch(view_func, path_info=None, method=None, catch_http_exceptions=False)
Does the complete dispatching process. view_func is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it catch_http_exceptions=True and it will catch the http exceptions. Here a small example for the dispatch usage: from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import responder
from werkzeug.routing import Map, Rule
def on_index(request):
return Response('Hello from the index')
url_map = Map([Rule('/', endpoint='index')])
views = {'index': on_index}
@responder
def application(environ, start_response):
request = Request(environ)
urls = url_map.bind_to_environ(environ)
return urls.dispatch(lambda e, v: views[e](request, **v),
catch_http_exceptions=True)
Keep in mind that this method might return exception objects, too, so use Response.force_type to get a response object. Parameters
view_func (Callable[[str, Mapping[str, Any]], WSGIApplication]) β a function that is called with the endpoint as first argument and the value dict as second. Has to dispatch to the actual view function with this information. (see above)
path_info (Optional[str]) β the path info to use for matching. Overrides the path info specified on binding.
method (Optional[str]) β the HTTP method used for matching. Overrides the method specified on binding.
catch_http_exceptions (bool) β set to True to catch any of the werkzeug HTTPExceptions. Return type
WSGIApplication
get_host(domain_part)
Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name. Parameters
domain_part (Optional[str]) β Return type
str
make_alias_redirect_url(path, endpoint, values, method, query_args)
Internally called to make an alias redirect URL. Parameters
path (str) β
endpoint (str) β
values (Mapping[str, Any]) β
method (str) β
query_args (Union[Mapping[str, Any], str]) β Return type
str
match(path_info=None, method=None, return_rule=False, query_args=None, websocket=None)
The usage is simple: you just pass the match method the current path info as well as the method (which defaults to GET). The following things can then happen: you receive a NotFound exception that indicates that no URL is matching. A NotFound exception is also a WSGI application you can call to get a default page not found page (happens to be the same object as werkzeug.exceptions.NotFound) you receive a MethodNotAllowed exception that indicates that there is a match for this URL but not for the current request method. This is useful for RESTful applications. you receive a RequestRedirect exception with a new_url attribute. This exception is used to notify you about a request Werkzeug requests from your WSGI application. This is for example the case if you request /foo although the correct URL is /foo/ You can use the RequestRedirect instance as response-like object similar to all other subclasses of HTTPException. you receive a WebsocketMismatch exception if the only match is a WebSocket rule but the bind is an HTTP request, or if the match is an HTTP rule but the bind is a WebSocket request. you get a tuple in the form (endpoint, arguments) if there is a match (unless return_rule is True, in which case you get a tuple in the form (rule, arguments)) If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly). All of the exceptions raised are subclasses of HTTPException so they can be used as WSGI responses. They will all render generic error or redirect pages. Here is a small example for matching: >>> m = Map([
... Rule('/', endpoint='index'),
... Rule('/downloads/', endpoint='downloads/index'),
... Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.match("/", "GET")
('index', {})
>>> urls.match("/downloads/42")
('downloads/show', {'id': 42})
And here is what happens on redirect and missing URLs: >>> urls.match("/downloads")
Traceback (most recent call last):
...
RequestRedirect: http://example.com/downloads/
>>> urls.match("/missing")
Traceback (most recent call last):
...
NotFound: 404 Not Found
Parameters
path_info (Optional[str]) β the path info to use for matching. Overrides the path info specified on binding.
method (Optional[str]) β the HTTP method used for matching. Overrides the method specified on binding.
return_rule (bool) β return the rule that matched instead of just the endpoint (defaults to False).
query_args (Optional[Union[Mapping[str, Any], str]]) β optional query arguments that are used for automatic redirects as string or dictionary. Itβs currently not possible to use the query arguments for URL matching.
websocket (Optional[bool]) β Match WebSocket instead of HTTP requests. A websocket request has a ws or wss url_scheme. This overrides that detection. Return type
Tuple[Union[str, werkzeug.routing.Rule], Mapping[str, Any]] Changelog New in version 1.0: Added websocket. Changed in version 0.8: query_args can be a string. New in version 0.7: Added query_args. New in version 0.6: Added return_rule.
test(path_info=None, method=None)
Test if a rule would match. Works like match but returns True if the URL matches, or False if it does not exist. Parameters
path_info (Optional[str]) β the path info to use for matching. Overrides the path info specified on binding.
method (Optional[str]) β the HTTP method used for matching. Overrides the method specified on binding. Return type
bool | werkzeug.routing.index#werkzeug.routing.MapAdapter |
allowed_methods(path_info=None)
Returns the valid methods that match for a given path. Changelog New in version 0.7. Parameters
path_info (Optional[str]) β Return type
Iterable[str] | werkzeug.routing.index#werkzeug.routing.MapAdapter.allowed_methods |
build(endpoint, values=None, method=None, force_external=False, append_unknown=True, url_scheme=None)
Building URLs works pretty much the other way round. Instead of match you call build and pass it the endpoint and a dict of arguments for the placeholders. The build function also accepts an argument called force_external which, if you set it to True will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain. >>> m = Map([
... Rule('/', endpoint='index'),
... Rule('/downloads/', endpoint='downloads/index'),
... Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.build("index", {})
'/'
>>> urls.build("downloads/show", {'id': 42})
'/downloads/42'
>>> urls.build("downloads/show", {'id': 42}, force_external=True)
'http://example.com/downloads/42'
Because URLs cannot contain non ASCII data you will always get bytes back. Non ASCII characters are urlencoded with the charset defined on the map instance. Additional values are converted to strings and appended to the URL as URL querystring parameters: >>> urls.build("index", {'q': 'My Searchstring'})
'/?q=My+Searchstring'
When processing those additional values, lists are furthermore interpreted as multiple values (as per werkzeug.datastructures.MultiDict): >>> urls.build("index", {'q': ['a', 'b', 'c']})
'/?q=a&q=b&q=c'
Passing a MultiDict will also add multiple values: >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b'))))
'/?p=z&q=a&q=b'
If a rule does not exist when building a BuildError exception is raised. The build method accepts an argument called method which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified. Parameters
endpoint (str) β the endpoint of the URL to build.
values (Optional[Mapping[str, Any]]) β the values for the URL to build. Unhandled values are appended to the URL as query parameters.
method (Optional[str]) β the HTTP method for the rule if there are different URLs for different methods on the same endpoint.
force_external (bool) β enforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL.
append_unknown (bool) β unknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those.
url_scheme (Optional[str]) β Scheme to use in place of the bound url_scheme. Return type
str Changed in version 2.0: Added the url_scheme parameter. Changelog New in version 0.6: Added the append_unknown parameter. | werkzeug.routing.index#werkzeug.routing.MapAdapter.build |
dispatch(view_func, path_info=None, method=None, catch_http_exceptions=False)
Does the complete dispatching process. view_func is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it catch_http_exceptions=True and it will catch the http exceptions. Here a small example for the dispatch usage: from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import responder
from werkzeug.routing import Map, Rule
def on_index(request):
return Response('Hello from the index')
url_map = Map([Rule('/', endpoint='index')])
views = {'index': on_index}
@responder
def application(environ, start_response):
request = Request(environ)
urls = url_map.bind_to_environ(environ)
return urls.dispatch(lambda e, v: views[e](request, **v),
catch_http_exceptions=True)
Keep in mind that this method might return exception objects, too, so use Response.force_type to get a response object. Parameters
view_func (Callable[[str, Mapping[str, Any]], WSGIApplication]) β a function that is called with the endpoint as first argument and the value dict as second. Has to dispatch to the actual view function with this information. (see above)
path_info (Optional[str]) β the path info to use for matching. Overrides the path info specified on binding.
method (Optional[str]) β the HTTP method used for matching. Overrides the method specified on binding.
catch_http_exceptions (bool) β set to True to catch any of the werkzeug HTTPExceptions. Return type
WSGIApplication | werkzeug.routing.index#werkzeug.routing.MapAdapter.dispatch |
get_host(domain_part)
Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name. Parameters
domain_part (Optional[str]) β Return type
str | werkzeug.routing.index#werkzeug.routing.MapAdapter.get_host |
make_alias_redirect_url(path, endpoint, values, method, query_args)
Internally called to make an alias redirect URL. Parameters
path (str) β
endpoint (str) β
values (Mapping[str, Any]) β
method (str) β
query_args (Union[Mapping[str, Any], str]) β Return type
str | werkzeug.routing.index#werkzeug.routing.MapAdapter.make_alias_redirect_url |
match(path_info=None, method=None, return_rule=False, query_args=None, websocket=None)
The usage is simple: you just pass the match method the current path info as well as the method (which defaults to GET). The following things can then happen: you receive a NotFound exception that indicates that no URL is matching. A NotFound exception is also a WSGI application you can call to get a default page not found page (happens to be the same object as werkzeug.exceptions.NotFound) you receive a MethodNotAllowed exception that indicates that there is a match for this URL but not for the current request method. This is useful for RESTful applications. you receive a RequestRedirect exception with a new_url attribute. This exception is used to notify you about a request Werkzeug requests from your WSGI application. This is for example the case if you request /foo although the correct URL is /foo/ You can use the RequestRedirect instance as response-like object similar to all other subclasses of HTTPException. you receive a WebsocketMismatch exception if the only match is a WebSocket rule but the bind is an HTTP request, or if the match is an HTTP rule but the bind is a WebSocket request. you get a tuple in the form (endpoint, arguments) if there is a match (unless return_rule is True, in which case you get a tuple in the form (rule, arguments)) If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly). All of the exceptions raised are subclasses of HTTPException so they can be used as WSGI responses. They will all render generic error or redirect pages. Here is a small example for matching: >>> m = Map([
... Rule('/', endpoint='index'),
... Rule('/downloads/', endpoint='downloads/index'),
... Rule('/downloads/<int:id>', endpoint='downloads/show')
... ])
>>> urls = m.bind("example.com", "/")
>>> urls.match("/", "GET")
('index', {})
>>> urls.match("/downloads/42")
('downloads/show', {'id': 42})
And here is what happens on redirect and missing URLs: >>> urls.match("/downloads")
Traceback (most recent call last):
...
RequestRedirect: http://example.com/downloads/
>>> urls.match("/missing")
Traceback (most recent call last):
...
NotFound: 404 Not Found
Parameters
path_info (Optional[str]) β the path info to use for matching. Overrides the path info specified on binding.
method (Optional[str]) β the HTTP method used for matching. Overrides the method specified on binding.
return_rule (bool) β return the rule that matched instead of just the endpoint (defaults to False).
query_args (Optional[Union[Mapping[str, Any], str]]) β optional query arguments that are used for automatic redirects as string or dictionary. Itβs currently not possible to use the query arguments for URL matching.
websocket (Optional[bool]) β Match WebSocket instead of HTTP requests. A websocket request has a ws or wss url_scheme. This overrides that detection. Return type
Tuple[Union[str, werkzeug.routing.Rule], Mapping[str, Any]] Changelog New in version 1.0: Added websocket. Changed in version 0.8: query_args can be a string. New in version 0.7: Added query_args. New in version 0.6: Added return_rule. | werkzeug.routing.index#werkzeug.routing.MapAdapter.match |
test(path_info=None, method=None)
Test if a rule would match. Works like match but returns True if the URL matches, or False if it does not exist. Parameters
path_info (Optional[str]) β the path info to use for matching. Overrides the path info specified on binding.
method (Optional[str]) β the HTTP method used for matching. Overrides the method specified on binding. Return type
bool | werkzeug.routing.index#werkzeug.routing.MapAdapter.test |
Middleware A WSGI middleware is a WSGI application that wraps another application in order to observe or change its behavior. Werkzeug provides some middleware for common use cases. X-Forwarded-For Proxy Fix Serve Shared Static Files Application Dispatcher Basic HTTP Proxy WSGI Protocol Linter Application Profiler The interactive debugger is also a middleware that can be applied manually, although it is typically used automatically with the development server. | werkzeug.middleware.index |
class werkzeug.datastructures.MIMEAccept(values=())
Like Accept but with special methods and behavior for mimetypes.
property accept_html
True if this object accepts HTML.
property accept_json
True if this object accepts JSON.
property accept_xhtml
True if this object accepts XHTML. | werkzeug.datastructures.index#werkzeug.datastructures.MIMEAccept |
class werkzeug.datastructures.MultiDict(mapping=None)
A MultiDict is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key. MultiDict implements all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key. If you want to gain access to the other values, too, you have to use the list methods as explained below. Basic Usage: >>> d = MultiDict([('a', 'b'), ('a', 'c')])
>>> d
MultiDict([('a', 'b'), ('a', 'c')])
>>> d['a']
'b'
>>> d.getlist('a')
['b', 'c']
>>> 'a' in d
True
It behaves like a normal dict thus all dict functions will only return the first value when multiple values for one key are found. From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions. A MultiDict can be constructed from an iterable of (key, value) tuples, a dict, a MultiDict or from Werkzeug 0.2 onwards some keyword parameters. Parameters
mapping β the initial value for the MultiDict. Either a regular dict, an iterable of (key, value) tuples or None.
add(key, value)
Adds a new value for the key. Changelog New in version 0.6. Parameters
key β the key for the value.
value β the value to add.
clear() β None. Remove all items from D.
copy()
Return a shallow copy of this object.
deepcopy(memo=None)
Return a deep copy of this object.
fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value.
get(key, default=None, type=None)
Return the default value if the requested data doesnβt exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found: >>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
Parameters
key β The key to be looked up.
default β The default value to be returned if the key canβt be looked up. If not further specified None is returned.
type β A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the default value is returned.
getlist(key, type=None)
Return the list of items for a given key. If that key is not in the MultiDict, the return value will be an empty list. Just like get, getlist accepts a type parameter. All items will be converted with the callable defined there. Parameters
key β The key to be looked up.
type β A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the value will be removed from the list. Returns
a list of all the values for the key.
items(multi=False)
Return an iterator of (key, value) pairs. Parameters
multi β If set to True the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key.
keys() β a set-like object providing a view on Dβs keys
lists()
Return a iterator of (key, values) pairs, where values is the list of all values associated with the key.
listvalues()
Return an iterator of all values associated with a key. Zipping keys() and this is the same as calling lists(): >>> d = MultiDict({"foo": [1, 2, 3]})
>>> zip(d.keys(), d.listvalues()) == d.lists()
True
pop(key, default=no value)
Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: >>> d = MultiDict({"foo": [1, 2, 3]})
>>> d.pop("foo")
1
>>> "foo" in d
False
Parameters
key β the key to pop.
default β if provided the value to return if the key was not in the dictionary.
popitem()
Pop an item from the dict.
popitemlist()
Pop a (key, list) tuple from the dict.
poplist(key)
Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. Changelog Changed in version 0.5: If the key does no longer exist a list is returned instead of raising an error.
setdefault(key, default=None)
Returns the value for the key if it is in the dict, otherwise it returns default and sets that value for key. Parameters
key β The key to be looked up.
default β The default value to be returned if the key is not in the dict. If not further specified itβs None.
setlist(key, new_list)
Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. >>> d = MultiDict()
>>> d.setlist('foo', ['1', '2'])
>>> d['foo']
'1'
>>> d.getlist('foo')
['1', '2']
Parameters
key β The key for which the values are set.
new_list β An iterable with the new values for the key. Old values are removed first.
setlistdefault(key, default_list=None)
Like setdefault but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiDict({"foo": 1})
>>> d.setlistdefault("foo").extend([2, 3])
>>> d.getlist("foo")
[1, 2, 3]
Parameters
key β The key to be looked up.
default_list β An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. Returns
a list
to_dict(flat=True)
Return the contents as regular dict. If flat is True the returned dict will only have the first item present, if flat is False all values will be returned as lists. Parameters
flat β If set to False the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key. Returns
a dict
update(mapping)
update() extends rather than replaces existing key lists: >>> a = MultiDict({'x': 1})
>>> b = MultiDict({'x': 2, 'y': 3})
>>> a.update(b)
>>> a
MultiDict([('y', 3), ('x', 1), ('x', 2)])
If the value list for a key in other_dict is empty, no new values will be added to the dict and the key will not be created: >>> x = {'empty_list': []}
>>> y = MultiDict()
>>> y.update(x)
>>> y
MultiDict([])
values()
Returns an iterator of the first value on every keyβs value list. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict |
add(key, value)
Adds a new value for the key. Changelog New in version 0.6. Parameters
key β the key for the value.
value β the value to add. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.add |
clear() β None. Remove all items from D. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.clear |
copy()
Return a shallow copy of this object. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.copy |
deepcopy(memo=None)
Return a deep copy of this object. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.deepcopy |
fromkeys(value=None, /)
Create a new dictionary with keys from iterable and values set to value. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.fromkeys |
get(key, default=None, type=None)
Return the default value if the requested data doesnβt exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found: >>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
Parameters
key β The key to be looked up.
default β The default value to be returned if the key canβt be looked up. If not further specified None is returned.
type β A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the default value is returned. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.get |
getlist(key, type=None)
Return the list of items for a given key. If that key is not in the MultiDict, the return value will be an empty list. Just like get, getlist accepts a type parameter. All items will be converted with the callable defined there. Parameters
key β The key to be looked up.
type β A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the value will be removed from the list. Returns
a list of all the values for the key. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.getlist |
items(multi=False)
Return an iterator of (key, value) pairs. Parameters
multi β If set to True the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.items |
keys() β a set-like object providing a view on Dβs keys | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.keys |
lists()
Return a iterator of (key, values) pairs, where values is the list of all values associated with the key. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.lists |
listvalues()
Return an iterator of all values associated with a key. Zipping keys() and this is the same as calling lists(): >>> d = MultiDict({"foo": [1, 2, 3]})
>>> zip(d.keys(), d.listvalues()) == d.lists()
True | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.listvalues |
pop(key, default=no value)
Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: >>> d = MultiDict({"foo": [1, 2, 3]})
>>> d.pop("foo")
1
>>> "foo" in d
False
Parameters
key β the key to pop.
default β if provided the value to return if the key was not in the dictionary. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.pop |
popitem()
Pop an item from the dict. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.popitem |
popitemlist()
Pop a (key, list) tuple from the dict. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.popitemlist |
poplist(key)
Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. Changelog Changed in version 0.5: If the key does no longer exist a list is returned instead of raising an error. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.poplist |
setdefault(key, default=None)
Returns the value for the key if it is in the dict, otherwise it returns default and sets that value for key. Parameters
key β The key to be looked up.
default β The default value to be returned if the key is not in the dict. If not further specified itβs None. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.setdefault |
setlist(key, new_list)
Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. >>> d = MultiDict()
>>> d.setlist('foo', ['1', '2'])
>>> d['foo']
'1'
>>> d.getlist('foo')
['1', '2']
Parameters
key β The key for which the values are set.
new_list β An iterable with the new values for the key. Old values are removed first. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.setlist |
setlistdefault(key, default_list=None)
Like setdefault but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiDict({"foo": 1})
>>> d.setlistdefault("foo").extend([2, 3])
>>> d.getlist("foo")
[1, 2, 3]
Parameters
key β The key to be looked up.
default_list β An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. Returns
a list | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.setlistdefault |
to_dict(flat=True)
Return the contents as regular dict. If flat is True the returned dict will only have the first item present, if flat is False all values will be returned as lists. Parameters
flat β If set to False the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key. Returns
a dict | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.to_dict |
update(mapping)
update() extends rather than replaces existing key lists: >>> a = MultiDict({'x': 1})
>>> b = MultiDict({'x': 2, 'y': 3})
>>> a.update(b)
>>> a
MultiDict([('y', 3), ('x', 1), ('x', 2)])
If the value list for a key in other_dict is empty, no new values will be added to the dict and the key will not be created: >>> x = {'empty_list': []}
>>> y = MultiDict()
>>> y.update(x)
>>> y
MultiDict([]) | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.update |
values()
Returns an iterator of the first value on every keyβs value list. | werkzeug.datastructures.index#werkzeug.datastructures.MultiDict.values |
class werkzeug.datastructures.OrderedMultiDict(mapping=None)
Works like a regular MultiDict but preserves the order of the fields. To convert the ordered multi dict into a list you can use the items() method and pass it multi=True. In general an OrderedMultiDict is an order of magnitude slower than a MultiDict. note Due to a limitation in Python you cannot convert an ordered multi dict into a regular dict by using dict(multidict). Instead you have to use the to_dict() method, otherwise the internal bucket objects are exposed. | werkzeug.datastructures.index#werkzeug.datastructures.OrderedMultiDict |
werkzeug.http.parse_accept_header(value[, class])
Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new Accept object (basically a list of (value, quality) tuples sorted by the quality with some additional accessor methods). The second parameter can be a subclass of Accept that is created with the parsed values and returned. Parameters
value (Optional[str]) β the accept header string to be parsed.
cls (Optional[Type[werkzeug.http._TAnyAccept]]) β the wrapper class for the return value (can be Accept or a subclass thereof) Returns
an instance of cls. Return type
werkzeug.http._TAnyAccept | werkzeug.http.index#werkzeug.http.parse_accept_header |
werkzeug.http.parse_authorization_header(value)
Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either None if the header was invalid or not given, otherwise an Authorization object. Parameters
value (Optional[str]) β the authorization header to parse. Returns
a Authorization object or None. Return type
Optional[werkzeug.datastructures.Authorization] | werkzeug.http.index#werkzeug.http.parse_authorization_header |
werkzeug.http.parse_cache_control_header(value, on_update=None, cls=None)
Parse a cache control header. The RFC differs between response and request cache control, this method does not. Itβs your responsibility to not use the wrong control statements. Changelog New in version 0.5: The cls was added. If not specified an immutable RequestCacheControl is returned. Parameters
value (Optional[str]) β a cache control header to be parsed.
on_update (Optional[Callable[[werkzeug.http._TAnyCC], None]]) β an optional callable that is called every time a value on the CacheControl object is changed.
cls (Optional[Type[werkzeug.http._TAnyCC]]) β the class for the returned object. By default RequestCacheControl is used. Returns
a cls object. Return type
werkzeug.http._TAnyCC | werkzeug.http.index#werkzeug.http.parse_cache_control_header |
werkzeug.http.parse_content_range_header(value, on_update=None)
Parses a range header into a ContentRange object or None if parsing is not possible. Changelog New in version 0.7. Parameters
value (Optional[str]) β a content range header to be parsed.
on_update (Optional[Callable[[werkzeug.datastructures.ContentRange], None]]) β an optional callable that is called every time a value on the ContentRange object is changed. Return type
Optional[werkzeug.datastructures.ContentRange] | werkzeug.http.index#werkzeug.http.parse_content_range_header |
werkzeug.http.parse_cookie(header, charset='utf-8', errors='replace', cls=None)
Parse a cookie from a string or WSGI environ. The same key can be provided multiple times, the values are stored in-order. The default MultiDict will have the first value first, and all values can be retrieved with MultiDict.getlist(). Parameters
header (Optional[Union[WSGIEnvironment, str, bytes]]) β The cookie header as a string, or a WSGI environ dict with a HTTP_COOKIE key.
charset (str) β The charset for the cookie values.
errors (str) β The error behavior for the charset decoding.
cls (Optional[Type[ds.MultiDict]]) β A dict-like class to store the parsed cookies in. Defaults to MultiDict. Return type
ds.MultiDict[str, str] Changelog Changed in version 1.0.0: Returns a MultiDict instead of a TypeConversionDict. Changed in version 0.5: Returns a TypeConversionDict instead of a regular dict. The cls parameter was added. | werkzeug.http.index#werkzeug.http.parse_cookie |
werkzeug.http.parse_date(value)
Parse an RFC 2822 date into a timezone-aware datetime.datetime object, or None if parsing fails. This is a wrapper for email.utils.parsedate_to_datetime(). It returns None if parsing fails instead of raising an exception, and always returns a timezone-aware datetime object. If the string doesnβt have timezone information, it is assumed to be UTC. Parameters
value (Optional[str]) β A string with a supported date format. Return type
Optional[datetime.datetime] Changed in version 2.0: Return a timezone-aware datetime object. Use email.utils.parsedate_to_datetime. | werkzeug.http.index#werkzeug.http.parse_date |
werkzeug.http.parse_dict_header(value, cls=<class 'dict'>)
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the cls argument): >>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be None: >>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the dict again, use the dump_header() function. Changelog Changed in version 0.9: Added support for cls argument. Parameters
value (str) β a string with a dict header.
cls (Type[dict]) β callable to use for storage of parsed results. Returns
an instance of cls Return type
Dict[str, str] | werkzeug.http.index#werkzeug.http.parse_dict_header |
werkzeug.http.parse_etags(value)
Parse an etag header. Parameters
value (Optional[str]) β the tag header to parse Returns
an ETags object. Return type
werkzeug.datastructures.ETags | werkzeug.http.index#werkzeug.http.parse_etags |
werkzeug.formparser.parse_form_data(environ, stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True)
Parse the form data in the environ and return it as tuple in the form (stream, form, files). You should only call this method if the transport method is POST, PUT, or PATCH. If the mimetype of the data transmitted is multipart/form-data the files multidict will be filled with FileStorage objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty. This is a shortcut for the common usage of FormDataParser. Have a look at Dealing with Request Data for more details. Changelog New in version 0.5.1: The optional silent flag was added. New in version 0.5: The max_form_memory_size, max_content_length and cls parameters were added. Parameters
environ (WSGIEnvironment) β the WSGI environment to be used for parsing.
stream_factory (Optional[TStreamFactory]) β An optional callable that returns a new read and writeable file descriptor. This callable works the same as Response._get_file_stream().
charset (str) β The character set for URL and url encoded form data.
errors (str) β The encoding error behavior.
max_form_memory_size (Optional[int]) β the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an RequestEntityTooLarge exception is raised.
max_content_length (Optional[int]) β If this is provided and the transmitted data is longer than this value an RequestEntityTooLarge exception is raised.
cls (Optional[Type[werkzeug.datastructures.MultiDict]]) β an optional dict class to use. If this is not specified or None the default MultiDict is used.
silent (bool) β If set to False parsing errors will not be caught. Returns
A tuple in the form (stream, form, files). Return type
t_parse_result | werkzeug.http.index#werkzeug.formparser.parse_form_data |
werkzeug.http.parse_if_range_header(value)
Parses an if-range header which can be an etag or a date. Returns a IfRange object. Changed in version 2.0: If the value represents a datetime, it is timezone-aware. Changelog New in version 0.7. Parameters
value (Optional[str]) β Return type
werkzeug.datastructures.IfRange | werkzeug.http.index#werkzeug.http.parse_if_range_header |
werkzeug.http.parse_list_header(value)
Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like parse_set_header() just that items may appear multiple times and case sensitivity is preserved. The return value is a standard list: >>> parse_list_header('token, "quoted value"')
['token', 'quoted value']
To create a header from the list again, use the dump_header() function. Parameters
value (str) β a string with a list header. Returns
list Return type
List[str] | werkzeug.http.index#werkzeug.http.parse_list_header |
werkzeug.http.parse_options_header(value, multiple=False)
Parse a Content-Type like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8')
('text/html', {'charset': 'utf8'})
This should not be used to parse Cache-Control like headers that use a slightly different format. For these headers use the parse_dict_header() function. Changelog Changed in version 0.15: RFC 2231 parameter continuations are handled. New in version 0.5. Parameters
value (Optional[str]) β the header to parse.
multiple (bool) β Whether try to parse and return multiple MIME types Returns
(mimetype, options) or (mimetype, options, mimetype, options, β¦) if multiple=True Return type
Union[Tuple[str, Dict[str, str]], Tuple[Any, β¦]] | werkzeug.http.index#werkzeug.http.parse_options_header |
werkzeug.http.parse_range_header(value, make_inclusive=True)
Parses a range header into a Range object. If the header is missing or malformed None is returned. ranges is a list of (start, stop) tuples where the ranges are non-inclusive. Changelog New in version 0.7. Parameters
value (Optional[str]) β
make_inclusive (bool) β Return type
Optional[werkzeug.datastructures.Range] | werkzeug.http.index#werkzeug.http.parse_range_header |
werkzeug.http.parse_set_header(value, on_update=None)
Parse a set-like header and return a HeaderSet object: >>> hs = parse_set_header('token, "quoted value"')
The return value is an object that treats the items case-insensitively and keeps the order of the items: >>> 'TOKEN' in hs
True
>>> hs.index('quoted value')
1
>>> hs
HeaderSet(['token', 'quoted value'])
To create a header from the HeaderSet again, use the dump_header() function. Parameters
value (Optional[str]) β a set header to be parsed.
on_update (Optional[Callable[[werkzeug.datastructures.HeaderSet], None]]) β an optional callable that is called every time a value on the HeaderSet object is changed. Returns
a HeaderSet Return type
werkzeug.datastructures.HeaderSet | werkzeug.http.index#werkzeug.http.parse_set_header |
werkzeug.http.parse_www_authenticate_header(value, on_update=None)
Parse an HTTP WWW-Authenticate header into a WWWAuthenticate object. Parameters
value (Optional[str]) β a WWW-Authenticate header to parse.
on_update (Optional[Callable[[werkzeug.datastructures.WWWAuthenticate], None]]) β an optional callable that is called every time a value on the WWWAuthenticate object is changed. Returns
a WWWAuthenticate object. Return type
werkzeug.datastructures.WWWAuthenticate | werkzeug.http.index#werkzeug.http.parse_www_authenticate_header |
class werkzeug.routing.PathConverter(map, *args, **kwargs)
Like the default UnicodeConverter, but it also matches slashes. This is useful for wikis and similar applications: Rule('/<path:wikipage>')
Rule('/<path:wikipage>/edit')
Parameters
map (Map) β the Map.
args (Any) β
kwargs (Any) β Return type
None | werkzeug.routing.index#werkzeug.routing.PathConverter |
werkzeug.security.pbkdf2_bin(data, salt, iterations=260000, keylen=None, hashfunc=None)
Returns a binary digest for the PBKDF2 hash algorithm of data with the given salt. It iterates iterations times and produces a key of keylen bytes. By default, SHA-256 is used as hash function; a different hashlib hashfunc can be provided. Parameters
data (Union[str, bytes]) β the data to derive.
salt (Union[str, bytes]) β the salt for the derivation.
iterations (int) β the number of iterations.
keylen (Optional[int]) β the length of the resulting key. If not provided the digest size will be used.
hashfunc (Optional[Union[str, Callable]]) β the hash function to use. This can either be the string name of a known hash function or a function from the hashlib module. Defaults to sha256. Return type
bytes Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hashlib.pbkdf2_hmac() instead. Changelog New in version 0.9. | werkzeug.utils.index#werkzeug.security.pbkdf2_bin |
werkzeug.security.pbkdf2_hex(data, salt, iterations=260000, keylen=None, hashfunc=None)
Like pbkdf2_bin(), but returns a hex-encoded string. Parameters
data (Union[str, bytes]) β the data to derive.
salt (Union[str, bytes]) β the salt for the derivation.
iterations (int) β the number of iterations.
keylen (Optional[int]) β the length of the resulting key. If not provided, the digest size will be used.
hashfunc (Optional[Union[str, Callable]]) β the hash function to use. This can either be the string name of a known hash function, or a function from the hashlib module. Defaults to sha256. Return type
str Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hashlib.pbkdf2_hmac() instead. Changelog New in version 0.9. | werkzeug.utils.index#werkzeug.security.pbkdf2_hex |
werkzeug.wsgi.peek_path_info(environ, charset='utf-8', errors='replace')
Returns the next segment on the PATH_INFO or None if there is none. Works like pop_path_info() without modifying the environment: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> peek_path_info(env)
'a'
>>> peek_path_info(env)
'a'
If the charset is set to None bytes are returned. Changelog Changed in version 0.9: The path is now decoded and a charset and encoding parameter can be provided. New in version 0.5. Parameters
environ (WSGIEnvironment) β the WSGI environment that is checked.
charset (str) β
errors (str) β Return type
Optional[str] | werkzeug.wsgi.index#werkzeug.wsgi.peek_path_info |
werkzeug.wsgi.pop_path_info(environ, charset='utf-8', errors='replace')
Removes and returns the next segment of PATH_INFO, pushing it onto SCRIPT_NAME. Returns None if there is nothing left on PATH_INFO. If the charset is set to None bytes are returned. If there are empty segments ('/foo//bar) these are ignored but properly pushed to the SCRIPT_NAME: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> pop_path_info(env)
'a'
>>> env['SCRIPT_NAME']
'/foo/a'
>>> pop_path_info(env)
'b'
>>> env['SCRIPT_NAME']
'/foo/a/b'
Changelog Changed in version 0.9: The path is now decoded and a charset and encoding parameter can be provided. New in version 0.5. Parameters
environ (WSGIEnvironment) β the WSGI environment that is modified.
charset (str) β The encoding parameter passed to bytes.decode().
errors (str) β The errors paramater passed to bytes.decode(). Return type
Optional[str] | werkzeug.wsgi.index#werkzeug.wsgi.pop_path_info |
class werkzeug.middleware.profiler.ProfilerMiddleware(app, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, sort_by=('time', 'calls'), restrictions=(), profile_dir=None, filename_format='{method}.{path}.{elapsed:.0f}ms.{time:.0f}.prof')
Wrap a WSGI application and profile the execution of each request. Responses are buffered so that timings are more exact. If stream is given, pstats.Stats are written to it after each request. If profile_dir is given, cProfile data files are saved to that directory, one file per request. The filename can be customized by passing filename_format. If it is a string, it will be formatted using str.format() with the following fields available:
{method} - The request method; GET, POST, etc.
{path} - The request path or βrootβ should one not exist.
{elapsed} - The elapsed time of the request.
{time} - The time of the request. If it is a callable, it will be called with the WSGI environ dict and should return a filename. Parameters
app (WSGIApplication) β The WSGI application to wrap.
stream (TextIO) β Write stats to this stream. Disable with None.
sort_by (Iterable[str]) β A tuple of columns to sort stats by. See pstats.Stats.sort_stats().
restrictions (Iterable[Union[str, int, float]]) β A tuple of restrictions to filter stats by. See pstats.Stats.print_stats().
profile_dir (Optional[str]) β Save profile data files to this directory.
filename_format (str) β Format string for profile data file names, or a callable returning a name. See explanation above. Return type
None from werkzeug.middleware.profiler import ProfilerMiddleware
app = ProfilerMiddleware(app)
Changelog Changed in version 0.15: Stats are written even if profile_dir is given, and can be disable by passing stream=None. New in version 0.15: Added filename_format. New in version 0.9: Added restrictions and profile_dir. | werkzeug.middleware.profiler.index#werkzeug.middleware.profiler.ProfilerMiddleware |
class werkzeug.middleware.proxy_fix.ProxyFix(app, x_for=1, x_proto=1, x_host=0, x_port=0, x_prefix=0)
Adjust the WSGI environ based on X-Forwarded- that proxies in front of the application may set.
X-Forwarded-For sets REMOTE_ADDR.
X-Forwarded-Proto sets wsgi.url_scheme.
X-Forwarded-Host sets HTTP_HOST, SERVER_NAME, and SERVER_PORT.
X-Forwarded-Port sets HTTP_HOST and SERVER_PORT.
X-Forwarded-Prefix sets SCRIPT_NAME. You must tell the middleware how many proxies set each header so it knows what values to trust. It is a security issue to trust values that came from the client rather than a proxy. The original values of the headers are stored in the WSGI environ as werkzeug.proxy_fix.orig, a dict. Parameters
app (WSGIApplication) β The WSGI application to wrap.
x_for (int) β Number of values to trust for X-Forwarded-For.
x_proto (int) β Number of values to trust for X-Forwarded-Proto.
x_host (int) β Number of values to trust for X-Forwarded-Host.
x_port (int) β Number of values to trust for X-Forwarded-Port.
x_prefix (int) β Number of values to trust for X-Forwarded-Prefix. Return type
None from werkzeug.middleware.proxy_fix import ProxyFix
# App is behind one proxy that sets the -For and -Host headers.
app = ProxyFix(app, x_for=1, x_host=1)
Changelog Changed in version 1.0: Deprecated code has been removed: The num_proxies argument and attribute. The get_remote_addr method. The environ keys orig_remote_addr, orig_wsgi_url_scheme, and orig_http_host. Changed in version 0.15: All headers support multiple values. The num_proxies argument is deprecated. Each header is configured with a separate number of trusted proxies. Changed in version 0.15: Original WSGI environ values are stored in the werkzeug.proxy_fix.orig dict. orig_remote_addr, orig_wsgi_url_scheme, and orig_http_host are deprecated and will be removed in 1.0. Changed in version 0.15: Support X-Forwarded-Port and X-Forwarded-Prefix. Changed in version 0.15: X-Forwarded-Host and X-Forwarded-Port modify SERVER_NAME and SERVER_PORT. | werkzeug.middleware.proxy_fix.index#werkzeug.middleware.proxy_fix.ProxyFix |
class werkzeug.middleware.http_proxy.ProxyMiddleware(app, targets, chunk_size=16384, timeout=10)
Proxy requests under a path to an external server, routing other requests to the app. This middleware can only proxy HTTP requests, as HTTP is the only protocol handled by the WSGI server. Other protocols, such as WebSocket requests, cannot be proxied at this layer. This should only be used for development, in production a real proxy server should be used. The middleware takes a dict mapping a path prefix to a dict describing the host to be proxied to: app = ProxyMiddleware(app, {
"/static/": {
"target": "http://127.0.0.1:5001/",
}
})
Each host has the following options:
target:
The target URL to dispatch to. This is required.
remove_prefix:
Whether to remove the prefix from the URL before dispatching it to the target. The default is False.
host:
"<auto>" (default):
The host header is automatically rewritten to the URL of the target.
None:
The host header is unmodified from the client request. Any other value:
The host header is overwritten with the value.
headers:
A dictionary of headers to be sent with the request to the target. The default is {}.
ssl_context:
A ssl.SSLContext defining how to verify requests if the target is HTTPS. The default is None. In the example above, everything under "/static/" is proxied to the server on port 5001. The host header is rewritten to the target, and the "/static/" prefix is removed from the URLs. Parameters
app (WSGIApplication) β The WSGI application to wrap.
targets (Mapping[str, Dict[str, Any]]) β Proxy target configurations. See description above.
chunk_size (int) β Size of chunks to read from input stream and write to target.
timeout (int) β Seconds before an operation to a target fails. Return type
None Changelog New in version 0.14. | werkzeug.middleware.http_proxy.index#werkzeug.middleware.http_proxy.ProxyMiddleware |
Quickstart This part of the documentation shows how to use the most important parts of Werkzeug. Itβs intended as a starting point for developers with basic understanding of PEP 3333 (WSGI) and RFC 2616 (HTTP). | werkzeug.quickstart.index |
werkzeug.http.quote_etag(etag, weak=False)
Quote an etag. Parameters
etag (str) β the etag to quote.
weak (bool) β set to True to tag it βweakβ. Return type
str | werkzeug.http.index#werkzeug.http.quote_etag |
werkzeug.http.quote_header_value(value, extra_chars='', allow_token=True)
Quote a header value if necessary. Changelog New in version 0.5. Parameters
value (Union[str, int]) β the value to quote.
extra_chars (str) β a list of extra characters to skip quoting.
allow_token (bool) β if this is enabled token values are returned unchanged. Return type
str | werkzeug.http.index#werkzeug.http.quote_header_value |
class werkzeug.datastructures.Range(units, ranges)
Represents a Range header. All methods only support only bytes as the unit. Stores a list of ranges if given, but the methods only work if only one range is provided. Raises
ValueError β If the ranges provided are invalid. Changelog Changed in version 0.15: The ranges passed in are validated. New in version 0.7.
make_content_range(length)
Creates a ContentRange object from the current range and given content length.
range_for_length(length)
If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a (start, stop) tuple, otherwise None.
ranges
A list of (begin, end) tuples for the range header provided. The ranges are non-inclusive.
to_content_range_header(length)
Converts the object into Content-Range HTTP header, based on given length
to_header()
Converts the object back into an HTTP header.
units
The units of this range. Usually βbytesβ. | werkzeug.datastructures.index#werkzeug.datastructures.Range |
make_content_range(length)
Creates a ContentRange object from the current range and given content length. | werkzeug.datastructures.index#werkzeug.datastructures.Range.make_content_range |
ranges
A list of (begin, end) tuples for the range header provided. The ranges are non-inclusive. | werkzeug.datastructures.index#werkzeug.datastructures.Range.ranges |
range_for_length(length)
If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a (start, stop) tuple, otherwise None. | werkzeug.datastructures.index#werkzeug.datastructures.Range.range_for_length |
to_content_range_header(length)
Converts the object into Content-Range HTTP header, based on given length | werkzeug.datastructures.index#werkzeug.datastructures.Range.to_content_range_header |
to_header()
Converts the object back into an HTTP header. | werkzeug.datastructures.index#werkzeug.datastructures.Range.to_header |
units
The units of this range. Usually βbytesβ. | werkzeug.datastructures.index#werkzeug.datastructures.Range.units |
werkzeug.utils.redirect(location, code=302, Response=None)
Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because itβs not a real redirect and 304 because itβs the answer for a request with a request with defined If-Modified-Since headers. Changelog New in version 0.10: The class used for the Response object can now be passed in. New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function. Parameters
location (str) β the location the response should redirect to.
code (int) β the redirect status code. defaults to 302.
Response (class) β a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified. Return type
Response | werkzeug.utils.index#werkzeug.utils.redirect |
werkzeug.local.release_local(local)
Releases the contents of the local for the current context. This makes it possible to use locals without a manager. Example: >>> loc = Local()
>>> loc.foo = 42
>>> release_local(loc)
>>> hasattr(loc, 'foo')
False
With this function one can release Local objects as well as LocalStack objects. However it is not possible to release data held by proxies that way, one always has to retain a reference to the underlying local object in order to be able to release it. Changelog New in version 0.6.1. Parameters
local (Union[werkzeug.local.Local, werkzeug.local.LocalStack]) β Return type
None | werkzeug.local.index#werkzeug.local.release_local |
werkzeug.http.remove_entity_headers(headers, allowed=('expires', 'content-location'))
Remove all entity headers from a list or Headers object. This operation works in-place. Expires and Content-Location headers are by default not removed. The reason for this is RFC 2616 section 10.3.5 which specifies some entity headers that should be sent. Changelog Changed in version 0.5: added allowed parameter. Parameters
headers (Union[werkzeug.datastructures.Headers, List[Tuple[str, str]]]) β a list or Headers object.
allowed (Iterable[str]) β a list of headers that should still be allowed even though they are entity headers. Return type
None | werkzeug.http.index#werkzeug.http.remove_entity_headers |
werkzeug.http.remove_hop_by_hop_headers(headers)
Remove all HTTP/1.1 βHop-by-Hopβ headers from a list or Headers object. This operation works in-place. Changelog New in version 0.5. Parameters
headers (Union[werkzeug.datastructures.Headers, List[Tuple[str, str]]]) β a list or Headers object. Return type
None | werkzeug.http.index#werkzeug.http.remove_hop_by_hop_headers |
class werkzeug.wrappers.Request(environ, populate_request=True, shallow=False)
Represents an incoming WSGI HTTP request, with headers and body taken from the WSGI environment. Has properties and methods for using the functionality defined by various HTTP specs. The data in requests object is read-only. Text data is assumed to use UTF-8 encoding, which should be true for the vast majority of modern clients. Using an encoding set by the client is unsafe in Python due to extra encodings it provides, such as zip. To change the assumed encoding, subclass and replace charset. Parameters
environ (WSGIEnvironment) β The WSGI environ is generated by the WSGI server and contains information about the server configuration and client request.
populate_request (bool) β Add this request object to the WSGI environ as environ['werkzeug.request']. Can be useful when debugging.
shallow (bool) β Makes reading from stream (and any method that would read from it) raise a RuntimeError. Useful to prevent consuming the form data in middleware, which would make it unavailable to the final application. Return type
None Changed in version 2.0: Combine BaseRequest and mixins into a single Request class. Using the old classes is deprecated and will be removed in Werkzeug 2.1. Changelog Changed in version 0.5: Read-only mode is enforced with immutable classes for all data.
_get_file_stream(total_content_length, content_type, filename=None, content_length=None)
Called to get a stream for the file upload. This must provide a file-like class with read(), readline() and seek() methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. Parameters
total_content_length (Optional[int]) β the total content length of all the data in the request combined. This value is guaranteed to be there.
content_type (Optional[str]) β the mimetype of the uploaded file.
filename (Optional[str]) β the filename of the uploaded file. May be None.
content_length (Optional[int]) β the length of this file. This value is usually not provided because webbrowsers do not provide this value. Return type
BinaryIO
property accept_charsets: werkzeug.datastructures.CharsetAccept
List of charsets this client supports as CharsetAccept object.
property accept_encodings: werkzeug.datastructures.Accept
List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset.
property accept_languages: werkzeug.datastructures.LanguageAccept
List of languages this client accepts as LanguageAccept object.
property accept_mimetypes: werkzeug.datastructures.MIMEAccept
List of mimetypes this client supports as MIMEAccept object.
access_control_request_headers
Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.
access_control_request_method
Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.
property access_route: List[str]
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.
classmethod application(f)
Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the request object will be closed automatically: @Request.application
def my_wsgi_app(request):
return Response('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing. Parameters
f (Callable[[Request], WSGIApplication]) β the WSGI callable to decorate Returns
a new WSGI callable Return type
WSGIApplication
property args: MultiDict[str, str]
The parsed URL parameters (the part in the URL after the question mark). By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important.
property authorization: Optional[werkzeug.datastructures.Authorization]
The Authorization object in parsed form.
property base_url: str
Like url but without the query string.
property cache_control: werkzeug.datastructures.RequestCacheControl
A RequestCacheControl object for the incoming cache control headers.
close()
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. Changelog New in version 0.9. Return type
None
content_encoding
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field. Changelog New in version 0.9.
property content_length: Optional[int]
The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
content_md5
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.) Changelog New in version 0.9.
content_type
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
property cookies: ImmutableMultiDict[str, str]
A dict with the contents of all cookies transmitted with the request.
property data: bytes
Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle.
date
The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. Changed in version 2.0: The datetime object is timezone-aware.
dict_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict
disable_data_descriptor: Optional[bool] = None
Disable the data property to avoid reading from the input stream. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Create the request with shallow=True instead. Changelog New in version 0.9.
environ: WSGIEnvironment
The WSGI environment containing HTTP headers and information from the WSGI server.
property files: ImmutableMultiDict[str, FileStorage]
MultiDict object containing all uploaded files. Each key in files is the name from the <input type="file" name="">. Each value in files is a Werkzeug FileStorage object. It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem. Note that files will only contain data if the request method was POST, PUT or PATCH and the <form> that posted to the request had enctype="multipart/form-data". It will be empty otherwise. See the MultiDict / FileStorage documentation for more details about the used data structure.
property form: ImmutableMultiDict[str, str]
The form parameters. By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important. Please keep in mind that file uploads will not end up here, but instead in the files attribute. Changelog Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.
form_data_parser_class
alias of werkzeug.formparser.FormDataParser
classmethod from_values(*args, **kwargs)
Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (Client) that allows to create multipart requests, support for cookies etc. This accepts the same options as the EnvironBuilder. Changelog Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides. Returns
request object Parameters
args (Any) β
kwargs (Any) β Return type
werkzeug.wrappers.request.Request
property full_path: str
Requested path, including the query string.
get_data(cache=True, as_text=False, parse_form_data=False)
This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting cache to False. Usually itβs a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server. Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory. If as_text is set to True the return value will be a decoded string. Changelog New in version 0.9. Parameters
cache (bool) β
as_text (bool) β
parse_form_data (bool) β Return type
Union[bytes, str]
get_json(force=False, silent=False, cache=True)
Parse data as JSON. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. If parsing fails, on_json_loading_failed() is called and its return value is used as the return value. Parameters
force (bool) β Ignore the mimetype and always try to parse JSON.
silent (bool) β Silence parsing errors and return None instead.
cache (bool) β Store the parsed JSON to return for subsequent calls. Return type
Optional[Any]
headers
The headers received with the request.
property host: str
The host name the request was made to, including the port if itβs non-standard. Validated with trusted_hosts.
property host_url: str
The request URL scheme and host only.
property if_match: werkzeug.datastructures.ETags
An object containing all the etags in the If-Match header. Return type
ETags
property if_modified_since: Optional[datetime.datetime]
The parsed If-Modified-Since header as a datetime object. Changed in version 2.0: The datetime object is timezone-aware.
property if_none_match: werkzeug.datastructures.ETags
An object containing all the etags in the If-None-Match header. Return type
ETags
property if_range: werkzeug.datastructures.IfRange
The parsed If-Range header. Changed in version 2.0: IfRange.date is timezone-aware. Changelog New in version 0.7.
property if_unmodified_since: Optional[datetime.datetime]
The parsed If-Unmodified-Since header as a datetime object. Changed in version 2.0: The datetime object is timezone-aware.
input_stream
The WSGI input stream. In general itβs a bad idea to use this one because you can easily read past the boundary. Use the stream instead.
property is_json: bool
Check if the mimetype indicates JSON data, either application/json or application/*+json.
is_multiprocess
boolean that is True if the application is served by a WSGI server that spawns multiple processes.
is_multithread
boolean that is True if the application is served by a multithreaded WSGI server.
is_run_once
boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but itβs not guaranteed that the execution only happens one time.
property is_secure: bool
True if the request was made with a secure protocol (HTTPS or WSS).
property json: Optional[Any]
The parsed JSON data if mimetype indicates JSON (application/json, see is_json()). Calls get_json() with default arguments.
json_module = <module 'json' from '/home/docs/.pyenv/versions/3.7.9/lib/python3.7/json/__init__.py'>
A module or other object that has dumps and loads functions that match the API of the built-in json module.
list_storage_class
alias of werkzeug.datastructures.ImmutableList
make_form_data_parser()
Creates the form data parser. Instantiates the form_data_parser_class with some parameters. Changelog New in version 0.8. Return type
werkzeug.formparser.FormDataParser
max_content_length: Optional[int] = None
the maximum content length. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the parsing fails because more than the specified value is transmitted a RequestEntityTooLarge exception is raised. Have a look at Dealing with Request Data for more details. Changelog New in version 0.5.
max_form_memory_size: Optional[int] = None
the maximum form field size. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the data in memory for post data is longer than the specified value a RequestEntityTooLarge exception is raised. Have a look at Dealing with Request Data for more details. Changelog New in version 0.5.
max_forwards
The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.
method
The method the request was made with, such as GET.
property mimetype: str
Like content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is text/HTML; charset=utf-8 the mimetype would be 'text/html'.
property mimetype_params: Dict[str, str]
The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.
on_json_loading_failed(e)
Called if get_json() parsing fails and isnβt silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest. Parameters
e (ValueError) β Return type
Any
origin
The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.
parameter_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict
path
The path part of the URL after root_path. This is the path used for routing within the application.
property pragma: werkzeug.datastructures.HeaderSet
The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives.
query_string
The part of the URL after the β?β. This is the raw value, use args for the parsed values.
property range: Optional[werkzeug.datastructures.Range]
The parsed Range header. Changelog New in version 0.7. Return type
Range
referrer
The Referer[sic] request-header field allows the client to specify, for the serverβs benefit, the address (URI) of the resource from which the Request-URI was obtained (the βreferrerβ, although the header field is misspelled).
remote_addr
The address of the client sending the request.
remote_user
If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.
root_path
The prefix that the application is mounted under, without a trailing slash. path comes after this.
property root_url: str
The request URL scheme, host, and root path. This is the root that the application is accessed from.
scheme
The URL scheme of the protocol the request used, such as https or wss.
property script_root: str
Alias for self.root_path. environ["SCRIPT_ROOT"] without a trailing slash.
server
The address of the server. (host, port), (path, None) for unix sockets, or None if not known.
shallow: bool
Set when creating the request object. If True, reading from the request body will cause a RuntimeException. Useful to prevent modifying the stream from middleware.
property stream: BinaryIO
If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use data which will give you that data as a string. The stream only returns the data once. Unlike input_stream this stream is properly guarded that you canβt accidentally read past the length of the input. Werkzeug will internally always refer to this stream to read data which makes it possible to wrap this object with a stream that does filtering. Changelog Changed in version 0.9: This stream is now always available but might be consumed by the form parser later on. Previously the stream was only set if no parsing happened.
property url: str
The full request URL with the scheme, host, root path, path, and query string.
property url_charset: str
The charset that is assumed for URLs. Defaults to the value of charset. Changelog New in version 0.6.
property url_root: str
Alias for root_url. The URL with scheme, host, and root path. For example, https://example.com/app/.
property user_agent: werkzeug.user_agent.UserAgent
The user agent. Use user_agent.string to get the header value. Set user_agent_class to a subclass of UserAgent to provide parsing for the other properties or other extended data. Changed in version 2.0: The built in parser is deprecated and will be removed in Werkzeug 2.1. A UserAgent subclass must be set to parse data from the string.
user_agent_class
alias of werkzeug.useragents._UserAgent
property values: CombinedMultiDict[str, str]
A werkzeug.datastructures.CombinedMultiDict that combines args and form. For GET requests, only args are present, not form. Changed in version 2.0: For GET requests, only args are present, not form.
property want_form_data_parsed: bool
True if the request method carries content. By default this is true if a Content-Type is sent. Changelog New in version 0.8. | werkzeug.wrappers.index#werkzeug.wrappers.Request |
access_control_request_headers
Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed. | werkzeug.wrappers.index#werkzeug.wrappers.Request.access_control_request_headers |
access_control_request_method
Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed. | werkzeug.wrappers.index#werkzeug.wrappers.Request.access_control_request_method |
classmethod application(f)
Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the request object will be closed automatically: @Request.application
def my_wsgi_app(request):
return Response('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing. Parameters
f (Callable[[Request], WSGIApplication]) β the WSGI callable to decorate Returns
a new WSGI callable Return type
WSGIApplication | werkzeug.wrappers.index#werkzeug.wrappers.Request.application |
close()
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. Changelog New in version 0.9. Return type
None | werkzeug.wrappers.index#werkzeug.wrappers.Request.close |
content_encoding
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field. Changelog New in version 0.9. | werkzeug.wrappers.index#werkzeug.wrappers.Request.content_encoding |
content_md5
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.) Changelog New in version 0.9. | werkzeug.wrappers.index#werkzeug.wrappers.Request.content_md5 |
content_type
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. | werkzeug.wrappers.index#werkzeug.wrappers.Request.content_type |
date
The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. Changed in version 2.0: The datetime object is timezone-aware. | werkzeug.wrappers.index#werkzeug.wrappers.Request.date |
dict_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict | werkzeug.wrappers.index#werkzeug.wrappers.Request.dict_storage_class |
disable_data_descriptor: Optional[bool] = None
Disable the data property to avoid reading from the input stream. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Create the request with shallow=True instead. Changelog New in version 0.9. | werkzeug.wrappers.index#werkzeug.wrappers.Request.disable_data_descriptor |
environ: WSGIEnvironment
The WSGI environment containing HTTP headers and information from the WSGI server. | werkzeug.wrappers.index#werkzeug.wrappers.Request.environ |
form_data_parser_class
alias of werkzeug.formparser.FormDataParser | werkzeug.wrappers.index#werkzeug.wrappers.Request.form_data_parser_class |
classmethod from_values(*args, **kwargs)
Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (Client) that allows to create multipart requests, support for cookies etc. This accepts the same options as the EnvironBuilder. Changelog Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides. Returns
request object Parameters
args (Any) β
kwargs (Any) β Return type
werkzeug.wrappers.request.Request | werkzeug.wrappers.index#werkzeug.wrappers.Request.from_values |
get_data(cache=True, as_text=False, parse_form_data=False)
This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting cache to False. Usually itβs a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server. Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory. If as_text is set to True the return value will be a decoded string. Changelog New in version 0.9. Parameters
cache (bool) β
as_text (bool) β
parse_form_data (bool) β Return type
Union[bytes, str] | werkzeug.wrappers.index#werkzeug.wrappers.Request.get_data |
get_json(force=False, silent=False, cache=True)
Parse data as JSON. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. If parsing fails, on_json_loading_failed() is called and its return value is used as the return value. Parameters
force (bool) β Ignore the mimetype and always try to parse JSON.
silent (bool) β Silence parsing errors and return None instead.
cache (bool) β Store the parsed JSON to return for subsequent calls. Return type
Optional[Any] | werkzeug.wrappers.index#werkzeug.wrappers.Request.get_json |
headers
The headers received with the request. | werkzeug.wrappers.index#werkzeug.wrappers.Request.headers |
input_stream
The WSGI input stream. In general itβs a bad idea to use this one because you can easily read past the boundary. Use the stream instead. | werkzeug.wrappers.index#werkzeug.wrappers.Request.input_stream |
is_multiprocess
boolean that is True if the application is served by a WSGI server that spawns multiple processes. | werkzeug.wrappers.index#werkzeug.wrappers.Request.is_multiprocess |
is_multithread
boolean that is True if the application is served by a multithreaded WSGI server. | werkzeug.wrappers.index#werkzeug.wrappers.Request.is_multithread |
is_run_once
boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but itβs not guaranteed that the execution only happens one time. | werkzeug.wrappers.index#werkzeug.wrappers.Request.is_run_once |
json_module = <module 'json' from '/home/docs/.pyenv/versions/3.7.9/lib/python3.7/json/__init__.py'>
A module or other object that has dumps and loads functions that match the API of the built-in json module. | werkzeug.wrappers.index#werkzeug.wrappers.Request.json_module |
list_storage_class
alias of werkzeug.datastructures.ImmutableList | werkzeug.wrappers.index#werkzeug.wrappers.Request.list_storage_class |
make_form_data_parser()
Creates the form data parser. Instantiates the form_data_parser_class with some parameters. Changelog New in version 0.8. Return type
werkzeug.formparser.FormDataParser | werkzeug.wrappers.index#werkzeug.wrappers.Request.make_form_data_parser |
max_content_length: Optional[int] = None
the maximum content length. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the parsing fails because more than the specified value is transmitted a RequestEntityTooLarge exception is raised. Have a look at Dealing with Request Data for more details. Changelog New in version 0.5. | werkzeug.wrappers.index#werkzeug.wrappers.Request.max_content_length |
max_form_memory_size: Optional[int] = None
the maximum form field size. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the data in memory for post data is longer than the specified value a RequestEntityTooLarge exception is raised. Have a look at Dealing with Request Data for more details. Changelog New in version 0.5. | werkzeug.wrappers.index#werkzeug.wrappers.Request.max_form_memory_size |
max_forwards
The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server. | werkzeug.wrappers.index#werkzeug.wrappers.Request.max_forwards |
method
The method the request was made with, such as GET. | werkzeug.wrappers.index#werkzeug.wrappers.Request.method |
on_json_loading_failed(e)
Called if get_json() parsing fails and isnβt silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest. Parameters
e (ValueError) β Return type
Any | werkzeug.wrappers.index#werkzeug.wrappers.Request.on_json_loading_failed |
origin
The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed. | werkzeug.wrappers.index#werkzeug.wrappers.Request.origin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.