Data Structures

2018-02-24 15:39 更新

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 theFileMultiDict won't be pickleable as soon as it contains afile.

class werkzeug.datastructures.TypeConversionDict
Works like a regular dict but the get() method can performtype conversions. MultiDict and CombinedMultiDictare 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] 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
參數(shù):
  • key – The key to be looked up.
  • default – The default value to be returned if the key can'tbe looked up. If not further specified None isreturned.
  • type – A callable that is used to cast the value in theMultiDict. If a ValueError [http://docs.python.org/dev/library/exceptions.html#ValueError] is raisedby this callable the default value is returned.

class werkzeug.datastructures.ImmutableTypeConversionDict
Works like a TypeConversionDict but does not supportmodifications.

0.5 新版功能.

copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's 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]).

class werkzeug.datastructures.MultiDict(mapping=None)
A 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 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 can be constructed from an iterable of(key,value) tuples, a dict, a MultiDict or from Werkzeug 0.2onwards some keyword parameters.

add(key, value)
Adds a new value for the key.

0.6 新版功能.

參數(shù):
  • 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.

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] 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
參數(shù):
  • key – The key to be looked up.
  • default – The default value to be returned if the key can'tbe looked up. If not further specified None isreturned.
  • type – A callable that is used to cast the value in theMultiDict. If a ValueError [http://docs.python.org/dev/library/exceptions.html#ValueError] is raisedby 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 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.

參數(shù):
  • key – The key to be looked up.
  • type – A callable that is used to cast the value in theMultiDict. If a ValueError [http://docs.python.org/dev/library/exceptions.html#ValueError] is raisedby this callable the value will be removed from the list.
返回:

a list [http://docs.python.org/dev/library/stdtypes.html#list] of all the values for the key.

has_key(k) → True if D has a key k, else Falseitems(a, kw*)
Like iteritems(), but returns a list.

iteritems(multi=False)
Return an iterator of (key,value) pairs.

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. Zippingkeys() and this is the same as calling 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(), but returns a list.

listvalues(a, kw*)
Like 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
參數(shù):
  • key – the key to pop.
  • default – if provided the value to return if the key wasnot 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 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.

參數(shù):
  • key – The key to be looked up.
  • default – The default value to be returned if the key is notin 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 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']
參數(shù):
  • key – The key for which the values are set.
  • new_list – An iterable with the new values for the key. Old valuesare removed first.

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]
參數(shù):
  • key – The key to be looked up.
  • default – An iterable of default values. It is either copied(in case it was a list) or converted into a listbefore returned.
返回:

a list [http://docs.python.org/dev/library/stdtypes.html#list]

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.

參數(shù): 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]

update(other_dict)
update() extends rather than replaces existing key lists.

values(a, kw*)
Like 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 valuesclass werkzeug.datastructures.OrderedMultiDict(mapping=None)
Works like a regular 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 is an order of magnitudeslower than a 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.

0.5 新版功能.

copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's 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]).

class werkzeug.datastructures.ImmutableOrderedMultiDict(mapping=None)
An immutable OrderedMultiDict.

0.6 新版功能.

copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's 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]).

class werkzeug.datastructures.CombinedMultiDict(dicts=None)
A read only MultiDict that you can pass multiple MultiDictinstances 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].

0.5 新版功能.

copy()
Return a shallow mutable copy of this object. Keep in mind thatthe standard library's 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]).

class werkzeug.datastructures.ImmutableList
An immutable list [http://docs.python.org/dev/library/stdtypes.html#list].

0.5 新版功能.

class werkzeug.datastructures.FileMultiDict(mapping=None)
A special 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 object.

參數(shù):
  • name – the name of the field.
  • file – a filename or file-like object
  • filename – an optional filename
  • content_type – an optional content type

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] 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]class, with the exception of getitem. wsgiref [http://docs.python.org/dev/library/wsgiref.html#module-wsgiref] will returnNone for headers['missing'], whereas Headers will raisea KeyError [http://docs.python.org/dev/library/exceptions.html#KeyError].

To create a new 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.

在 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] compatibility.

add_header(_key, _value, **_kw)
Add a new header tuple to the list.

An alias for add() for compatibility with the wsgiref [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] 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.

參數(shù):
  • key – The key to be looked up.
  • default – The default value to be returned if the key can'tbe looked up. If not further specified None isreturned.
  • type – A callable that is used to cast the value in theHeaders. If a ValueError [http://docs.python.org/dev/library/exceptions.html#ValueError] is raisedby this callable the default value is returned.
  • as_bytes – return bytes instead of unicode strings.

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][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 theHeaders, the return value will be an empty list. Just asget()getlist() accepts a type parameter. All items willbe converted with the callable defined there.

0.9 新版功能: Added support for as_bytes.

參數(shù):
  • key – The key to be looked up.
  • type – A callable that is used to cast the value in theHeaders. If a ValueError [http://docs.python.org/dev/library/exceptions.html#ValueError] is raisedby this callable the value will be removed from the list.
  • as_bytes – return bytes instead of unicode strings.
返回:

a list [http://docs.python.org/dev/library/stdtypes.html#list] of all the values for the key.

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.

參數(shù): 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.

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() formore information.

在 0.6.1 版更改: set() now accepts the same arguments as add().

參數(shù):
  • key – The key to be inserted.
  • value – The value to be inserted.

setdefault(key, value)
Returns the value for the key if it is in the dict, otherwise itreturns default and sets that value for key.

參數(shù):
  • key – The key to be looked up.
  • default – The default value to be returned if the key is notin the dict. If not further specified it's None.

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.

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 class this implements a set-like structure.Unlike 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.

clear()
Clear the set.

discard(header)
Like remove() but ignores errors.

find(header)
Return the index of the header in the set or return -1 if not found.

index(header)
Return the index of the header in the set or raise anIndexError

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號