You can import all these objects directly from werkzeug.
A WSGI middleware that provides static content for development environments or simple server setups. Usage is quite simple:
import os
from werkzeug import SharedDataMiddleware
app = SharedDataMiddleware(app, {
'/shared': os.path.join(os.path.dirname(__file__), 'shared')
})
The contents of the folder ./shared will now be available on http://example.com/shared/. This is pretty useful during development because a standalone media server is not required. One can also mount files on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders.
If pkg_resources is available you can also tell the middleware to serve files from package data:
app = SharedDataMiddleware(app, {
'/shared': ('myapplication', 'shared_files')
})
This will then serve the shared_files folder in the myapplication Python package.
The optional disallow parameter can be a list of fnmatch() rules for files that are not accessible from the web. If cache is set to False no caching headers are sent.
Currently the middleware does not support non ASCII filenames. If the encoding on the file system happens to be the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files.
Changed in version 0.5: The cache timeout is configurable now.
Parameters: |
|
---|---|
Param cache_timeout: | |
the cache timeout in seconds for the headers. |
Allows one to mount middlewares or application in a WSGI application. This is useful if you want to combine multiple WSGI applications:
app = DispatcherMiddleware(app, {
'/app2': app2,
'/app3': app3
})
The WSGI specification requires that all middlewares and gateways respect the close callback of an iterator. Because it is useful to add another close action to a returned iterator and adding a custom iterator is a boring task this class can be used for that:
return ClosingIterator(app(environ, start_response), [cleanup_session,
cleanup_locals])
If there is just one close function it can be passed instead of the list.
A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started:
try:
return response(environ, start_response)
finally:
cleanup_session()
cleanup_locals()
This class can be used to convert a file-like object into an iterable. It yields buffer_size blocks until the file is fully read.
You should not use this class directly but rather use the wrap_file() function that uses the WSGI server’s file wrapper support if it’s available.
New in version 0.5.
Parameters: |
---|
Wraps a stream so that it doesn’t read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it on_exhausted() is called which by default returns an empty string or raises BadRequest if silent is set to False. The return value of that function is forwarded to the reader function. So if it returns an empty string read() will return an empty string as well.
The limit however must never be higher than what the stream can output. Otherwise readlines() will try to read past the limit.
The silent parameter has no effect if is_exhausted() is overriden by a subclass.
Note on WSGI compliance
calls to readline() and readlines() are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to readline() because there is no EOF marker in the stream. As a result of that the use of readline() is discouraged.
For the same reason iterating over the LimitedStream is not portable. It internally calls readline().
We strongly suggest using read() only or using the make_line_iter() which savely iterates line-based over a WSGI input stream.
Parameters: |
|
---|
Exhaust the stream. This consumes all the data left until the limit is reached.
Parameter: | chunk_size – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. |
---|
This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function.
Per default this raises a BadRequest.
Read size bytes or if size is not provided everything is read.
Parameter: | size – the number of bytes read. |
---|
Savely iterates line-based over an input stream. If the input stream is not a LimitedStream the limit parameter is mandatory.
This uses the stream’s read() method internally as opposite to the readline() method that is unsafe and can only be used in violation of the WSGI specification. The same problem applies to the __iter__ function of the input stream which calls readline() without arguments.
If you need line-by-line processing it’s strongly recommended to iterate over the input stream using this helper function.
Parameters: |
|
---|
Return the real host for the given WSGI environment. This takes care of the X-Forwarded-Host header.
Parameter: | environ – the WSGI environment to get the host of. |
---|
A handy helper function that recreates the full URL for the current request or parts of it. Here an example:
>>> env = create_environ("/?param=foo", "http://localhost/script")
>>> get_current_url(env)
'http://localhost/script/?param=foo'
>>> get_current_url(env, root_only=True)
'http://localhost/script/'
>>> get_current_url(env, host_only=True)
'http://localhost/'
>>> get_current_url(env, strip_querystring=True)
'http://localhost/script/'
Parameters: |
|
---|
Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application.
Example:
@responder
def application(environ, start_response):
return Response('Hello World!')
Wraps a file. This uses the WSGI server’s file wrapper if available or otherwise the generic FileWrapper.
New in version 0.5.
If the file wrapper from the WSGI server is used it’s important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set direct_passthrough to True.
More information about file wrappers are available in PEP 333.
Parameters: |
---|
Removes and returns the next segment of PATH_INFO, pushing it onto SCRIPT_NAME. Returns None if there is nothing left on PATH_INFO.
If there are empty segments ('/foo//bar) these are ignored but properly pushed to the SCRIPT_NAME:
>>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> pop_path_info(env)
'a'
>>> env['SCRIPT_NAME']
'/foo/a'
>>> pop_path_info(env)
'b'
>>> env['SCRIPT_NAME']
'/foo/a/b'
New in version 0.5.
Parameter: | environ – the WSGI environment that is modified. |
---|
Returns the next segment on the PATH_INFO or None if there is none. Works like pop_path_info() without modifying the environment:
>>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> peek_path_info(env)
'a'
>>> peek_path_info(env)
'a'
New in version 0.5.
Parameter: | environ – the WSGI environment that is checked. |
---|
Implements a callable that constructs URLs with the given base. The function can be called with any number of positional and keyword arguments which than are used to assemble the URL. Works with URLs and posix paths.
Positional arguments are appended as individual segments to the 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 it will be skipped. If no keyword arguments are given the last argument can be a dict or MultiDict (or any other dict subclass), otherwise the keyword arguments are used for the query parameters, cutting off 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 with the 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 default sorting algorithm:
>>> href = Href("/", sort=True)
>>> href(a=1, b=2, c=3)
'/?a=1&b=2&c=3'
New in version 0.5: sort and key were added.
Parse a querystring and return it as MultiDict. Per default only values are decoded into unicode strings. If decode_keys is set to True the same will happen for keys.
Per default a missing value for a key will default to an empty key. If you don’t want that behavior you can set include_empty to False.
Per default encoding errors are ignored. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.
Changed in version 0.5: In previous versions “;” and “&” could be used for url decoding. This changed in 0.5 where only “&” is supported. If you want to use “;” instead a different separator can be provided.
The cls parameter was added.
Parameters: |
|
---|
URL encode a dict/MultiDict. If a value is None it will not appear in the result string. Per default only values are encoded into the target charset strings. If encode_keys is set to True unicode keys are supported too.
If sort is set to True the items are sorted by key or the default sorting algorithm.
New in version 0.5: sort, key, and separator were added.
Parameters: |
|
---|
URL encode a single string with a given encoding.
Parameters: |
|
---|
URL encode a single string with the given encoding and convert whitespace to “+”.
Parameters: |
|
---|
URL decode a single string with a given decoding.
Per default encoding errors are ignored. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.
Parameters: |
|
---|
URL decode a single string with the given decoding and decode a “+” to whitespace.
Per default encoding errors are ignored. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.
Parameters: |
|
---|
Sometimes you get an URL by a user that just isn’t a real URL because it contains unsafe characters like ‘ ‘ and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
Parameters: |
|
---|
Helper object for HTML generation.
Per default there are two instances of that class. The html one, and the xhtml one for those two dialects. The class uses keyword parameters and positional parameters to generate small snippets of HTML.
Keyword parameters are converted to XML/SGML attributes, positional arguments are used as children. Because Python accepts positional arguments before keyword arguments it’s a good idea to use a list with the star-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 for arbitrary SGML/XML generation. For that purpose lxml and similar libraries exist.
Calling the builder escapes the string passed:
>>> html.p(html("<foo>"))
u'<p><foo></p>'
Replace special characters “&”, “<” and “>” to HTML-safe sequences. If the optional flag quote is True, the quotation mark character (“) is also translated.
There is a special handling for None which escapes to an empty string.
Parameters: |
|
---|
The reverse function of escape. This unescapes all the HTML entities, not only the XML entities inserted by escape.
Parameter: | s – the string to unescape. |
---|
Represents a user agent. Pass it a WSGI environment or a user agent string and you can inspect some of the details from the user agent string via the attributes. The following attributes exist:
the browser platform. The following platforms are currently recognized:
the name of the browser. The following browsers are currently recognized:
(Browsers maked with a star (*) are crawlers.)
Dump an HTTP header again. This is the reversal of parse_list_header(), parse_set_header() and parse_dict_header(). This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs.
Parameters: |
|
---|
Formats the time to ensure compatibility with Netscape’s cookie standard.
Accepts a floating point number expressed in seconds since the epoc in, a datetime object or a timetuple. All times in UTC. The parse_date() function can be used to parse such a date.
Outputs a string in the format Wdy, DD-Mon-YYYY HH:MM:SS GMT.
Parameter: | expires – If provided that date is used, otherwise the current. |
---|
Formats the time to match the RFC1123 date format.
Accepts a floating point number expressed in seconds since the epoc in, a datetime object or a timetuple. All times in UTC. The parse_date() function can be used to parse such a date.
Outputs a string in the format Wdy, DD Mon YYYY HH:MM:SS GMT.
Parameter: | timestamp – If provided that date is used, otherwise the current. |
---|
Parse the form data in the environ and return it as tuple in the form (stream, form, files). You should only call this method if the transport method is POST or PUT.
If the mimetype of the data transmitted is multipart/form-data the files multidict will be filled with FileStorage objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty.
This function does not raise exceptions, even if the input data is malformed.
Have a look at Dealing with Request Data for more details.
New in version 0.5: The max_form_memory_size, max_content_length and cls parameters were added.
Parameters: |
|
---|---|
Returns: | A tuple in the form (stream, form, files). |
Parse an etag header.
Parameter: | value – the tag header to parse |
---|---|
Returns: | an ETags object. |
Quote an etag.
Parameters: |
|
---|
Unquote a single etag:
>>> unquote_etag('w/"bar"')
('bar', True)
>>> unquote_etag('"bar"')
('bar', False)
Parameter: | etag – the etag identifier to unquote. |
---|---|
Returns: | a (etag, weak) tuple. |
Convenience method for conditional requests.
Parameters: |
|
---|---|
Returns: | True if the resource was modified, otherwise False. |
Parse a Content-Type like header into a tuple with the content type and the options:
>>> parse_options_header('Content-Type: text/html; mimetype=text/html')
('Content-Type: text/html', {'mimetype': 'text/html'})
This should not be used to parse Cache-Control like headers that use a slightly different format. For these headers use the parse_dict_header() function.
New in version 0.5.
Parameter: | value – the header to parse. |
---|---|
Returns: | (str, options) |
Parse a set-like header and return a HeaderSet object. The return value is an object that treats the items case-insensitively and keeps the order of the items.
Parameters: |
|
---|---|
Returns: |
Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing.
Parameter: | value – a string with a list header. |
---|---|
Returns: | list |
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict. If there is no value for a key it will be None.
Parameter: | value – a string with a dict header. |
---|---|
Returns: | dict |
Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction.
Returns a new Accept object (basically a list of (value, quality) tuples sorted by the quality with some additional accessor methods).
The second parameter can be a subclass of Accept that is created with the parsed values and returned.
Parameters: |
|
---|---|
Returns: | an instance of cls. |
Parse a cache control header. The RFC differs between response and request cache control, this method does not. It’s your responsibility to not use the wrong control statements.
New in version 0.5: The cls was added. If not specified an immutable RequestCacheControl is returned.
Parameters: |
|
---|---|
Returns: | a cls object. |
Parse one of the following date formats into a datetime object:
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
If parsing fails the return value is None.
Parameter: | value – a string with a supported date format. |
---|---|
Returns: | a datetime.datetime object. |
Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either None if the header was invalid or not given, otherwise an Authorization object.
Parameter: | value – the authorization header to parse. |
---|---|
Returns: | a Authorization object or None. |
Parse an HTTP WWW-Authenticate header into a WWWAuthenticate object.
Parameters: |
|
---|---|
Returns: | a WWWAuthenticate object. |
Remove all entity headers from a list or Headers object. This operation works in-place. Expires and Content-Location headers are by default not removed. The reason for this is RFC 2616 section 10.3.5 which specifies some entity headers that should be sent.
Changed in version 0.5: added allowed parameter.
Parameters: |
|
---|
Remove all HTTP/1.1 “Hop-by-Hop” headers from a list or Headers object. This operation works in-place.
New in version 0.5.
Parameter: | headers – a list or Headers object. |
---|
Check if a header is an entity header.
New in version 0.5.
Parameter: | header – the header to test. |
---|---|
Returns: | True if it’s an entity header, False otherwise. |
Check if a header is an HTTP/1.1 “Hop-by-Hop” header.
New in version 0.5.
Parameter: | header – the header to test. |
---|---|
Returns: | True if it’s an entity header, False otherwise. |
Quote a header value if necessary.
New in version 0.5.
Parameters: |
|
---|
Unquotes a header value. (Reversal of quote_header_value()). This does not use the real unquoting but what browsers are actually using for quoting.
New in version 0.5.
Parameter: | value – the header value to unquote. |
---|
A decorator that converts a function into a lazy property. The function wrapped is called the first time to retrieve the result and than that calculated result is used the next time you access the value:
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
Changed in version 0.5: cached properties are now optionally writeable.
Maps request attributes to environment variables. This works not only for the Werzeug request object, but also any other class with an environ 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 not exist, the third one can be a converter that takes a value and converts it. If it raises ValueError or TypeError the default value is used. If no default value is provided None is used.
Per default the property is read only. You have to explicitly enable it by passing read_only=False to the constructor.
Parse a cookie. Either from a string or WSGI environ.
Per default encoding errors are ignored. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.
Changed in version 0.5: This function now returns a TypeConversionDict instead of a regular dict. The cls parameter was added.
Parameters: |
|
---|
Creates a new Set-Cookie header without the Set-Cookie prefix The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Parameters: |
|
---|
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 real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
Parameters: |
|
---|
Redirect to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already.
Parameters: |
|
---|
Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be 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.
Parameters: |
|
---|---|
Returns: | imported object |
Find all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application.
Packages are not returned unless include_packages is True. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module.
Parameters: |
|
---|---|
Returns: | generator |
Check if the function accepts the arguments and keyword arguments. Returns a new (args, kwargs) tuple that can savely be passed to the function without causing a TypeError because the function signature is 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:
This can be useful for decorators that forward user submitted data to a view function:
from werkzeug 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
Parameters: |
|
---|---|
Returns: | tuple in the form (args, kwargs). |
Pass it a filename and it will return a secure version of it. This filename can then savely be stored on a regular file system and passed to os.path.join(). The filename returned is an ASCII only string for maximum portability.
On windows system the function also makes sure that the file is not named 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'
New in version 0.5.
Parameter: | filename – the filename to secure |
---|
Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments bind_arguments returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments.
Parameters: |
|
---|---|
Returns: | a dict of bound keyword arguments. |