Utilities
最后更新于:2022-04-01 04:07:32
# Utilities
Various utility functions shipped with Werkzeug.
### HTML Helpers
*class *werkzeug.utils.HTMLBuilder(*dialect*)
Helper object for HTML generation.
Per default there are two instances of that class. The html one, andthe xhtml one for those two dialects. The class uses keyword parametersand positional parameters to generate small snippets of HTML.
Keyword parameters are converted to XML/SGML attributes, positionalarguments are used as children. Because Python accepts positionalarguments before keyword arguments it's a good idea to use a list with thestar-syntax for some children:
~~~
>>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
... html.a('bar', href='bar.html')])
u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'
~~~
This class works around some browser limitations and can not be used forarbitrary SGML/XML generation. For that purpose lxml and similarlibraries exist.
Calling the builder escapes the string passed:
~~~
>>> html.p(html("<foo>"))
u'<p><foo></p>'
~~~
werkzeug.utils.escape(*s*, *quote=None*)
Replace special characters “&”, “<”, “>” and (”) to HTML-safe sequences.
There is a special handling for None which escapes to an empty string.
在 0.9 版更改: quote is now implicitly on.
<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>s</strong> – the string to escape.</li><li><strong>quote</strong> – ignored.</li></ul></td></tr></tbody></table>
werkzeug.utils.unescape(*s*)
The reverse function of escape. This unescapes all the HTMLentities, not only the XML entities inserted by escape.
| 参数: | **s** – the string to unescape. |
|-----|-----|
### General Helpers
*class *werkzeug.utils.cached_property(*func*, *name=None*, *doc=None*)
A decorator that converts a function into a lazy property. Thefunction wrapped is called the first time to retrieve the resultand then that calculated result is used the next time you accessthe value:
~~~
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
~~~
The class has to have a __dict__ in order for this property towork.
*class *werkzeug.utils.environ_property(*name*, *default=None*, *load_func=None*, *dump_func=None*, *read_only=None*, *doc=None*)
Maps request attributes to environment variables. This works not onlyfor the Werzeug request object, but also any other class with anenviron attribute:
~~~
>>> class Test(object):
... environ = {'key': 'value'}
... test = environ_property('key')
>>> var = Test()
>>> var.test
'value'
~~~
If you pass it a second value it's used as default if the key does notexist, the third one can be a converter that takes a value and convertsit. If it raises [ValueError](http://docs.python.org/dev/library/exceptions.html#ValueError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#ValueError] or [TypeError](http://docs.python.org/dev/library/exceptions.html#TypeError "(在 Python v3.5)") [http://docs.python.org/dev/library/exceptions.html#TypeError] the default valueis used. If no default value is provided None is used.
Per default the property is read only. You have to explicitly enable itby passing read_only=False to the constructor.
*class *werkzeug.utils.header_property(*name*, *default=None*, *load_func=None*, *dump_func=None*, *read_only=None*, *doc=None*)
Like environ_property but for headers.
werkzeug.utils.parse_cookie(*header*, *charset='utf-8'*, *errors='replace'*, *cls=None*)
Parse a cookie. Either from a string or WSGI environ.
Per default encoding errors are ignored. If you want a different behavioryou can set errors to 'replace' or 'strict'. In strict mode aHTTPUnicodeError is raised.
在 0.5 版更改: This function now returns a TypeConversionDict instead of aregular dict. The cls parameter was added.
<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>header</strong> – the header to be used to parse the cookie. Alternativelythis can be a WSGI environment.</li><li><strong>charset</strong> – the charset for the cookie values.</li><li><strong>errors</strong> – the error behavior for the charset decoding.</li><li><strong>cls</strong> – an optional dict class to use. If this is not specifiedor <cite>None</cite> the default <tt class="xref py py-class docutils literal"><span class="pre">TypeConversionDict</span></tt> isused.</li></ul></td></tr></tbody></table>
werkzeug.utils.dump_cookie(*key*, *value=''*, *max_age=None*, *expires=None*, *path='/'*, *domain=None*, *secure=False*, *httponly=False*, *charset='utf-8'*, *sync_expires=True*)
Creates a new Set-Cookie header without the Set-Cookie prefixThe parameters are the same as in the cookie Morsel object in thePython standard library but it accepts unicode data, too.
On Python 3 the return value of this function will be a unicodestring, on Python 2 it will be a native string. In both cases thereturn value is usually restricted to ascii as the vast majority ofvalues are properly escaped, but that is no guarantee. If a unicodestring is returned it's tunneled through latin1 as required byPEP 3333.
The return value is not ASCII safe if the key contains unicodecharacters. This is technically against the specification buthappens in the wild. It's strongly recommended to not usenon-ASCII values for the keys.
<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>max_age</strong> – should be a number of seconds, or <cite>None</cite> (default) ifthe cookie should last only as long as the client'sbrowser session. Additionally <cite>timedelta</cite> objectsare accepted, too.</li><li><strong>expires</strong> – should be a <cite>datetime</cite> object or unix timestamp.</li><li><strong>path</strong> – limits the cookie to a given path, per default it willspan the whole domain.</li><li><strong>domain</strong> – Use this if you want to set a cross-domain cookie. Forexample, <tt class="docutils literal"><span class="pre">domain=".example.com"</span></tt> will set a cookiethat is readable by the domain <tt class="docutils literal"><span class="pre">www.example.com</span></tt>,<tt class="docutils literal"><span class="pre">foo.example.com</span></tt> etc. Otherwise, a cookie will onlybe readable by the domain that set it.</li><li><strong>secure</strong> – The cookie will only be available via HTTPS</li><li><strong>httponly</strong> – disallow JavaScript to access the cookie. This is anextension to the cookie standard and probably notsupported by all browsers.</li><li><strong>charset</strong> – the encoding for unicode values.</li><li><strong>sync_expires</strong> – automatically set expires if max_age is definedbut expires not.</li></ul></td></tr></tbody></table>
werkzeug.utils.redirect(*location*, *code=302*)
Return a response object (a WSGI application) that, if called,redirects the client to the target location. Supported codes are 301,302, 303, 305, and 307. 300 is not supported because it's not a realredirect and 304 because it's the answer for a request with a requestwith defined If-Modified-Since headers.
0.6 新版功能: The location can now be a unicode string that is encoded usingthe iri_to_uri() function.
<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>location</strong> – the location the response should redirect to.</li><li><strong>code</strong> – the redirect status code. defaults to 302.</li></ul></td></tr></tbody></table>
werkzeug.utils.append_slash_redirect(*environ*, *code=301*)
Redirect to the same URL but with a slash appended. The behaviorof this function is undefined if the path ends with a slash already.
<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>environ</strong> – the WSGI environment for the request that triggersthe redirect.</li><li><strong>code</strong> – the status code for the redirect.</li></ul></td></tr></tbody></table>
werkzeug.utils.import_string(*import_name*, *silent=False*)
Imports an object based on a string. This is useful if you want touse import paths as endpoints or something similar. An import path canbe specified either in dotted notation (xml.sax.saxutils.escape)or with a colon as object delimiter (xml.sax.saxutils:escape).
If silent is True the return value will be None if the import fails.
<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>import_name</strong> – the dotted name for the object to import.</li><li><strong>silent</strong> – if set to <cite>True</cite> import errors are ignored and<cite>None</cite> is returned instead.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">imported object</p></td></tr></tbody></table>
werkzeug.utils.find_modules(*import_path*, *include_packages=False*, *recursive=False*)
Find all the modules below a package. This can be useful toautomatically import all views / controllers so that their metaclasses /function decorators have a chance to register themselves on theapplication.
Packages are not returned unless include_packages is True. This canalso recursively list modules but in that case it will import all thepackages to get the correct load path of that module.
<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>import_name</strong> – the dotted name for the package to find child modules.</li><li><strong>include_packages</strong> – set to <cite>True</cite> if packages should be returned, too.</li><li><strong>recursive</strong> – set to <cite>True</cite> if recursion should happen.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">generator</p></td></tr></tbody></table>
werkzeug.utils.validate_arguments(*func*, *args*, *kwargs*, *drop_extra=True*)
Check if the function accepts the arguments and keyword arguments.Returns a new (args,kwargs) tuple that can safely be passed tothe function without causing a TypeError because the function signatureis incompatible. If drop_extra is set to True (which is the default)any extra positional or keyword arguments are dropped automatically.
The exception raised provides three attributes:
missingA set of argument names that the function expected but wheremissing.extraA dict of keyword arguments that the function can not handle butwhere provided.extra_positionalA list of values that where given by positional argument but thefunction cannot accept.
This can be useful for decorators that forward user submitted data toa view function:
~~~
from werkzeug.utils import ArgumentValidationError, validate_arguments
def sanitize(f):
def proxy(request):
data = request.values.to_dict()
try:
args, kwargs = validate_arguments(f, (request,), data)
except ArgumentValidationError:
raise BadRequest('The browser failed to transmit all '
'the data expected.')
return f(*args, **kwargs)
return proxy
~~~
<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>func</strong> – the function the validation is performed against.</li><li><strong>args</strong> – a tuple of positional arguments.</li><li><strong>kwargs</strong> – a dict of keyword arguments.</li><li><strong>drop_extra</strong> – set to <cite>False</cite> if you don't want extra argumentsto be silently dropped.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">tuple in the form <tt class="docutils literal"><span class="pre">(args,</span> <span class="pre">kwargs)</span></tt>.</p></td></tr></tbody></table>
werkzeug.utils.secure_filename(*filename*)
Pass it a filename and it will return a secure version of it. Thisfilename can then safely be stored on a regular file system and passedto [os.path.join()](http://docs.python.org/dev/library/os.path.html#os.path.join "(在 Python v3.5)") [http://docs.python.org/dev/library/os.path.html#os.path.join]. The filename returned is an ASCII only stringfor maximum portability.
On windows system the function also makes sure that the file is notnamed after one of the special device files.
~~~
>>> secure_filename("My cool movie.mov")
'My_cool_movie.mov'
>>> secure_filename("../../../etc/passwd")
'etc_passwd'
>>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
'i_contain_cool_umlauts.txt'
~~~
The function might return an empty filename. It's your responsibilityto ensure that the filename is unique and that you generate randomfilename if the function returned an empty one.
0.5 新版功能.
| 参数: | **filename** – the filename to secure |
|-----|-----|
werkzeug.utils.bind_arguments(*func*, *args*, *kwargs*)
Bind the arguments provided into a dict. When passed a function,a tuple of arguments and a dict of keyword arguments bind_argumentsreturns a dict of names as the function would see it. This can be usefulto implement a cache decorator that uses the function arguments to buildthe cache key based on the values of the arguments.
<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>func</strong> – the function the arguments should be bound for.</li><li><strong>args</strong> – tuple of positional arguments.</li><li><strong>kwargs</strong> – a dict of keyword arguments.</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#dict" title="(在 Python v3.5)"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/stdtypes.html#dict]</span> of bound keyword arguments.</p></td></tr></tbody></table>
### URL Helpers
*class *werkzeug.urls.Href(*base='./'*, *charset='utf-8'*, *sort=False*, *key=None*)
Implements a callable that constructs URLs with the given base. Thefunction can be called with any number of positional and keywordarguments which than are used to assemble the URL. Works with URLsand posix paths.
Positional arguments are appended as individual segments tothe path of the URL:
~~~
>>> href = Href('/foo')
>>> href('bar', 23)
'/foo/bar/23'
>>> href('foo', bar=23)
'/foo/foo?bar=23'
~~~
If any of the arguments (positional or keyword) evaluates to None itwill be skipped. If no keyword arguments are given the last argumentcan be a [dict](http://docs.python.org/dev/library/stdtypes.html#dict "(在 Python v3.5)") [http://docs.python.org/dev/library/stdtypes.html#dict] or MultiDict (or any other dict subclass),otherwise the keyword arguments are used for the query parameters, cuttingoff the first trailing underscore of the parameter name:
~~~
>>> href(is_=42)
'/foo?is=42'
>>> href({'foo': 'bar'})
'/foo?foo=bar'
~~~
Combining of both methods is not allowed:
~~~
>>> href({'foo': 'bar'}, bar=42)
Traceback (most recent call last):
...
TypeError: keyword arguments and query-dicts can't be combined
~~~
Accessing attributes on the href object creates a new href object withthe attribute name as prefix:
~~~
>>> bar_href = href.bar
>>> bar_href("blub")
'/foo/bar/blub'
~~~
If sort is set to True the items are sorted by key or the defaultsorting algorithm:
~~~
>>> href = Href("/", sort=True)
>>> href(a=1, b=2, c=3)
'/?a=1&b=2&c=3'
~~~
0.5 新版功能: sort and key were added.
werkzeug.urls.url_decode(*s*, *charset='utf-8'*, *decode_keys=False*, *include_empty=True*, *errors='replace'*, *separator='&'*, *cls=None*)
Parse a querystring and return it as MultiDict. There is adifference in key decoding on different Python versions. On Python 3keys will always be fully decoded whereas on Python 2, keys willremain bytestrings if they fit into ASCII. On 2.x keys can be forcedto be unicode by setting decode_keys to True.
If the charset is set to None no unicode decoding will happen andraw bytes will be returned.
Per default a missing value for a key will default to an empty key. Ifyou don't want that behavior you can set include_empty to False.
Per default encoding errors are ignored. If you want a different behavioryou can set errors to 'replace' or 'strict'. In strict mode aHTTPUnicodeError is raised.
在 0.5 版更改: In previous versions ”;” and “&” could be used for url decoding.This changed in 0.5 where only “&” is supported. If you want touse ”;” instead a different separator can be provided.
The cls parameter was added.
<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>s</strong> – a string with the query string to decode.</li><li><strong>charset</strong> – the charset of the query string. If set to <cite>None</cite>no unicode decoding will take place.</li><li><strong>decode_keys</strong> – Used on Python 2.x to control whether keys shouldbe forced to be unicode objects. If set to <cite>True</cite>then keys will be unicode in all cases. Otherwise,they remain <cite>str</cite> if they fit into ASCII.</li><li><strong>include_empty</strong> – Set to <cite>False</cite> if you don't want empty values toappear in the dict.</li><li><strong>errors</strong> – the decoding error behavior.</li><li><strong>separator</strong> – the pair separator to be used, defaults to <tt class="docutils literal"><span class="pre">&</span></tt></li><li><strong>cls</strong> – an optional dict class to use. If this is not specifiedor <cite>None</cite> the default <tt class="xref py py-class docutils literal"><span class="pre">MultiDict</span></tt> is used.</li></ul></td></tr></tbody></table>
werkzeug.urls.url_decode_stream(*stream*, *charset='utf-8'*, *decode_keys=False*, *include_empty=True*, *errors='replace'*, *separator='&'*, *cls=None*, *limit=None*, *return_iterator=False*)
Works like [url_decode()](# "werkzeug.urls.url_decode") but decodes a stream. The behaviorof stream and limit follows functions like[make_line_iter()](# "werkzeug.wsgi.make_line_iter"). The generator of pairs isdirectly fed to the cls so you can consume the data while it'sparsed.
0.8 新版功能.
<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>stream</strong> – a stream with the encoded querystring</li><li><strong>charset</strong> – the charset of the query string. If set to <cite>None</cite>no unicode decoding will take place.</li><li><strong>decode_keys</strong> – Used on Python 2.x to control whether keys shouldbe forced to be unicode objects. If set to <cite>True</cite>,keys will be unicode in all cases. Otherwise, theyremain <cite>str</cite> if they fit into ASCII.</li><li><strong>include_empty</strong> – Set to <cite>False</cite> if you don't want empty values toappear in the dict.</li><li><strong>errors</strong> – the decoding error behavior.</li><li><strong>separator</strong> – the pair separator to be used, defaults to <tt class="docutils literal"><span class="pre">&</span></tt></li><li><strong>cls</strong> – an optional dict class to use. If this is not specifiedor <cite>None</cite> the default <tt class="xref py py-class docutils literal"><span class="pre">MultiDict</span></tt> is used.</li><li><strong>limit</strong> – the content length of the URL data. Not necessary ifa limited stream is provided.</li><li><strong>return_iterator</strong> – if set to <cite>True</cite> the <cite>cls</cite> argument is ignoredand an iterator over all decoded pairs isreturned</li></ul></td></tr></tbody></table>
werkzeug.urls.url_encode(*obj*, *charset='utf-8'*, *encode_keys=False*, *sort=False*, *key=None*, *separator='&'*)
URL encode a dict/MultiDict. If a value is None it will not appearin the result string. Per default only values are encoded into the targetcharset strings. If encode_keys is set to True unicode keys aresupported too.
If sort is set to True the items are sorted by key or the defaultsorting algorithm.
0.5 新版功能: sort, key, and separator were added.
<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>obj</strong> – the object to encode into a query string.</li><li><strong>charset</strong> – the charset of the query string.</li><li><strong>encode_keys</strong> – set to <cite>True</cite> if you have unicode keys. (Ignored onPython 3.x)</li><li><strong>sort</strong> – set to <cite>True</cite> if you want parameters to be sorted by <cite>key</cite>.</li><li><strong>separator</strong> – the separator to be used for the pairs.</li><li><strong>key</strong> – an optional function to be used for sorting. For more detailscheck out the <a class="reference external" href="http://docs.python.org/dev/library/functions.html#sorted" title="(在 Python v3.5)"><tt class="xref py py-func docutils literal"><span class="pre">sorted()</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/functions.html#sorted]</span> documentation.</li></ul></td></tr></tbody></table>
werkzeug.urls.url_encode_stream(*obj*, *stream=None*, *charset='utf-8'*, *encode_keys=False*, *sort=False*, *key=None*, *separator='&'*)
Like [url_encode()](# "werkzeug.urls.url_encode") but writes the results to a streamobject. If the stream is None a generator over all encodedpairs is returned.
0.8 新版功能.
<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>obj</strong> – the object to encode into a query string.</li><li><strong>stream</strong> – a stream to write the encoded object into or <cite>None</cite> ifan iterator over the encoded pairs should be returned. Inthat case the separator argument is ignored.</li><li><strong>charset</strong> – the charset of the query string.</li><li><strong>encode_keys</strong> – set to <cite>True</cite> if you have unicode keys. (Ignored onPython 3.x)</li><li><strong>sort</strong> – set to <cite>True</cite> if you want parameters to be sorted by <cite>key</cite>.</li><li><strong>separator</strong> – the separator to be used for the pairs.</li><li><strong>key</strong> – an optional function to be used for sorting. For more detailscheck out the <a class="reference external" href="http://docs.python.org/dev/library/functions.html#sorted" title="(在 Python v3.5)"><tt class="xref py py-func docutils literal"><span class="pre">sorted()</span></tt></a><span class="link-target"> [http://docs.python.org/dev/library/functions.html#sorted]</span> documentation.</li></ul></td></tr></tbody></table>
werkzeug.urls.url_quote(*string*, *charset='utf-8'*, *errors='strict'*, *safe='/:'*, *unsafe=''*)
URL encode a single string with a given encoding.
<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>s</strong> – the string to quote.</li><li><strong>charset</strong> – the charset to be used.</li><li><strong>safe</strong> – an optional sequence of safe characters.</li><li><strong>unsafe</strong> – an optional sequence of unsafe characters.</li></ul></td></tr></tbody></table>
0.9.2 新版功能: The unsafe parameter was added.
werkzeug.urls.url_quote_plus(*string*, *charset='utf-8'*, *errors='strict'*, *safe=''*)
URL encode a single string with the given encoding and convertwhitespace to “+”.
<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>s</strong> – The string to quote.</li><li><strong>charset</strong> – The charset to be used.</li><li><strong>safe</strong> – An optional sequence of safe characters.</li></ul></td></tr></tbody></table>
werkzeug.urls.url_unquote(*string*, *charset='utf-8'*, *errors='replace'*, *unsafe=''*)
URL decode a single string with a given encoding. If the charsetis set to None no unicode decoding is performed and raw bytesare returned.
<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>s</strong> – the string to unquote.</li><li><strong>charset</strong> – the charset of the query string. If set to <cite>None</cite>no unicode decoding will take place.</li><li><strong>errors</strong> – the error handling for the charset decoding.</li></ul></td></tr></tbody></table>
werkzeug.urls.url_unquote_plus(*s*, *charset='utf-8'*, *errors='replace'*)
URL decode a single string with the given charset and decode “+” towhitespace.
Per default encoding errors are ignored. If you want a different behavioryou can set errors to 'replace' or 'strict'. In strict mode aHTTPUnicodeError is raised.
<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>s</strong> – The string to unquote.</li><li><strong>charset</strong> – the charset of the query string. If set to <cite>None</cite>no unicode decoding will take place.</li><li><strong>errors</strong> – The error handling for the <cite>charset</cite> decoding.</li></ul></td></tr></tbody></table>
werkzeug.urls.url_fix(*s*, *charset='utf-8'*)
Sometimes you get an URL by a user that just isn't a real URL becauseit contains unsafe characters like ‘ ‘ and so on. This function can fixsome of the problems in a similar way browsers handle data entered by theuser:
~~~
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)'
~~~
<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>s</strong> – the string with the URL to fix.</li><li><strong>charset</strong> – The target charset for the URL if the url was given asunicode string.</li></ul></td></tr></tbody></table>
werkzeug.urls.uri_to_iri(*uri*, *charset='utf-8'*, *errors='replace'*)
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
~~~
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
~~~
Query strings are left unchanged:
~~~
>>> uri_to_iri('/?foo=24&x=%26%2f')
u'/?foo=24&x=%26%2f'
~~~
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>uri</strong> – The URI to convert.</li><li><strong>charset</strong> – The charset of the URI.</li><li><strong>errors</strong> – The error handling on decode.</li></ul></td></tr></tbody></table>
werkzeug.urls.iri_to_uri(*iri*, *charset='utf-8'*, *errors='strict'*)
Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug alwaysuses utf-8 URLs internally because this is what browsers and HTTP do aswell. In some places where it accepts an URL it also accepts a unicode IRIand converts it into a URI.
Examples for IRI versus URI:
~~~
>>> iri_to_uri(u'http://☃.net/')
'http://xn--n3h.net/'
>>> iri_to_uri(u'http://üser:pässword@☃.net/påth')
'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th'
~~~
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>iri</strong> – The IRI to convert.</li><li><strong>charset</strong> – The charset for the URI.</li></ul></td></tr></tbody></table>
### UserAgent Parsing
*class *werkzeug.useragents.UserAgent(*environ_or_string*)
Represents a user agent. Pass it a WSGI environment or a user agentstring and you can inspect some of the details from the user agentstring via the attributes. The following attributes exist:
string
the raw user agent string
platform
the browser platform. The following platforms are currentlyrecognized:
- aix
- amiga
- android
- bsd
- hpux
- iphone
- ipad
- irix
- linux
- macos
- sco
- solaris
- wii
- windows
browser
the name of the browser. The following browsers are currentlyrecognized:
- aol *
- ask *
- camino
- chrome
- firefox
- galeon
- google *
- kmeleon
- konqueror
- links
- lynx
- msie
- msn
- netscape
- opera
- safari
- seamonkey
- webkit
- yahoo *
(Browsers maked with a star (*) are crawlers.)
version
the version of the browser
language
the language of the browser
### Security Helpers
0.6.1 新版功能.
werkzeug.security.generate_password_hash(*password*, *method='pbkdf2:sha1'*, *salt_length=8*)
Hash a password with the given method and salt with with a string ofthe given length. The format of the string returned includes the methodthat was used so that [check_password_hash()](# "werkzeug.security.check_password_hash") can check the hash.
The format for the hashed string looks like this:
~~~
method$salt$hash
~~~
This method can **not** generate unsalted passwords but it is possibleto set the method to plain to enforce plaintext passwords. If a saltis used, hmac is used internally to salt the password.
If PBKDF2 is wanted it can be enabled by setting the method topbkdf2:method:iterations where iterations is optional:
~~~
pbkdf2:sha1:2000$salt$hash
pbkdf2:sha1$salt$hash
~~~
<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>password</strong> – the password to hash</li><li><strong>method</strong> – the hash method to use (one that hashlib supports), canoptionally be in the format <tt class="docutils literal"><span class="pre">pbpdf2:<method>[:iterations]</span></tt>to enable PBKDF2.</li><li><strong>salt_length</strong> – the length of the salt in letters</li></ul></td></tr></tbody></table>
werkzeug.security.check_password_hash(*pwhash*, *password*)
check a password against a given salted and hashed password value.In order to support unsalted legacy passwords this method supportsplain text passwords, md5 and sha1 hashes (both salted and unsalted).
Returns True if the password matched, False otherwise.
<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>pwhash</strong> – a hashed string like returned by<a class="reference internal" href="#werkzeug.security.generate_password_hash" title="werkzeug.security.generate_password_hash"><tt class="xref py py-func docutils literal"><span class="pre">generate_password_hash()</span></tt></a></li><li><strong>password</strong> – the plaintext password to compare against the hash</li></ul></td></tr></tbody></table>
werkzeug.security.safe_str_cmp(*a*, *b*)
This function compares strings in somewhat constant time. Thisrequires that the length of at least one string is known in advance.
Returns True if the two strings are equal or False if they are not.
0.7 新版功能.
werkzeug.security.safe_join(*directory*, *filename*)
Safely join directory and filename. If this cannot be done,this function returns None.
<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>directory</strong> – the base directory.</li><li><strong>filename</strong> – the untrusted filename relative to that directory.</li></ul></td></tr></tbody></table>
werkzeug.security.pbkdf2_hex(*data*, *salt*, *iterations=1000*, *keylen=None*, *hashfunc=None*)
Like [pbkdf2_bin()](# "werkzeug.security.pbkdf2_bin") but returns a hex encoded string.
0.9 新版功能.
<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>data</strong> – the data to derive.</li><li><strong>salt</strong> – the salt for the derivation.</li><li><strong>iterations</strong> – the number of iterations.</li><li><strong>keylen</strong> – the length of the resulting key. If not providedthe digest size will be used.</li><li><strong>hashfunc</strong> – the hash function to use. This can either be thestring name of a known hash function or a functionfrom the hashlib module. Defaults to sha1.</li></ul></td></tr></tbody></table>
werkzeug.security.pbkdf2_bin(*data*, *salt*, *iterations=1000*, *keylen=None*, *hashfunc=None*)
Returns a binary digest for the PBKDF2 hash algorithm of datawith the given salt. It iterates iterations time and produces akey of keylen bytes. By default SHA-1 is used as hash function,a different hashlib hashfunc can be provided.
0.9 新版功能.
<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>data</strong> – the data to derive.</li><li><strong>salt</strong> – the salt for the derivation.</li><li><strong>iterations</strong> – the number of iterations.</li><li><strong>keylen</strong> – the length of the resulting key. If not providedthe digest size will be used.</li><li><strong>hashfunc</strong> – the hash function to use. This can either be thestring name of a known hash function or a functionfrom the hashlib module. Defaults to sha1.</li></ul></td></tr></tbody></table>