Data Structures
最后更新于:2022-04-01 04:07:30
# Data Structures
Werkzeug provides some subclasses of common Python objects to extend themwith additional features. Some of them are used to make them immutable, othersare used to change some semantics to better work with HTTP.
### General Purpose
在 0.6 版更改: The general purpose classes are now pickleable in each protocol as longas the contained objects are pickleable. This means that the[FileMultiDict](# "werkzeug.datastructures.FileMultiDict") won't be pickleable as soon as it contains afile.
*class *werkzeug.datastructures.TypeConversionDict
Works like a regular dict but the [get()](# "werkzeug.datastructures.TypeConversionDict.get") method can performtype conversions. [MultiDict](# "werkzeug.datastructures.MultiDict") and [CombinedMultiDict](# "werkzeug.datastructures.CombinedMultiDict")are subclasses of this class and provide the same feature.
0.5 新版功能.
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](http://docs.python.org/dev/library/exceptions.html#ValueError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#ValueError] if that is not possible. Inthis case the function will return the default as if the value was notfound:
~~~
>>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>default</strong> – The default value to be returned if the key can'tbe looked up. If not further specified <cite>None</cite> isreturned.</li><li><strong>type</strong> – A callable that is used to cast the value in the<a class="reference internal" href="#werkzeug.datastructures.MultiDict" title="werkzeug.datastructures.MultiDict"><tt class="xref py py-class docutils literal"><span class="pre">MultiDict</span></tt></a>. If a <a class="reference external" href="http://docs.python.org/dev/library/exceptions.html#ValueError" title="(在 Python v3.5)"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/exceptions.html#ValueError]</span> is raisedby this callable the default value is returned.</li></ul></td></tr></tbody></table>
*class *werkzeug.datastructures.ImmutableTypeConversionDict
Works like a [TypeConversionDict](# "werkzeug.datastructures.TypeConversionDict") but does not supportmodifications.
0.5 新版功能.
copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's [copy()](# "werkzeug.datastructures.ImmutableTypeConversionDict.copy") function is a no-op for this classlike for any other python immutable type (eg: [tuple](http://docs.python.org/dev/library/stdtypes.html#tuple "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#tuple]).
*class *werkzeug.datastructures.MultiDict(*mapping=None*)
A [MultiDict](# "werkzeug.datastructures.MultiDict") is a dictionary subclass customized to deal withmultiple values for the same key which is for example used by the parsingfunctions in the wrappers. This is necessary because some HTML formelements pass multiple values for the same key.
[MultiDict](# "werkzeug.datastructures.MultiDict") implements all standard dictionary methods.Internally, it saves all values for a key as a list, but the standard dictaccess methods will only return the first value for a key. If you want togain access to the other values, too, you have to use the list methods asexplained 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 thefirst value when multiple values for one key are found.
From Werkzeug 0.3 onwards, the KeyError raised by this class is also asubclass of the BadRequest HTTP exception and willrender a page for a 400BADREQUEST if caught in a catch-all for HTTPexceptions.
A [MultiDict](# "werkzeug.datastructures.MultiDict") can be constructed from an iterable of(key,value) tuples, a dict, a [MultiDict](# "werkzeug.datastructures.MultiDict") or from Werkzeug 0.2onwards some keyword parameters.
| 参数: | **mapping** – the initial value for the [MultiDict](# "werkzeug.datastructures.MultiDict"). Either aregular dict, an iterable of (key,value) tuplesor None. |
|-----|-----|
add(*key*, *value*)
Adds a new value for the key.
0.6 新版功能.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key for the value.</li><li><strong>value</strong> – the value to add.</li></ul></td></tr></tbody></table>
clear() → None. Remove all items from D.copy()
Return a shallow copy of this object.
*static *fromkeys(*S*[, *v*]) → New dict with keys from S and values equal to v.
v defaults to None.
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](http://docs.python.org/dev/library/exceptions.html#ValueError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#ValueError] if that is not possible. Inthis case the function will return the default as if the value was notfound:
~~~
>>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>default</strong> – The default value to be returned if the key can'tbe looked up. If not further specified <cite>None</cite> isreturned.</li><li><strong>type</strong> – A callable that is used to cast the value in the<a class="reference internal" href="#werkzeug.datastructures.MultiDict" title="werkzeug.datastructures.MultiDict"><tt class="xref py py-class docutils literal"><span class="pre">MultiDict</span></tt></a>. If a <a class="reference external" href="http://docs.python.org/dev/library/exceptions.html#ValueError" title="(在 Python v3.5)"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/exceptions.html#ValueError]</span> is raisedby this callable the default value is returned.</li></ul></td></tr></tbody></table>
getlist(*key*, *type=None*)
Return the list of items for a given key. If that key is not in theMultiDict, the return value will be an empty list. Just as getgetlist accepts a type parameter. All items will be convertedwith the callable defined there.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>type</strong> – A callable that is used to cast the value in the<a class="reference internal" href="#werkzeug.datastructures.MultiDict" title="werkzeug.datastructures.MultiDict"><tt class="xref py py-class docutils literal"><span class="pre">MultiDict</span></tt></a>. If a <a class="reference external" href="http://docs.python.org/dev/library/exceptions.html#ValueError" title="(在 Python v3.5)"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/exceptions.html#ValueError]</span> is raisedby this callable the value will be removed from the list.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">a <a class="reference external" href="http://docs.python.org/dev/library/stdtypes.html#list" title="(在 Python v3.5)"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/stdtypes.html#list]</span> of all the values for the key.</p></td></tr></tbody></table>
has_key(*k*) → True if D has a key k, else Falseitems(**a*, ***kw*)
Like [iteritems()](# "werkzeug.datastructures.MultiDict.iteritems"), but returns a list.
iteritems(*multi=False*)
Return an iterator of (key,value) pairs.
| 参数: | **multi** – If set to True the iterator returned will have a pairfor each value of each key. Otherwise it will onlycontain pairs for the first value of each key. |
|-----|-----|
iterlists()
Return a list of (key,values) pairs, where values is the listof all values associated with the key.
iterlistvalues()
Return an iterator of all values associated with a key. Zipping[keys()](# "werkzeug.datastructures.MultiDict.keys") and this is the same as calling [lists()](# "werkzeug.datastructures.MultiDict.lists"):
~~~
>>> d = MultiDict({"foo": [1, 2, 3]})
>>> zip(d.keys(), d.listvalues()) == d.lists()
True
~~~
itervalues()
Returns an iterator of the first value on every key's value list.
keys(**a*, ***kw*)
Like iterkeys(), but returns a list.
lists(**a*, ***kw*)
Like [iterlists()](# "werkzeug.datastructures.MultiDict.iterlists"), but returns a list.
listvalues(**a*, ***kw*)
Like [iterlistvalues()](# "werkzeug.datastructures.MultiDict.iterlistvalues"), but returns a list.
pop(*key*, *default=no value*)
Pop the first item for a list on the dict. Afterwards thekey is removed from the dict, so additional values are discarded:
~~~
>>> d = MultiDict({"foo": [1, 2, 3]})
>>> d.pop("foo")
1
>>> "foo" in d
False
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key to pop.</li><li><strong>default</strong> – if provided the value to return if the key wasnot in the dictionary.</li></ul></td></tr></tbody></table>
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 dictan empty list is returned.
在 0.5 版更改: If the key does no longer exist a list is returned instead ofraising an error.
setdefault(*key*, *default=None*)
Returns the value for the key if it is in the dict, otherwise itreturns default and sets that value for key.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>default</strong> – The default value to be returned if the key is notin the dict. If not further specified it's <cite>None</cite>.</li></ul></td></tr></tbody></table>
setlist(*key*, *new_list*)
Remove the old values for a key and add new ones. Note that the listyou pass the values in will be shallow-copied before it is inserted inthe dictionary.
~~~
>>> d = MultiDict()
>>> d.setlist('foo', ['1', '2'])
>>> d['foo']
'1'
>>> d.getlist('foo')
['1', '2']
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – The key for which the values are set.</li><li><strong>new_list</strong> – An iterable with the new values for the key. Old valuesare removed first.</li></ul></td></tr></tbody></table>
setlistdefault(*key*, *default_list=None*)
Like setdefault but sets multiple values. The list returnedis not a copy, but the list that is actually used internally. Thismeans that you can put new values into the dict by appending itemsto the list:
~~~
>>> d = MultiDict({"foo": 1})
>>> d.setlistdefault("foo").extend([2, 3])
>>> d.getlist("foo")
[1, 2, 3]
~~~
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>default</strong> – An iterable of default values. It is either copied(in case it was a list) or converted into a listbefore returned.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">a <a class="reference external" href="http://docs.python.org/dev/library/stdtypes.html#list" title="(在 Python v3.5)"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/stdtypes.html#list]</span></p></td></tr></tbody></table>
to_dict(*flat=True*)
Return the contents as regular dict. If flat is True thereturned dict will only have the first item present, if flat isFalse all values will be returned as lists.
| 参数: | **flat** – If set to False the dict returned will have listswith all the values in it. Otherwise it will onlycontain the first value for each key. |
|-----|-----|
| 返回: | a [dict](http://docs.python.org/dev/library/stdtypes.html#dict "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#dict] |
update(*other_dict*)
update() extends rather than replaces existing key lists.
values(**a*, ***kw*)
Like [itervalues()](# "werkzeug.datastructures.MultiDict.itervalues"), but returns a list.
viewitems() → a set-like object providing a view on D's itemsviewkeys() → a set-like object providing a view on D's keysviewvalues() → an object providing a view on D's values*class *werkzeug.datastructures.OrderedMultiDict(*mapping=None*)
Works like a regular [MultiDict](# "werkzeug.datastructures.MultiDict") but preserves theorder of the fields. To convert the ordered multi dict into alist you can use the items() method and pass it multi=True.
In general an [OrderedMultiDict](# "werkzeug.datastructures.OrderedMultiDict") is an order of magnitudeslower than a [MultiDict](# "werkzeug.datastructures.MultiDict").
note
Due to a limitation in Python you cannot convert an orderedmulti dict into a regular dict by using dict(multidict).Instead you have to use the to_dict() method, otherwisethe internal bucket objects are exposed.
*class *werkzeug.datastructures.ImmutableMultiDict(*mapping=None*)
An immutable [MultiDict](# "werkzeug.datastructures.MultiDict").
0.5 新版功能.
copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's [copy()](# "werkzeug.datastructures.ImmutableMultiDict.copy") function is a no-op for this classlike for any other python immutable type (eg: [tuple](http://docs.python.org/dev/library/stdtypes.html#tuple "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#tuple]).
*class *werkzeug.datastructures.ImmutableOrderedMultiDict(*mapping=None*)
An immutable [OrderedMultiDict](# "werkzeug.datastructures.OrderedMultiDict").
0.6 新版功能.
copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's [copy()](# "werkzeug.datastructures.ImmutableOrderedMultiDict.copy") function is a no-op for this classlike for any other python immutable type (eg: [tuple](http://docs.python.org/dev/library/stdtypes.html#tuple "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#tuple]).
*class *werkzeug.datastructures.CombinedMultiDict(*dicts=None*)
A read only [MultiDict](# "werkzeug.datastructures.MultiDict") that you can pass multiple [MultiDict](# "werkzeug.datastructures.MultiDict")instances as sequence and it will combine the return values of all wrappeddicts:
~~~
>>> from werkzeug.datastructures import CombinedMultiDict, MultiDict
>>> post = MultiDict([('foo', 'bar')])
>>> get = MultiDict([('blub', 'blah')])
>>> combined = CombinedMultiDict([get, post])
>>> combined['foo']
'bar'
>>> combined['blub']
'blah'
~~~
This works for all read operations and will raise a TypeError formethods that usually change data which isn't possible.
From Werkzeug 0.3 onwards, the KeyError raised by this class is also asubclass of the BadRequest HTTP exception and willrender a page for a 400BADREQUEST if caught in a catch-all for HTTPexceptions.
*class *werkzeug.datastructures.ImmutableDict
An immutable [dict](http://docs.python.org/dev/library/stdtypes.html#dict "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#dict].
0.5 新版功能.
copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's [copy()](# "werkzeug.datastructures.ImmutableDict.copy") function is a no-op for this classlike for any other python immutable type (eg: [tuple](http://docs.python.org/dev/library/stdtypes.html#tuple "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#tuple]).
*class *werkzeug.datastructures.ImmutableList
An immutable [list](http://docs.python.org/dev/library/stdtypes.html#list "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#list].
0.5 新版功能.
| Private: | |
|-----|-----|
*class *werkzeug.datastructures.FileMultiDict(*mapping=None*)
A special [MultiDict](# "werkzeug.datastructures.MultiDict") that has convenience methods to addfiles to it. This is used for EnvironBuilder and generallyuseful for unittesting.
0.5 新版功能.
add_file(*name*, *file*, *filename=None*, *content_type=None*)
Adds a new file to the dict. file can be a file name ora file-like or a [FileStorage](# "werkzeug.datastructures.FileStorage") object.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>name</strong> – the name of the field.</li><li><strong>file</strong> – a filename or <tt class="xref py py-class docutils literal"><span class="pre">file</span></tt>-like object</li><li><strong>filename</strong> – an optional filename</li><li><strong>content_type</strong> – an optional content type</li></ul></td></tr></tbody></table>
### HTTP Related
*class *werkzeug.datastructures.Headers([*defaults*])
An object that stores some headers. It has a dict-like interfacebut is ordered and can store the same keys multiple times.
This data structure is useful if you want a nicer way to handle WSGIheaders which are stored as tuples in a list.
From Werkzeug 0.3 onwards, the [KeyError](http://docs.python.org/dev/library/exceptions.html#KeyError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#KeyError] raised by this class isalso a subclass of the BadRequest HTTP exceptionand will render a page for a 400BADREQUEST if caught in acatch-all for HTTP exceptions.
Headers is mostly compatible with the Python [wsgiref.headers.Headers](http://docs.python.org/dev/library/wsgiref.html#wsgiref.headers.Headers "(在 Python v3.5)") [http://docs.python.org/dev/library/wsgiref.html#wsgiref.headers.Headers]class, with the exception of __getitem__. [wsgiref](http://docs.python.org/dev/library/wsgiref.html#module-wsgiref "(在 Python v3.5)") [http://docs.python.org/dev/library/wsgiref.html#module-wsgiref] will returnNone for headers['missing'], whereas [Headers](# "werkzeug.datastructures.Headers") will raisea [KeyError](http://docs.python.org/dev/library/exceptions.html#KeyError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#KeyError].
To create a new [Headers](# "werkzeug.datastructures.Headers") object pass it a list or dict of headerswhich are used as default values. This does not reuse the list passedto the constructor for internal usage.
| 参数: | **defaults** – The list of default values for the [Headers](# "werkzeug.datastructures.Headers"). |
|-----|-----|
在 0.9 版更改: This data structure now stores unicode values similar to how themulti dicts do it. The main difference is that bytes can be set aswell which will automatically be latin1 decoded.
在 0.9 版更改: The linked() function was removed without replacement as itwas an API that does not support the changes to the encoding model.
add(*_key*, *_value*, ***kw*)
Add a new header tuple to the list.
Keyword arguments can specify additional parameters for the headervalue, with underscores converted to dashes:
~~~
>>> d = Headers()
>>> d.add('Content-Type', 'text/plain')
>>> d.add('Content-Disposition', 'attachment', filename='foo.png')
~~~
The keyword argument dumping uses dump_options_header()behind the scenes.
0.4.1 新版功能: keyword arguments were added for [wsgiref](http://docs.python.org/dev/library/wsgiref.html#module-wsgiref "(在 Python v3.5)") [http://docs.python.org/dev/library/wsgiref.html#module-wsgiref] compatibility.
add_header(*_key*, *_value*, ***_kw*)
Add a new header tuple to the list.
An alias for [add()](# "werkzeug.datastructures.Headers.add") for compatibility with the [wsgiref](http://docs.python.org/dev/library/wsgiref.html#module-wsgiref "(在 Python v3.5)") [http://docs.python.org/dev/library/wsgiref.html#module-wsgiref][add_header()](http://docs.python.org/dev/library/wsgiref.html#wsgiref.headers.Headers.add_header "(在 Python v3.5)") [http://docs.python.org/dev/library/wsgiref.html#wsgiref.headers.Headers.add_header] method.
clear()
Clears all headers.
extend(*iterable*)
Extend the headers with a dict or an iterable yielding keys andvalues.
get(*key*, *default=None*, *type=None*, *as_bytes=False*)
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](http://docs.python.org/dev/library/exceptions.html#ValueError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#ValueError] if that is not possible. Inthis case the function will return the default as if the value was notfound:
~~~
>>> d = Headers([('Content-Length', '42')])
>>> d.get('Content-Length', type=int)
42
~~~
If a headers object is bound you must not add unicode stringsbecause no encoding takes place.
0.9 新版功能: Added support for as_bytes.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>default</strong> – The default value to be returned if the key can'tbe looked up. If not further specified <cite>None</cite> isreturned.</li><li><strong>type</strong> – A callable that is used to cast the value in the<a class="reference internal" href="#werkzeug.datastructures.Headers" title="werkzeug.datastructures.Headers"><tt class="xref py py-class docutils literal"><span class="pre">Headers</span></tt></a>. If a <a class="reference external" href="http://docs.python.org/dev/library/exceptions.html#ValueError" title="(在 Python v3.5)"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/exceptions.html#ValueError]</span> is raisedby this callable the default value is returned.</li><li><strong>as_bytes</strong> – return bytes instead of unicode strings.</li></ul></td></tr></tbody></table>
get_all(*name*)
Return a list of all the values for the named field.
This method is compatible with the [wsgiref](http://docs.python.org/dev/library/wsgiref.html#module-wsgiref "(在 Python v3.5)") [http://docs.python.org/dev/library/wsgiref.html#module-wsgiref][get_all()](http://docs.python.org/dev/library/wsgiref.html#wsgiref.headers.Headers.get_all "(在 Python v3.5)") [http://docs.python.org/dev/library/wsgiref.html#wsgiref.headers.Headers.get_all] method.
getlist(*key*, *type=None*, *as_bytes=False*)
Return the list of items for a given key. If that key is not in the[Headers](# "werkzeug.datastructures.Headers"), the return value will be an empty list. Just as[get()](# "werkzeug.datastructures.Headers.get")[getlist()](# "werkzeug.datastructures.Headers.getlist") accepts a type parameter. All items willbe converted with the callable defined there.
0.9 新版功能: Added support for as_bytes.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>type</strong> – A callable that is used to cast the value in the<a class="reference internal" href="#werkzeug.datastructures.Headers" title="werkzeug.datastructures.Headers"><tt class="xref py py-class docutils literal"><span class="pre">Headers</span></tt></a>. If a <a class="reference external" href="http://docs.python.org/dev/library/exceptions.html#ValueError" title="(在 Python v3.5)"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/exceptions.html#ValueError]</span> is raisedby this callable the value will be removed from the list.</li><li><strong>as_bytes</strong> – return bytes instead of unicode strings.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">a <a class="reference external" href="http://docs.python.org/dev/library/stdtypes.html#list" title="(在 Python v3.5)"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/stdtypes.html#list]</span> of all the values for the key.</p></td></tr></tbody></table>
has_key(*key*)
Check if a key is present.
items(**a*, ***kw*)
Like iteritems(), but returns a list.
keys(**a*, ***kw*)
Like iterkeys(), but returns a list.
pop(*key=None*, *default=no value*)
Removes and returns a key or index.
| 参数: | **key** – The key to be popped. If this is an integer the item atthat position is removed, if it's a string the value forthat key is. If the key is omitted or None the lastitem is removed. |
|-----|-----|
| 返回: | an item. |
popitem()
Removes a key or index and returns a (key, value) item.
remove(*key*)
Remove a key.
| 参数: | **key** – The key to be removed. |
|-----|-----|
set(*_key*, *_value*, ***kw*)
Remove all header tuples for key and add a new one. The newlyadded key either appears at the end of the list if there was noentry or replaces the first one.
Keyword arguments can specify additional parameters for the headervalue, with underscores converted to dashes. See [add()](# "werkzeug.datastructures.Headers.add") formore information.
在 0.6.1 版更改: [set()](# "werkzeug.datastructures.Headers.set") now accepts the same arguments as [add()](# "werkzeug.datastructures.Headers.add").
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – The key to be inserted.</li><li><strong>value</strong> – The value to be inserted.</li></ul></td></tr></tbody></table>
setdefault(*key*, *value*)
Returns the value for the key if it is in the dict, otherwise itreturns default and sets that value for key.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – The key to be looked up.</li><li><strong>default</strong> – The default value to be returned if the key is notin the dict. If not further specified it's <cite>None</cite>.</li></ul></td></tr></tbody></table>
to_list(*charset='iso-8859-1'*)
Convert the headers into a list suitable for WSGI.
to_wsgi_list()
Convert the headers into a list suitable for WSGI.
The values are byte strings in Python 2 converted to latin1 and unicodestrings in Python 3 for the WSGI server to encode.
| 返回: | list |
|-----|-----|
values(**a*, ***kw*)
Like itervalues(), but returns a list.
*class *werkzeug.datastructures.EnvironHeaders(*environ*)
Read only version of the headers from a WSGI environment. Thisprovides the same interface as Headers and is constructed froma WSGI environment.
From Werkzeug 0.3 onwards, the KeyError raised by this class is also asubclass of the BadRequest HTTP exception and willrender a page for a 400BADREQUEST if caught in a catch-all forHTTP exceptions.
*class *werkzeug.datastructures.HeaderSet(*headers=None*, *on_update=None*)
Similar to the [ETags](# "werkzeug.datastructures.ETags") class this implements a set-like structure.Unlike [ETags](# "werkzeug.datastructures.ETags") this is case insensitive and used for vary, allow, andcontent-language headers.
If not constructed using the parse_set_header() function theinstantiation works like this:
~~~
>>> hs = HeaderSet(['foo', 'bar', 'baz'])
>>> hs
HeaderSet(['foo', 'bar', 'baz'])
~~~
add(*header*)
Add a new header to the set.
as_set(*preserve_casing=False*)
Return the set as real python set type. When calling this, allthe items are converted to lowercase and the ordering is lost.
| 参数: | **preserve_casing** – if set to True the items in the set returnedwill have the original case like in the[HeaderSet](# "werkzeug.datastructures.HeaderSet"), otherwise they willbe lowercase. |
|-----|-----|
clear()
Clear the set.
discard(*header*)
Like [remove()](# "werkzeug.datastructures.HeaderSet.remove") but ignores errors.
| 参数: | **header** – the header to be discarded. |
|-----|-----|
find(*header*)
Return the index of the header in the set or return -1 if not found.
| 参数: | **header** – the header to be looked up. |
|-----|-----|
index(*header*)
Return the index of the header in the set or raise an[IndexError](http://docs.python.org/dev/library/exceptions.html#IndexError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#IndexError].
| 参数: | **header** – the header to be looked up. |
|-----|-----|
remove(*header*)
Remove a header from the set. This raises an [KeyError](http://docs.python.org/dev/library/exceptions.html#KeyError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#KeyError] if theheader is not in the set.
在 0.5 版更改: In older versions a [IndexError](http://docs.python.org/dev/library/exceptions.html#IndexError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#IndexError] was raised instead of a[KeyError](http://docs.python.org/dev/library/exceptions.html#KeyError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#KeyError] if the object was missing.
| 参数: | **header** – the header to be removed. |
|-----|-----|
to_header()
Convert the header set into an HTTP header string.
update(*iterable*)
Add all the headers from the iterable to the set.
| 参数: | **iterable** – updates the set with the items from the iterable. |
|-----|-----|
*class *werkzeug.datastructures.Accept(*values=()*)
An [Accept](# "werkzeug.datastructures.Accept") object is just a list subclass for lists of(value,quality) tuples. It is automatically sorted by quality.
All [Accept](# "werkzeug.datastructures.Accept") objects work similar to a list but provide extrafunctionality for working with the data. Containment checks arenormalized to the rules of that header:
~~~
>>> a = CharsetAccept([('ISO-8859-1', 1), ('utf-8', 0.7)])
>>> a.best
'ISO-8859-1'
>>> 'iso-8859-1' in a
True
>>> 'UTF8' in a
True
>>> 'utf7' in a
False
~~~
To get the quality for an item you can use normal item lookup:
~~~
>>> print a['utf-8']
0.7
>>> a['utf7']
0
~~~
在 0.5 版更改: [Accept](# "werkzeug.datastructures.Accept") objects are forced immutable now.
best
The best match as value.
best_match(*matches*, *default=None*)
Returns the best match from a list of possible matches basedon the quality of the client. If two items have the same quality,the one is returned that comes first.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>matches</strong> – a list of matches to check for</li><li><strong>default</strong> – the value that is returned if none match</li></ul></td></tr></tbody></table>
find(*key*)
Get the position of an entry or return -1.
| 参数: | **key** – The key to be looked up. |
|-----|-----|
index(*key*)
Get the position of an entry or raise [ValueError](http://docs.python.org/dev/library/exceptions.html#ValueError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#ValueError].
| 参数: | **key** – The key to be looked up. |
|-----|-----|
在 0.5 版更改: This used to raise [IndexError](http://docs.python.org/dev/library/exceptions.html#IndexError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#IndexError], which was inconsistentwith the list API.
itervalues()
Iterate over all values.
quality(*key*)
Returns the quality of the key.
0.6 新版功能: In previous versions you had to use the item-lookup syntax(eg: obj[key] instead of obj.quality(key))
to_header()
Convert the header set into an HTTP header string.
values(**a*, ***kw*)
Like [itervalues()](# "werkzeug.datastructures.Accept.itervalues"), but returns a list.
*class *werkzeug.datastructures.MIMEAccept(*values=()*)
Like [Accept](# "werkzeug.datastructures.Accept") but with special methods and behavior formimetypes.
accept_html
True if this object accepts HTML.
accept_json
True if this object accepts JSON.
accept_xhtml
True if this object accepts XHTML.
*class *werkzeug.datastructures.CharsetAccept(*values=()*)
Like [Accept](# "werkzeug.datastructures.Accept") but with normalization for charsets.
*class *werkzeug.datastructures.LanguageAccept(*values=()*)
Like [Accept](# "werkzeug.datastructures.Accept") but with normalization for languages.
*class *werkzeug.datastructures.RequestCacheControl(*values=()*, *on_update=None*)
A cache control for requests. This is immutable and gives accessto all the request-relevant cache control headers.
To get a header of the [RequestCacheControl](# "werkzeug.datastructures.RequestCacheControl") object again you canconvert the object into a string or call the to_header() method. Ifyou plan to subclass it and add your own items have a look at the sourcecodefor that class.
0.5 新版功能: In previous versions a CacheControl class existed that was usedboth for request and response.
no_cache
accessor for ‘no-cache'
no_store
accessor for ‘no-store'
max_age
accessor for ‘max-age'
no_transform
accessor for ‘no-transform'
max_stale
accessor for ‘max-stale'
min_fresh
accessor for ‘min-fresh'
no_transform
accessor for ‘no-transform'
only_if_cached
accessor for ‘only-if-cached'
*class *werkzeug.datastructures.ResponseCacheControl(*values=()*, *on_update=None*)
A cache control for responses. Unlike [RequestCacheControl](# "werkzeug.datastructures.RequestCacheControl")this is mutable and gives access to response-relevant cache controlheaders.
To get a header of the [ResponseCacheControl](# "werkzeug.datastructures.ResponseCacheControl") object again you canconvert the object into a string or call the to_header() method. Ifyou plan to subclass it and add your own items have a look at the sourcecodefor that class.
0.5 新版功能: In previous versions a CacheControl class existed that was usedboth for request and response.
no_cache
accessor for ‘no-cache'
no_store
accessor for ‘no-store'
max_age
accessor for ‘max-age'
no_transform
accessor for ‘no-transform'
must_revalidate
accessor for ‘must-revalidate'
private
accessor for ‘private'
proxy_revalidate
accessor for ‘proxy-revalidate'
public
accessor for ‘public'
s_maxage
accessor for ‘s-maxage'
*class *werkzeug.datastructures.ETags(*strong_etags=None*, *weak_etags=None*, *star_tag=False*)
A set that can be used to check if one etag is present in a collectionof etags.
as_set(*include_weak=False*)
Convert the ETags object into a python set. Per default all theweak etags are not part of this set.
contains(*etag*)
Check if an etag is part of the set ignoring weak tags.It is also possible to use the in operator.
contains_raw(*etag*)
When passed a quoted tag it will check if this tag is part of theset. If the tag is weak it is checked against weak and strong tags,otherwise strong only.
contains_weak(*etag*)
Check if an etag is part of the set including weak and strong tags.
is_weak(*etag*)
Check if an etag is weak.
to_header()
Convert the etags set into a HTTP header string.
*class *werkzeug.datastructures.Authorization(*auth_type*, *data=None*)
Represents an Authorization header sent by the client. You shouldnot create this kind of object yourself but use it when it's returned bythe parse_authorization_header function.
This object is a dict subclass and can be altered by setting dict itemsbut it should be considered immutable as it's returned by the client andnot meant for modifications.
在 0.5 版更改: This object became immutable.
cnonce
If the server sent a qop-header in the WWW-Authenticateheader, the client has to provide this value for HTTP digest auth.See the RFC for more details.
nc
The nonce count value transmitted by clients if a qop-header isalso transmitted. HTTP digest auth only.
nonce
The nonce the server sent for digest auth, sent back by the client.A nonce should be unique for every 401 response for HTTP digestauth.
opaque
The opaque header from the server returned unchanged by the client.It is recommended that this string be base64 or hexadecimal data.Digest auth only.
password
When the authentication type is basic this is the passwordtransmitted by the client, else None.
qop
Indicates what “quality of protection” the client has applied tothe message for HTTP digest auth.
realm
This is the server realm sent back for HTTP digest auth.
response
A string of 32 hex digits computed as defined in RFC 2617, whichproves that the user knows a password. Digest auth only.
uri
The URI from Request-URI of the Request-Line; duplicated becauseproxies are allowed to change the Request-Line in transit. HTTPdigest auth only.
username
The username transmitted. This is set for both basic and digestauth all the time.
*class *werkzeug.datastructures.WWWAuthenticate(*auth_type=None*, *values=None*, *on_update=None*)
Provides simple access to WWW-Authenticate headers.
algorithm
A string indicating a pair of algorithms used to produce the digestand a checksum. If this is not present it is assumed to be “MD5”.If the algorithm is not understood, the challenge should be ignored(and a different one used, if there is more than one).
*static *auth_property(*name*, *doc=None*)
A static helper function for subclasses to add extra authenticationsystem properties onto a class:
~~~
class FooAuthenticate(WWWAuthenticate):
special_realm = auth_property('special_realm')
~~~
For more information have a look at the sourcecode to see how theregular properties ([realm](# "werkzeug.datastructures.WWWAuthenticate.realm") etc.) are implemented.
domain
A list of URIs that define the protection space. If a URI is anabsolute path, it is relative to the canonical root URL of theserver being accessed.
nonce
A server-specified data string which should be uniquely generatedeach time a 401 response is made. It is recommended that thisstring be base64 or hexadecimal data.
opaque
A string of data, specified by the server, which should be returnedby the client unchanged in the Authorization header of subsequentrequests with URIs in the same protection space. It is recommendedthat this string be base64 or hexadecimal data.
qop
A set of quality-of-privacy directives such as auth and auth-int.
realm
A string to be displayed to users so they know which username andpassword to use. This string should contain at least the name ofthe host performing the authentication and might additionallyindicate the collection of users who might have access.
set_basic(*realm='authentication required'*)
Clear the auth info and enable basic auth.
set_digest(*realm*, *nonce*, *qop=('auth'*, *)*, *opaque=None*, *algorithm=None*, *stale=False*)
Clear the auth info and enable digest auth.
stale
A flag, indicating that the previous request from the client wasrejected because the nonce value was stale.
to_header()
Convert the stored values into a WWW-Authenticate header.
type
The type of the auth mechanism. HTTP currently specifiesBasic and Digest.
*class *werkzeug.datastructures.IfRange(*etag=None*, *date=None*)
Very simple object that represents the If-Range header in parsedform. It will either have neither a etag or date or one of either butnever both.
0.7 新版功能.
date* = None*
The date in parsed format or None.
etag* = None*
The etag parsed and unquoted. Ranges always operate on strongetags so the weakness information is not necessary.
to_header()
Converts the object back into an HTTP header.
*class *werkzeug.datastructures.Range(*units*, *ranges*)
Represents a range header. All the methods are only supporting bytesas unit. It does store multiple ranges but [range_for_length()](# "werkzeug.datastructures.Range.range_for_length") willonly work if only one range is provided.
0.7 新版功能.
make_content_range(*length*)
Creates a [ContentRange](# "werkzeug.datastructures.ContentRange") objectfrom the current range and given content length.
range_for_length(*length*)
If the range is for bytes, the length is not None and there isexactly one range and it is satisfiable it returns a (start,stop)tuple, otherwise None.
ranges* = None*
A list of (begin,end) tuples for the range header provided.The ranges are non-inclusive.
to_header()
Converts the object back into an HTTP header.
units* = None*
The units of this range. Usually “bytes”.
*class *werkzeug.datastructures.ContentRange(*units*, *start*, *stop*, *length=None*, *on_update=None*)
Represents the content range header.
0.7 新版功能.
length
The length of the range or None.
set(*start*, *stop*, *length=None*, *units='bytes'*)
Simple method to update the ranges.
start
The start point of the range or None.
stop
The stop point of the range (non-inclusive) or None. Can only beNone if also start is None.
units
The units to use, usually “bytes”
unset()
Sets the units to None which indicates that the header shouldno longer be used.
### Others
*class *werkzeug.datastructures.FileStorage(*stream=None*, *filename=None*, *name=None*, *content_type=None*, *content_length=None*, *headers=None*)
The [FileStorage](# "werkzeug.datastructures.FileStorage") class is a thin wrapper over incoming files.It is used by the request object to represent uploaded files. All theattributes of the wrapper stream are proxied by the file storage soit's possible to do storage.read() instead of the long formstorage.stream.read().
stream
The input stream for the uploaded file. This usually points to anopen temporary file.
filename
The filename of the file on the client.
name
The name of the form field.
headers
The multipart headers as [Headers](# "werkzeug.datastructures.Headers") object. This usually containsirrelevant information but in combination with custom multipart requeststhe raw headers might be interesting.
0.6 新版功能.
close()
Close the underlying file if possible.
content_length
The content-length sent in the header. Usually not available
content_type
The content-type sent in the header. Usually not available
mimetype
Like [content_type](# "werkzeug.datastructures.FileStorage.content_type") but without parameters (eg, withoutcharset, type etc.). For example if the contenttype is text/html;charset=utf-8 the mimetype would be'text/html'.
0.7 新版功能.
mimetype_params
The mimetype parameters as dict. For example if the contenttype is text/html;charset=utf-8 the params would be{'charset':'utf-8'}.
0.7 新版功能.
save(*dst*, *buffer_size=16384*)
Save the file to a destination path or file object. If thedestination is a file object you have to close it yourself after thecall. The buffer size is the number of bytes held in memory duringthe copy process. It defaults to 16KB.
For secure file saving also have a look at secure_filename().
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>dst</strong> – a filename or open file object the uploaded fileis saved to.</li><li><strong>buffer_size</strong> – the size of the buffer. This works the same asthe <cite>length</cite> parameter of<a class="reference external" href="http://docs.python.org/dev/library/shutil.html#shutil.copyfileobj" title="(在 Python v3.5)"><tt class="xref py py-func docutils literal"><span class="pre">shutil.copyfileobj()</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/shutil.html#shutil.copyfileobj]</span>.</li></ul></td></tr></tbody></table>