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
Changed in version 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
andCombinedMultiDict
are subclasses of this class and provide the same feature.
New in version 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
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
Parameters:
- **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 the[<code>MultiDict</code>]($7800771996c024cd.md#werkzeug.datastructures.MultiDict). If a [<code>ValueError</code>](https://docs.python.org/3/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.
New in version 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
).
- 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 400 BAD REQUEST
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.
Parameters:mapping – the initial value for the MultiDict
. Either aregular dict, an iterable of (key, value)
tuplesor None.
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.
Return a deep copy of this object.
Create a new dictionary with keys from iterable and values set to value.
- 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. 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
Parameters:
- **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 the[<code>MultiDict</code>]($7800771996c024cd.md#werkzeug.datastructures.MultiDict). If a [<code>ValueError</code>](https://docs.python.org/3/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 get__getlist accepts a type parameter. All items will be convertedwith the callable defined there.
Parameters:
- **key** – The key to be looked up.
- **type** – A callable that is used to cast the value in the[<code>MultiDict</code>]($7800771996c024cd.md#werkzeug.datastructures.MultiDict). If a [<code>ValueError</code>](https://docs.python.org/3/library/exceptions.html#ValueError) is raisedby this callable the value will be removed from the list.Returns:
a list
of all the values for the key.
Parameters: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.
keys
() → a set-like object providing a view on D's keyslists
()Return a iterator of
(key, values)
pairs, where values is the listof all values associated with the key.- Return an iterator of all values associated with a key. Zipping
keys()
and this is the same as callinglists()
:
- >>> 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 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
Parameters:
- **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.
Pop a
(key, list)
tuple from the dict.- Pop the list for a key from the dict. If the key is not in the dictan empty list is returned.
Changed in version 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.
Parameters:
- **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']
Parameters:
- **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]
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 listbefore returned.Returns:
a list
todict
(_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.
Parameters: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.Returns:a dict
- >>> 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 valueswill be added to the dict and the key will not be created:
- >>> x = {'empty_list': []}
- >>> y = MultiDict()
- >>> y.update(x)
- >>> y
- MultiDict([])
- class
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 theitems()
method and pass itmulti=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
.
New in version 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
).
- class
werkzeug.datastructures.
ImmutableOrderedMultiDict
(mapping=None) - An immutable
OrderedMultiDict
.
New in version 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
).
- class
werkzeug.datastructures.
CombinedMultiDict
(dicts=None) - A read only
MultiDict
that you can pass multipleMultiDict
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 400 BAD REQUEST
if caught in a catch-all for HTTPexceptions.
- class
werkzeug.datastructures.
ImmutableDict
- An immutable
dict
.
New in version 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
).
- class
werkzeug.datastructures.
ImmutableList
- An immutable
list
.
New in version 0.5.
Private:
- class
werkzeug.datastructures.
FileMultiDict
(mapping=None) - A special
MultiDict
that has convenience methods to addfiles to it. This is used forEnvironBuilder
and generallyuseful for unittesting.
New in version 0.5.
addfile
(_name, file, filename=None, content_type=None)- Adds a new file to the dict. file can be a file name ora
file
-like or aFileStorage
object.
Parameters:
- **name** – the name of the field.
- **file** – a filename or <code>file</code>-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
raised by this class isalso a subclass of the BadRequest
HTTP exceptionand will render a page for a 400 BAD REQUEST
if caught in acatch-all for HTTP exceptions.
Headers is mostly compatible with the Python wsgiref.headers.Headers
class, with the exception of getitem. wsgiref
will returnNone for headers['missing']
, whereas Headers
will raisea 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.
Parameters:defaults – The list of default values for the Headers
.
Changed in version 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.
Changed in version 0.9: The linked()
function was removed without replacement as itwas an API that does not support the changes to the encoding model.
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.
New in version 0.4.1: keyword arguments were added for wsgiref
compatibility.
An alias for add()
for compatibility with the wsgiref
add_header()
method.
clear
()Clears all headers.
Extend the headers with a dict or an iterable yielding keys andvalues.
- 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. 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.
New in version 0.9: Added support for as_bytes.
Parameters:
- **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 the[<code>Headers</code>]($7800771996c024cd.md#werkzeug.datastructures.Headers). If a [<code>ValueError</code>](https://docs.python.org/3/library/exceptions.html#ValueError) is raisedby this callable the default value is returned.
- **as_bytes** – return bytes instead of unicode strings.
This method is compatible with the wsgiref
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
, the return value will be an empty list. Just asget()
getlist()
accepts a type parameter. All items willbe converted with the callable defined there.
New in version 0.9: Added support for as_bytes.
Parameters:
- **key** – The key to be looked up.
- **type** – A callable that is used to cast the value in the[<code>Headers</code>]($7800771996c024cd.md#werkzeug.datastructures.Headers). If a [<code>ValueError</code>](https://docs.python.org/3/library/exceptions.html#ValueError) is raisedby this callable the value will be removed from the list.
- **as_bytes** – return bytes instead of unicode strings.Returns:
a list
of all the values for the key.
Parameters: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.Returns:an item.
Parameters: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()
formore information.
Changed in version 0.6.1: set()
now accepts the same arguments as add()
.
Parameters:
- **key** – The key to be inserted.
- **value** – The value to be inserted.
setdefault
(key, default)- Returns the value for the key if it is in the dict, otherwise itreturns 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 notin the dict. If not further specified it’s _None_.
Deprecated since version 0.9.
The values are byte strings in Python 2 converted to latin1 and unicodestrings in Python 3 for the WSGI server to encode.
Returns: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 400 BAD REQUEST
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.UnlikeETags
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.
- Return the set as real python set type. When calling this, allthe items are converted to lowercase and the ordering is lost.
Parameters:preserve_casing – if set to True the items in the set returnedwill have the original case like in theHeaderSet
, otherwise they willbe lowercase.
clear
()Clear the set.
- Like
remove()
but ignores errors.
Parameters:header – the header to be discarded.
Parameters:header – the header to be looked up.
index
(header)- Return the index of the header in the set or raise an
IndexError
.
Parameters:header – the header to be looked up.
remove
(header)- Remove a header from the set. This raises an
KeyError
if theheader is not in the set.
Changed in version 0.5: In older versions a IndexError
was raised instead of aKeyError
if the object was missing.
Parameters:header – the header to be removed.
to_header
()Convert the header set into an HTTP header string.
- Add all the headers from the iterable to the set.
Parameters:iterable – updates the set with the items from the iterable.
- class
werkzeug.datastructures.
Accept
(values=()) - An
Accept
object is just a list subclass for lists of(value, quality)
tuples. It is automatically sorted by specificityand quality.
All 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
Changed in version 0.5: Accept
objects are forced immutable now.
best
The best match as value.
- Returns the best match from a list of possible matches basedon the specificity and quality of the client. If two items have thesame quality and specificity, the one is returned that comes first.
Parameters:
- **matches** – a list of matches to check for
- **default** – the value that is returned if none match
Parameters:key – The key to be looked up.
index
(key)- Get the position of an entry or raise
ValueError
.
Parameters:key – The key to be looked up.
Changed in version 0.5: This used to raise IndexError
, which was inconsistentwith the list API.
New in version 0.6: In previous versions you had to use the item-lookup syntax(eg: obj[key]
instead of obj.quality(key)
)
- class
werkzeug.datastructures.
MIMEAccept
(values=()) Like
Accept
but with special methods and behavior formimetypes.
- class
werkzeug.datastructures.
CharsetAccept
(values=()) - Like
Accept
but with normalization for charsets.
- class
werkzeug.datastructures.
LanguageAccept
(values=()) - Like
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
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.
New in version 0.5: In previous versions a CacheControl class existed that was usedboth for request and response.
no_cache
accessor for ‘no-cache’
accessor for ‘no-store’
accessor for ‘max-age’
accessor for ‘no-transform’
accessor for ‘max-stale’
accessor for ‘min-fresh’
no_transform
accessor for ‘no-transform’
- accessor for ‘only-if-cached’
- class
werkzeug.datastructures.
ResponseCacheControl
(values=(), on_update=None) - A cache control for responses. Unlike
RequestCacheControl
this is mutable and gives access to response-relevant cache controlheaders.
To get a header of the 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.
New in version 0.5: In previous versions a CacheControl class existed that was usedboth for request and response.
no_cache
accessor for ‘no-cache’
accessor for ‘no-store’
accessor for ‘max-age’
accessor for ‘no-transform’
accessor for ‘must-revalidate’
accessor for ‘private’
accessor for ‘proxy-revalidate’
accessor for ‘public’
- 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.
asset
(_include_weak=False)Convert the ETags object into a python set. Per default all theweak etags are not part of this set.
Check if an etag is part of the set ignoring weak tags.It is also possible to use the
in
operator.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.
Check if an etag is part of the set including weak and strong tags.
Check if an etag is strong.
Check if an etag is weak.
- 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.
Changed in version 0.5: This object became immutable.
cnonce
If the server sent a qop-header in the
WWW-Authenticate
header, the client has to provide this value for HTTP digest auth.See the RFC for more details.The nonce count value transmitted by clients if a qop-header isalso transmitted. HTTP digest auth only.
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.
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.
When the authentication type is basic this is the passwordtransmitted by the client, else None.
Indicates what “quality of protection” the client has applied tothe message for HTTP digest auth. Note that this is a single token,not a quoted list of alternatives as in WWW-Authenticate.
This is the server realm sent back for HTTP digest auth.
A string of 32 hex digits computed as defined in RFC 2617, whichproves that the user knows a password. Digest auth only.
The URI from Request-URI of the Request-Line; duplicated becauseproxies are allowed to change the Request-Line in transit. HTTPdigest auth only.
- 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 producethe digest and a checksum. If this is not present it is assumedto be “MD5”. If the algorithm is not understood, the challengeshould be ignored (and a different one used, if there is morethan one).
- 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
etc.) are implemented.
domain
A list of URIs that define the protection space. If a URIis an absolute path, it is relative to the canonical root URL ofthe server being accessed.
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.
A string of data, specified by the server, which shouldbe returned by the client unchanged in the Authorization headerof subsequent requests with URIs in the same protection space.It is recommended that this string be base64 or hexadecimaldata.
A set of quality-of-privacy directives such as auth andauth-int.
A string to be displayed to users so they know whichusername and password to use. This string should contain atleast the name of the host performing the authentication andmight additionally indicate the collection of users who mighthave access.
Clear the auth info and enable basic auth.
setdigest
(_realm, nonce, qop=('auth', ), opaque=None, algorithm=None, stale=False)Clear the auth info and enable digest auth.
A flag, indicating that the previous request from the clientwas rejected because the nonce value was stale.
Convert the stored values into a WWW-Authenticate header.
- The type of the auth mechanism. HTTP currently specifies
Basic
andDigest
.
- 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.
New in version 0.7.
date
= NoneThe date in parsed format or None.
The etag parsed and unquoted. Ranges always operate on strongetags so the weakness information is not necessary.
- Converts the object back into an HTTP header.
- class
werkzeug.datastructures.
Range
(units, ranges) - Represents a
Range
header. All methods only support onlybytes as the unit. Stores a list of ranges if given, but the methodsonly work if only one range is provided.
Raises:ValueError – If the ranges provided are invalid.
Changed in version 0.15: The ranges passed in are validated.
New in version 0.7.
makecontent_range
(_length)Creates a
ContentRange
objectfrom the current range and given content 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.A list of
(begin, end)
tuples for the range header provided.The ranges are non-inclusive.Converts the object into Content-Range HTTP header,based on given length
Converts the object back into an HTTP header.
- The units of this range. Usually “bytes”.
- class
werkzeug.datastructures.
ContentRange
(units, start, stop, length=None, on_update=None) - Represents the content range header.
New in version 0.7.
length
The length of the range or None.
Simple method to update the ranges.
The start point of the range or None.
The stop point of the range (non-inclusive) or None. Can only beNone if also start is None.
The units to use, usually “bytes”
- 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
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 dostorage.read()
instead of the long formstorage.stream.read()
.stream
The input stream for the uploaded file. This usually points to anopen temporary file.
The filename of the file on the client.
The name of the form field.
- The multipart headers as
Headers
object. This usually containsirrelevant information but in combination with custom multipart requeststhe raw headers might be interesting.
New in version 0.6.
close
()Close the underlying file if possible.
The content-length sent in the header. Usually not available
The content-type sent in the header. Usually not available
- Like
content_type
, but without parameters (eg, withoutcharset, type etc.) and always lowercase. For example if the contenttype istext/HTML; charset=utf-8
the mimetype would be'text/html'
.
New in version 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'}
.
New in version 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()
.
Parameters:
- **dst** – a filename or open file object the uploaded fileis saved to.
- **buffer_size** – the size of the buffer. This works the same asthe _length_ parameter of[<code>shutil.copyfileobj()</code>](https://docs.python.org/3/library/shutil.html#shutil.copyfileobj).