signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@property<EOL><INDENT>def qop(self):<DEDENT>
def on_update(header_set):<EOL><INDENT>if not header_set and '<STR_LIT>' in self:<EOL><INDENT>del self['<STR_LIT>']<EOL><DEDENT>elif header_set:<EOL><INDENT>self['<STR_LIT>'] = header_set.to_header()<EOL><DEDENT><DEDENT>return parse_set_header(self.get('<STR_LIT>'), on_update)<EOL>
Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.
f5880:c31:m1
def set_basic(self, realm='<STR_LIT>'):
dict.clear(self)<EOL>dict.update(self, {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': realm})<EOL>if self.on_update:<EOL><INDENT>self.on_update(self)<EOL><DEDENT>
Clear the auth info and enable basic auth.
f5880:c32:m1
def set_digest(self, realm, nonce, qop=('<STR_LIT>',), opaque=None,<EOL>algorithm=None, stale=False):
d = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': realm,<EOL>'<STR_LIT>': nonce,<EOL>'<STR_LIT>': dump_header(qop)<EOL>}<EOL>if stale:<EOL><INDENT>d['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if opaque is not None:<EOL><INDENT>d['<STR_LIT>'] = opaque<EOL><DEDENT>if algorithm is not ...
Clear the auth info and enable digest auth.
f5880:c32:m2
def to_header(self):
d = dict(self)<EOL>auth_type = d.pop('<STR_LIT>', None) or '<STR_LIT>'<EOL>return '<STR_LIT>' % (auth_type.title(), '<STR_LIT:U+002CU+0020>'.join([<EOL>'<STR_LIT>' % (key, quote_header_value(value,<EOL>allow_token=key not in self._require_quoting))<EOL>for key, value in iteritems(d)<EOL>]))<EOL>
Convert the stored values into a WWW-Authenticate header.
f5880:c32:m3
def auth_property(name, doc=None):
def _set_value(self, value):<EOL><INDENT>if value is None:<EOL><INDENT>self.pop(name, None)<EOL><DEDENT>else:<EOL><INDENT>self[name] = str(value)<EOL><DEDENT><DEDENT>return property(lambda x: x.get(name), _set_value, doc=doc)<EOL>
A static helper function for subclasses to add extra authentication system 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 the regular prop...
f5880:c32:m6
@property<EOL><INDENT>def content_type(self):<DEDENT>
return self.headers.get('<STR_LIT>')<EOL>
The content-type sent in the header. Usually not available
f5880:c33:m2
@property<EOL><INDENT>def content_length(self):<DEDENT>
return int(self.headers.get('<STR_LIT>') or <NUM_LIT:0>)<EOL>
The content-length sent in the header. Usually not available
f5880:c33:m3
@property<EOL><INDENT>def mimetype(self):<DEDENT>
self._parse_content_type()<EOL>return self._parsed_content_type[<NUM_LIT:0>]<EOL>
Like :attr:`content_type` but without parameters (eg, without charset, type etc.). For example if the content type is ``text/html; charset=utf-8`` the mimetype would be ``'text/html'``. .. versionadded:: 0.7
f5880:c33:m4
@property<EOL><INDENT>def mimetype_params(self):<DEDENT>
self._parse_content_type()<EOL>return self._parsed_content_type[<NUM_LIT:1>]<EOL>
The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``. .. versionadded:: 0.7
f5880:c33:m5
def save(self, dst, buffer_size=<NUM_LIT>):
from shutil import copyfileobj<EOL>close_dst = False<EOL>if isinstance(dst, string_types):<EOL><INDENT>dst = open(dst, '<STR_LIT:wb>')<EOL>close_dst = True<EOL><DEDENT>try:<EOL><INDENT>copyfileobj(self.stream, dst, buffer_size)<EOL><DEDENT>finally:<EOL><INDENT>if close_dst:<EOL><INDENT>dst.close()<EOL><DEDENT><DEDENT>
Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. For secure file saving also have a look at :func:`...
f5880:c33:m6
def close(self):
try:<EOL><INDENT>self.stream.close()<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>
Close the underlying file if possible.
f5880:c33:m7
def responder(f):
return update_wrapper(lambda *a: f(*a)(*a[-<NUM_LIT:2>:]), f)<EOL>
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!')
f5881:m0
def get_current_url(environ, root_only=False, strip_querystring=False,<EOL>host_only=False, trusted_hosts=None):
tmp = [environ['<STR_LIT>'], '<STR_LIT>', get_host(environ, trusted_hosts)]<EOL>cat = tmp.append<EOL>if host_only:<EOL><INDENT>return uri_to_iri('<STR_LIT>'.join(tmp) + '<STR_LIT:/>')<EOL><DEDENT>cat(url_quote(wsgi_get_bytes(environ.get('<STR_LIT>', '<STR_LIT>'))).rstrip('<STR_LIT:/>'))<EOL>cat('<STR_LIT:/>')<EOL>if no...
A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug.test import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_cur...
f5881:m1
def host_is_trusted(hostname, trusted_list):
if not hostname:<EOL><INDENT>return False<EOL><DEDENT>if isinstance(trusted_list, string_types):<EOL><INDENT>trusted_list = [trusted_list]<EOL><DEDENT>def _normalize(hostname):<EOL><INDENT>if '<STR_LIT::>' in hostname:<EOL><INDENT>hostname = hostname.rsplit('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL><DEDENT>return _e...
Checks if a host is trusted against a list. This also takes care of port normalization. .. versionadded:: 0.9 :param hostname: the hostname to check :param trusted_list: a list of hostnames to check against. If a hostname starts with a dot it will match against ...
f5881:m2
def get_host(environ, trusted_hosts=None):
if '<STR_LIT>' in environ:<EOL><INDENT>rv = environ['<STR_LIT>'].split('<STR_LIT:U+002C>')[<NUM_LIT:0>].strip()<EOL><DEDENT>elif '<STR_LIT>' in environ:<EOL><INDENT>rv = environ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>rv = environ['<STR_LIT>']<EOL>if (environ['<STR_LIT>'], environ['<STR_LIT>']) notin (('<STR_LIT>', ...
Return the real host for the given WSGI environment. This takes care of the `X-Forwarded-Host` header. Optionally it verifies that the host is in a list of trusted hosts. If the host is not in there it will raise a :exc:`~werkzeug.exceptions.SecurityError`. :param environ: the WSGI environment to ge...
f5881:m3
def get_content_length(environ):
content_length = environ.get('<STR_LIT>')<EOL>if content_length is not None:<EOL><INDENT>try:<EOL><INDENT>return max(<NUM_LIT:0>, int(content_length))<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Returns the content length from the WSGI environment as integer. If it's not available `None` is returned. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the content length from.
f5881:m4
def get_input_stream(environ, safe_fallback=True):
stream = environ['<STR_LIT>']<EOL>content_length = get_content_length(environ)<EOL>if environ.get('<STR_LIT>'):<EOL><INDENT>return stream<EOL><DEDENT>if content_length is None:<EOL><INDENT>return safe_fallback and _empty_stream or stream<EOL><DEDENT>return LimitedStream(stream, content_length)<EOL>
Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. .. versionadded:: 0.9 :param environ: the WSGI environ ...
f5881:m5
def get_query_string(environ):
qs = wsgi_get_bytes(environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>return try_coerce_native(url_quote(qs, safe='<STR_LIT>'))<EOL>
Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the query str...
f5881:m6
def get_path_info(environ, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
path = wsgi_get_bytes(environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>return to_unicode(path, charset, errors, allow_none_charset=True)<EOL>
Returns the `PATH_INFO` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path fr...
f5881:m7
def get_script_name(environ, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
path = wsgi_get_bytes(environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>return to_unicode(path, charset, errors, allow_none_charset=True)<EOL>
Returns the `SCRIPT_NAME` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path ...
f5881:m8
def pop_path_info(environ, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
path = environ.get('<STR_LIT>')<EOL>if not path:<EOL><INDENT>return None<EOL><DEDENT>script_name = environ.get('<STR_LIT>', '<STR_LIT>')<EOL>old_path = path<EOL>path = path.lstrip('<STR_LIT:/>')<EOL>if path != old_path:<EOL><INDENT>script_name += '<STR_LIT:/>' * (len(old_path) - len(path))<EOL><DEDENT>if '<STR_LIT:/>' ...
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 the `charset` is set to `None` a bytestring is returned. If there are empty segments (``'/foo//bar``) these are ignored but properly pushed to the `SCRIPT_NAM...
f5881:m9
def peek_path_info(environ, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
segments = environ.get('<STR_LIT>', '<STR_LIT>').lstrip('<STR_LIT:/>').split('<STR_LIT:/>', <NUM_LIT:1>)<EOL>if segments:<EOL><INDENT>return to_unicode(wsgi_get_bytes(segments[<NUM_LIT:0>]),<EOL>charset, errors, allow_none_charset=True)<EOL><DEDENT>
Returns the next segment on the `PATH_INFO` or `None` if there is none. Works like :func:`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' If the `charset` is set to `None` ...
f5881:m10
def extract_path_info(environ_or_baseurl, path_or_url, charset='<STR_LIT:utf-8>',<EOL>errors='<STR_LIT:replace>', collapse_http_schemes=True):
def _normalize_netloc(scheme, netloc):<EOL><INDENT>parts = netloc.split(u'<STR_LIT:@>', <NUM_LIT:1>)[-<NUM_LIT:1>].split(u'<STR_LIT::>', <NUM_LIT:1>)<EOL>if len(parts) == <NUM_LIT:2>:<EOL><INDENT>netloc, port = parts<EOL>if (scheme == u'<STR_LIT:http>' and port == u'<STR_LIT>') or(scheme == u'<STR_LIT>' and port == u'<...
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info...
f5881:m11
def wrap_file(environ, file, buffer_size=<NUM_LIT>):
return environ.get('<STR_LIT>', FileWrapper)(file, buffer_size)<EOL>
Wraps a file. This uses the WSGI server's file wrapper if available or otherwise the generic :class:`FileWrapper`. .. versionadded:: 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 wan...
f5881:m12
def _make_chunk_iter(stream, limit, buffer_size):
if isinstance(stream, (bytes, bytearray, text_type)):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if not hasattr(stream, '<STR_LIT>'):<EOL><INDENT>for item in stream:<EOL><INDENT>if item:<EOL><INDENT>yield item<EOL><DEDENT><DEDENT>return<EOL><DEDENT>if not isinstance(stream, LimitedStream) and ...
Helper for the line and chunk iter functions.
f5881:m13
def make_line_iter(stream, limit=None, buffer_size=<NUM_LIT:10> * <NUM_LIT>):
_iter = _make_chunk_iter(stream, limit, buffer_size)<EOL>first_item = next(_iter, '<STR_LIT>')<EOL>if not first_item:<EOL><INDENT>return<EOL><DEDENT>s = make_literal_wrapper(first_item)<EOL>empty = s('<STR_LIT>')<EOL>cr = s('<STR_LIT:\r>')<EOL>lf = s('<STR_LIT:\n>')<EOL>crlf = s('<STR_LIT:\r\n>')<EOL>_iter = chain((fir...
Safely iterates line-based over an input stream. If the input stream is not a :class:`LimitedStream` the `limit` parameter is mandatory. This uses the stream's :meth:`~file.read` method internally as opposite to the :meth:`~file.readline` method that is unsafe and can only be used in violation of the ...
f5881:m14
def make_chunk_iter(stream, separator, limit=None, buffer_size=<NUM_LIT:10> * <NUM_LIT>):
_iter = _make_chunk_iter(stream, limit, buffer_size)<EOL>first_item = next(_iter, '<STR_LIT>')<EOL>if not first_item:<EOL><INDENT>return<EOL><DEDENT>_iter = chain((first_item,), _iter)<EOL>if isinstance(first_item, text_type):<EOL><INDENT>separator = to_unicode(separator)<EOL>_split = re.compile(r'<STR_LIT>' % re.escap...
Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline markers. .. versionadded:: 0.8 .. versionadded:: 0.9 added support for iterators as input stre...
f5881:m15
def is_allowed(self, filename):
return True<EOL>
Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten.
f5881:c0:m1
@property<EOL><INDENT>def is_exhausted(self):<DEDENT>
return self._pos >= self.limit<EOL>
If the stream is exhausted this attribute is `True`.
f5881:c4:m2
def on_exhausted(self):
<EOL>return self._read(<NUM_LIT:0>)<EOL>
This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function.
f5881:c4:m3
def on_disconnect(self):
from werkzeug.exceptions import ClientDisconnected<EOL>raise ClientDisconnected()<EOL>
What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised.
f5881:c4:m4
def exhaust(self, chunk_size=<NUM_LIT> * <NUM_LIT:64>):
to_read = self.limit - self._pos<EOL>chunk = chunk_size<EOL>while to_read > <NUM_LIT:0>:<EOL><INDENT>chunk = min(to_read, chunk)<EOL>self.read(chunk)<EOL>to_read -= chunk<EOL><DEDENT>
Exhaust the stream. This consumes all the data left until the limit is reached. :param chunk_size: the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results.
f5881:c4:m5
def read(self, size=None):
if self._pos >= self.limit:<EOL><INDENT>return self.on_exhausted()<EOL><DEDENT>if size is None or size == -<NUM_LIT:1>: <EOL><INDENT>size = self.limit<EOL><DEDENT>to_read = min(self.limit - self._pos, size)<EOL>try:<EOL><INDENT>read = self._read(to_read)<EOL><DEDENT>except (IOError, ValueError):<EOL><INDENT>return sel...
Read `size` bytes or if size is not provided everything is read. :param size: the number of bytes read.
f5881:c4:m6
def readline(self, size=None):
if self._pos >= self.limit:<EOL><INDENT>return self.on_exhausted()<EOL><DEDENT>if size is None:<EOL><INDENT>size = self.limit - self._pos<EOL><DEDENT>else:<EOL><INDENT>size = min(size, self.limit - self._pos)<EOL><DEDENT>try:<EOL><INDENT>line = self._readline(size)<EOL><DEDENT>except (ValueError, IOError):<EOL><INDENT>...
Reads one line from the stream.
f5881:c4:m7
def readlines(self, size=None):
last_pos = self._pos<EOL>result = []<EOL>if size is not None:<EOL><INDENT>end = min(self.limit, last_pos + size)<EOL><DEDENT>else:<EOL><INDENT>end = self.limit<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>if size is not None:<EOL><INDENT>size -= last_pos - self._pos<EOL><DEDENT>if self._pos >= end:<EOL><INDENT>break<EOL>...
Reads a file into a list of strings. It calls :meth:`readline` until the file is read to the end. It does support the optional `size` argument if the underlaying stream supports it for `readline`.
f5881:c4:m8
def tell(self):
return self._pos<EOL>
Returns the position of the stream. .. versionadded:: 0.9
f5881:c4:m9
def __dir__(self):
result = list(new_module.__all__)<EOL>result.extend(('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'))<EOL>return result<EOL>
Just show what we want to show.
f5882:c0:m1
def url_parse(url, scheme=None, allow_fragments=True):
s = make_literal_wrapper(url)<EOL>is_text_based = isinstance(url, text_type)<EOL>if scheme is None:<EOL><INDENT>scheme = s('<STR_LIT>')<EOL><DEDENT>netloc = query = fragment = s('<STR_LIT>')<EOL>i = url.find(s('<STR_LIT::>'))<EOL>if i > <NUM_LIT:0> and _scheme_re.match(to_native(url[:i], errors='<STR_LIT:replace>')):<E...
Parses a URL from a string into a :class:`URL` tuple. If the URL is lacking a scheme it can be provided as second argument. Otherwise, it is ignored. Optionally fragments can be stripped from the URL by setting `allow_fragments` to `False`. The inverse of this function is :func:`url_unparse`. :p...
f5883:m3
def url_quote(string, charset='<STR_LIT:utf-8>', errors='<STR_LIT:strict>', safe='<STR_LIT>'):
if not isinstance(string, (text_type, bytes, bytearray)):<EOL><INDENT>string = text_type(string)<EOL><DEDENT>if isinstance(string, text_type):<EOL><INDENT>string = string.encode(charset, errors)<EOL><DEDENT>if isinstance(safe, text_type):<EOL><INDENT>safe = safe.encode(charset, errors)<EOL><DEDENT>safe = frozenset(byte...
URL encode a single string with a given encoding. :param s: the string to quote. :param charset: the charset to be used. :param safe: an optional sequence of safe characters.
f5883:m4
def url_quote_plus(string, charset='<STR_LIT:utf-8>', errors='<STR_LIT:strict>', safe='<STR_LIT>'):
return url_quote(string, charset, errors, safe + '<STR_LIT:U+0020>').replace('<STR_LIT:U+0020>', '<STR_LIT:+>')<EOL>
URL encode a single string with the given encoding and convert whitespace to "+". :param s: The string to quote. :param charset: The charset to be used. :param safe: An optional sequence of safe characters.
f5883:m5
def url_unparse(components):
scheme, netloc, path, query, fragment =normalize_string_tuple(components)<EOL>s = make_literal_wrapper(scheme)<EOL>url = s('<STR_LIT>')<EOL>if netloc or (scheme and path.startswith(s('<STR_LIT:/>'))):<EOL><INDENT>if path and path[:<NUM_LIT:1>] != s('<STR_LIT:/>'):<EOL><INDENT>path = s('<STR_LIT:/>') + path<EOL><DEDENT>...
The reverse operation to :meth:`url_parse`. This accepts arbitrary as well as :class:`URL` tuples and returns a URL as a string. :param components: the parsed URL as tuple which should be converted into a URL string.
f5883:m6
def url_unquote(string, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>', unsafe='<STR_LIT>'):
rv = _unquote_to_bytes(string, unsafe)<EOL>if charset is not None:<EOL><INDENT>rv = rv.decode(charset, errors)<EOL><DEDENT>return rv<EOL>
URL decode a single string with a given encoding. If the charset is set to `None` no unicode decoding is performed and raw bytes are returned. :param s: the string to unquote. :param charset: the charset of the query string. If set to `None` no unicode decoding will take place. ...
f5883:m7
def url_unquote_plus(s, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
if isinstance(s, text_type):<EOL><INDENT>s = s.replace(u'<STR_LIT:+>', u'<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>s = s.replace(b'<STR_LIT:+>', b'<STR_LIT:U+0020>')<EOL><DEDENT>return url_unquote(s, charset, errors)<EOL>
URL decode a single string with the given `charset` and decode "+" 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 :exc:`HTTPUnicodeError` is raised. :param s: The string to unquote. ...
f5883:m8
def url_fix(s, charset='<STR_LIT:utf-8>'):
scheme, netloc, path, qs, anchor = url_parse(to_unicode(s, charset, '<STR_LIT:replace>'))<EOL>path = url_quote(path, charset, safe='<STR_LIT>')<EOL>qs = url_quote_plus(qs, charset, safe='<STR_LIT>')<EOL>return to_native(url_unparse((scheme, netloc, path, qs, anchor)))<EOL>
r"""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)') 'ht...
f5883:m9
def uri_to_iri(uri, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
if isinstance(uri, tuple):<EOL><INDENT>uri = url_unparse(uri)<EOL><DEDENT>uri = url_parse(to_unicode(uri, charset))<EOL>path = url_unquote(uri.path, charset, errors, '<STR_LIT>')<EOL>query = url_unquote(uri.query, charset, errors, '<STR_LIT>')<EOL>fragment = url_unquote(uri.fragment, charset, errors, '<STR_LIT>')<EOL>r...
r""" 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%[email protected]/p%C3%A5th') u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th' Query strings are left unchan...
f5883:m10
def iri_to_uri(iri, charset='<STR_LIT:utf-8>', errors='<STR_LIT:strict>'):
if isinstance(iri, tuple):<EOL><INDENT>iri = url_unparse(iri)<EOL><DEDENT>iri = url_parse(to_unicode(iri, charset, errors))<EOL>netloc = iri.encode_netloc().decode('<STR_LIT:ascii>')<EOL>path = url_quote(iri.path, charset, errors, '<STR_LIT>')<EOL>query = url_quote(iri.query, charset, errors, '<STR_LIT>')<EOL>fragment ...
r""" Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always uses utf-8 URLs internally because this is what browsers and HTTP do as well. In some places where it accepts an URL it also accepts a unicode IRI and converts it into a URI. Examples for IRI versus URI: >>> iri_to...
f5883:m11
def url_decode(s, charset='<STR_LIT:utf-8>', decode_keys=False, include_empty=True,<EOL>errors='<STR_LIT:replace>', separator='<STR_LIT:&>', cls=None):
if cls is None:<EOL><INDENT>cls = MultiDict<EOL><DEDENT>if isinstance(s, text_type) and not isinstance(separator, text_type):<EOL><INDENT>separator = separator.decode(charset or '<STR_LIT:ascii>')<EOL><DEDENT>elif isinstance(s, bytes) and not isinstance(separator, bytes):<EOL><INDENT>separator = separator.encode(charse...
Parse a querystring and return it as :class:`MultiDict`. There is a difference in key decoding on different Python versions. On Python 3 keys will always be fully decoded whereas on Python 2, keys will remain bytestrings if they fit into ASCII. On 2.x keys can be forced to be unicode by setting `decode_keys` to `Tru...
f5883:m12
def url_decode_stream(stream, charset='<STR_LIT:utf-8>', decode_keys=False,<EOL>include_empty=True, errors='<STR_LIT:replace>', separator='<STR_LIT:&>',<EOL>cls=None, limit=None, return_iterator=False):
from werkzeug.wsgi import make_chunk_iter<EOL>if return_iterator:<EOL><INDENT>cls = lambda x: x<EOL><DEDENT>elif cls is None:<EOL><INDENT>cls = MultiDict<EOL><DEDENT>pair_iter = make_chunk_iter(stream, separator, limit)<EOL>return cls(_url_decode_impl(pair_iter, charset, decode_keys,<EOL>include_empty, errors))<EOL>
Works like :func:`url_decode` but decodes a stream. The behavior of stream and limit follows functions like :func:`~werkzeug.wsgi.make_line_iter`. The generator of pairs is directly fed to the `cls` so you can consume the data while it's parsed. .. versionadded:: 0.8 :param stream: a stream ...
f5883:m13
def url_encode(obj, charset='<STR_LIT:utf-8>', encode_keys=False, sort=False, key=None,<EOL>separator=b'<STR_LIT:&>'):
separator = to_native(separator, '<STR_LIT:ascii>')<EOL>return separator.join(_url_encode_impl(obj, charset, encode_keys, sort, key))<EOL>
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 defaul...
f5883:m15
def url_encode_stream(obj, stream=None, charset='<STR_LIT:utf-8>', encode_keys=False,<EOL>sort=False, key=None, separator=b'<STR_LIT:&>'):
separator = to_native(separator, '<STR_LIT:ascii>')<EOL>gen = _url_encode_impl(obj, charset, encode_keys, sort, key)<EOL>if stream is None:<EOL><INDENT>return gen<EOL><DEDENT>for idx, chunk in enumerate(gen):<EOL><INDENT>if idx:<EOL><INDENT>stream.write(separator)<EOL><DEDENT>stream.write(chunk)<EOL><DEDENT>
Like :meth:`url_encode` but writes the results to a stream object. If the stream is `None` a generator over all encoded pairs is returned. .. versionadded:: 0.8 :param obj: the object to encode into a query string. :param stream: a stream to write the encoded object into or `None` if ...
f5883:m16
def url_join(base, url, allow_fragments=True):
if isinstance(base, tuple):<EOL><INDENT>base = url_unparse(base)<EOL><DEDENT>if isinstance(url, tuple):<EOL><INDENT>url = url_unparse(url)<EOL><DEDENT>base, url = normalize_string_tuple((base, url))<EOL>s = make_literal_wrapper(base)<EOL>if not base:<EOL><INDENT>return url<EOL><DEDENT>if not url:<EOL><INDENT>return bas...
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. :param base: the base URL for the join operation. :param url: the URL to join. :param allow_fragments: indicates whether fragments should be allowed.
f5883:m17
def replace(self, **kwargs):
return self._replace(**kwargs)<EOL>
Return an URL with the same values, except for those parameters given new values by whichever keyword arguments are specified.
f5883:c0:m0
@property<EOL><INDENT>def host(self):<DEDENT>
return self._split_host()[<NUM_LIT:0>]<EOL>
The host part of the URL if available, otherwise `None`. The host is either the hostname or the IP address mentioned in the URL. It will not contain the port.
f5883:c0:m1
@property<EOL><INDENT>def ascii_host(self):<DEDENT>
rv = self.host<EOL>if rv is not None and isinstance(rv, text_type):<EOL><INDENT>rv = _encode_idna(rv)<EOL><DEDENT>return to_native(rv, '<STR_LIT:ascii>', '<STR_LIT:ignore>')<EOL>
Works exactly like :attr:`host` but will return a result that is restricted to ASCII. If it finds a netloc that is not ASCII it will attempt to idna decode it. This is useful for socket operations when the URL might include internationalized characters.
f5883:c0:m2
@property<EOL><INDENT>def port(self):<DEDENT>
try:<EOL><INDENT>rv = int(to_native(self._split_host()[<NUM_LIT:1>]))<EOL>if <NUM_LIT:0> <= rv <= <NUM_LIT>:<EOL><INDENT>return rv<EOL><DEDENT><DEDENT>except (ValueError, TypeError):<EOL><INDENT>pass<EOL><DEDENT>
The port in the URL as an integer if it was present, `None` otherwise. This does not fill in default ports.
f5883:c0:m3
@property<EOL><INDENT>def auth(self):<DEDENT>
return self._split_netloc()[<NUM_LIT:0>]<EOL>
The authentication part in the URL if available, `None` otherwise.
f5883:c0:m4
@property<EOL><INDENT>def username(self):<DEDENT>
rv = self._split_auth()[<NUM_LIT:0>]<EOL>if rv is not None:<EOL><INDENT>return _url_unquote_legacy(rv)<EOL><DEDENT>
The username if it was part of the URL, `None` otherwise. This undergoes URL decoding and will always be a unicode string.
f5883:c0:m5
@property<EOL><INDENT>def raw_username(self):<DEDENT>
return self._split_auth()[<NUM_LIT:0>]<EOL>
The username if it was part of the URL, `None` otherwise. Unlike :attr:`username` this one is not being decoded.
f5883:c0:m6
@property<EOL><INDENT>def password(self):<DEDENT>
rv = self._split_auth()[<NUM_LIT:1>]<EOL>if rv is not None:<EOL><INDENT>return _url_unquote_legacy(rv)<EOL><DEDENT>
The password if it was part of the URL, `None` otherwise. This undergoes URL decoding and will always be a unicode string.
f5883:c0:m7
@property<EOL><INDENT>def raw_password(self):<DEDENT>
return self._split_auth()[<NUM_LIT:1>]<EOL>
The password if it was part of the URL, `None` otherwise. Unlike :attr:`password` this one is not being decoded.
f5883:c0:m8
def decode_query(self, *args, **kwargs):
return url_decode(self.query, *args, **kwargs)<EOL>
Decodes the query part of the URL. Ths is a shortcut for calling :func:`url_decode` on the query argument. The arguments and keyword arguments are forwarded to :func:`url_decode` unchanged.
f5883:c0:m9
def join(self, *args, **kwargs):
return url_parse(url_join(self, *args, **kwargs))<EOL>
Joins this URL with another one. This is just a convenience function for calling into :meth:`url_join` and then parsing the return value again.
f5883:c0:m10
def to_url(self):
return url_unparse(self)<EOL>
Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling :meth:`url_unparse` for this URL.
f5883:c0:m11
def decode_netloc(self):
rv = _decode_idna(self.host or '<STR_LIT>')<EOL>if '<STR_LIT::>' in rv:<EOL><INDENT>rv = '<STR_LIT>' % rv<EOL><DEDENT>port = self.port<EOL>if port is not None:<EOL><INDENT>rv = '<STR_LIT>' % (rv, port)<EOL><DEDENT>auth = '<STR_LIT::>'.join(filter(None, [<EOL>_url_unquote_legacy(self.raw_username or '<STR_LIT>', '<STR_L...
Decodes the netloc part into a string.
f5883:c0:m12
def to_uri_tuple(self):
return url_parse(iri_to_uri(self).encode('<STR_LIT:ascii>'))<EOL>
Returns a :class:`BytesURL` tuple that holds a URI. This will encode all the information in the URL properly to ASCII using the rules a web browser would follow. It's usually more interesting to directly call :meth:`iri_to_uri` which will return a string.
f5883:c0:m13
def to_iri_tuple(self):
return url_parse(uri_to_iri(self))<EOL>
Returns a :class:`URL` tuple that holds a IRI. This will try to decode as much information as possible in the URL without losing information similar to how a web browser does it for the URL bar. It's usually more interesting to directly call :meth:`uri_to_iri` which will return...
f5883:c0:m14
def encode_netloc(self):
rv = self.ascii_host or '<STR_LIT>'<EOL>if '<STR_LIT::>' in rv:<EOL><INDENT>rv = '<STR_LIT>' % rv<EOL><DEDENT>port = self.port<EOL>if port is not None:<EOL><INDENT>rv = '<STR_LIT>' % (rv, port)<EOL><DEDENT>auth = '<STR_LIT::>'.join(filter(None, [<EOL>url_quote(self.raw_username or '<STR_LIT>', '<STR_LIT:utf-8>', '<STR_...
Encodes the netloc part to an ASCII safe URL as bytes.
f5883:c1:m1
def encode(self, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
return BytesURL(<EOL>self.scheme.encode('<STR_LIT:ascii>'),<EOL>self.encode_netloc(),<EOL>self.path.encode(charset, errors),<EOL>self.query.encode(charset, errors),<EOL>self.fragment.encode(charset, errors)<EOL>)<EOL>
Encodes the URL to a tuple made out of bytes. The charset is only being used for the path, query and fragment.
f5883:c1:m2
def encode_netloc(self):
return self.netloc<EOL>
Returns the netloc unchanged as bytes.
f5883:c2:m1
def decode(self, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>'):
return URL(<EOL>self.scheme.decode('<STR_LIT:ascii>'),<EOL>self.decode_netloc(),<EOL>self.path.decode(charset, errors),<EOL>self.query.decode(charset, errors),<EOL>self.fragment.decode(charset, errors)<EOL>)<EOL>
Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment.
f5883:c2:m2
def wsgi_to_bytes(data):
if isinstance(data, bytes):<EOL><INDENT>return data<EOL><DEDENT>return data.encode('<STR_LIT>')<EOL>
coerce wsgi unicode represented bytes to real ones
f5884:m0
def quote_header_value(value, extra_chars='<STR_LIT>', allow_token=True):
if isinstance(value, bytes):<EOL><INDENT>value = bytes_to_wsgi(value)<EOL><DEDENT>value = str(value)<EOL>if allow_token:<EOL><INDENT>token_chars = _token_chars | set(extra_chars)<EOL>if set(value).issubset(token_chars):<EOL><INDENT>return value<EOL><DEDENT><DEDENT>return '<STR_LIT>' % value.replace('<STR_LIT:\\>', '<ST...
Quote a header value if necessary. .. versionadded:: 0.5 :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned unchanged.
f5884:m2
def unquote_header_value(value, is_filename=False):
if value and value[<NUM_LIT:0>] == value[-<NUM_LIT:1>] == '<STR_LIT:">':<EOL><INDENT>value = value[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>if not is_filename or value[:<NUM_LIT:2>] != '<STR_LIT>':<EOL><INDENT>return value.replace('<STR_LIT>', '<STR_LIT:\\>').replace('<STR_LIT>', '<STR_LIT:">')<EOL><DEDENT><DEDENT>return value<EO...
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. .. versionadded:: 0.5 :param value: the header value to unquote.
f5884:m3
def dump_options_header(header, options):
segments = []<EOL>if header is not None:<EOL><INDENT>segments.append(header)<EOL><DEDENT>for key, value in iteritems(options):<EOL><INDENT>if value is None:<EOL><INDENT>segments.append(key)<EOL><DEDENT>else:<EOL><INDENT>segments.append('<STR_LIT>' % (key, quote_header_value(value)))<EOL><DEDENT><DEDENT>return '<STR_LIT...
The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append.
f5884:m4
def dump_header(iterable, allow_token=True):
if isinstance(iterable, dict):<EOL><INDENT>items = []<EOL>for key, value in iteritems(iterable):<EOL><INDENT>if value is None:<EOL><INDENT>items.append(key)<EOL><DEDENT>else:<EOL><INDENT>items.append('<STR_LIT>' % (<EOL>key,<EOL>quote_header_value(value, allow_token=allow_token)<EOL>))<EOL><DEDENT><DEDENT><DEDENT>else:...
Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_header({'foo': 'bar baz'}) 'foo="bar baz"' >>> du...
f5884:m5
def parse_list_header(value):
result = []<EOL>for item in _parse_list_header(value):<EOL><INDENT>if item[:<NUM_LIT:1>] == item[-<NUM_LIT:1>:] == '<STR_LIT:">':<EOL><INDENT>item = unquote_header_value(item[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL><DEDENT>result.append(item)<EOL><DEDENT>return result<EOL>
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. It ba...
f5884:m6
def parse_dict_header(value, cls=dict):
result = cls()<EOL>if not isinstance(value, text_type):<EOL><INDENT>value = bytes_to_wsgi(value)<EOL><DEDENT>for item in _parse_list_header(value):<EOL><INDENT>if '<STR_LIT:=>' not in item:<EOL><INDENT>result[item] = None<EOL>continue<EOL><DEDENT>name, value = item.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>if value[:<NUM_L...
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` arugment): >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True ...
f5884:m7
def parse_options_header(value):
def _tokenize(string):<EOL><INDENT>for match in _option_header_piece_re.finditer(string):<EOL><INDENT>key, value = match.groups()<EOL>key = unquote_header_value(key)<EOL>if value is not None:<EOL><INDENT>value = unquote_header_value(value, key == '<STR_LIT:filename>')<EOL><DEDENT>yield key, value<EOL><DEDENT><DEDENT>if...
Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that use a slightly different format. For these headers u...
f5884:m8
def parse_accept_header(value, cls=None):
if cls is None:<EOL><INDENT>cls = Accept<EOL><DEDENT>if not value:<EOL><INDENT>return cls(None)<EOL><DEDENT>result = []<EOL>for match in _accept_re.finditer(value):<EOL><INDENT>quality = match.group(<NUM_LIT:2>)<EOL>if not quality:<EOL><INDENT>quality = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>quality = max(min(float(...
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 :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality with some additional accessor methods). The s...
f5884:m9
def parse_cache_control_header(value, on_update=None, cls=None):
if cls is None:<EOL><INDENT>cls = RequestCacheControl<EOL><DEDENT>if not value:<EOL><INDENT>return cls(None, on_update)<EOL><DEDENT>return cls(parse_dict_header(value), on_update)<EOL>
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. .. versionadded:: 0.5 The `cls` was added. If not specified an immutable :class:`~werkzeug.datastructures.Reques...
f5884:m10
def parse_set_header(value, on_update=None):
if not value:<EOL><INDENT>return HeaderSet(None, on_update)<EOL><DEDENT>return HeaderSet(parse_list_header(value), on_update)<EOL>
Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object: >>> hs = parse_set_header('token, "quoted value"') The return value is an object that treats the items case-insensitively and keeps the order of the items: >>> 'TOKEN' in hs True >>> hs.index('quoted ...
f5884:m11
def parse_authorization_header(value):
if not value:<EOL><INDENT>return<EOL><DEDENT>value = wsgi_to_bytes(value)<EOL>try:<EOL><INDENT>auth_type, auth_info = value.split(None, <NUM_LIT:1>)<EOL>auth_type = auth_type.lower()<EOL><DEDENT>except ValueError:<EOL><INDENT>return<EOL><DEDENT>if auth_type == b'<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>username, passwo...
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 :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization header to parse. :return: a :class:`~werkze...
f5884:m12
def parse_www_authenticate_header(value, on_update=None):
if not value:<EOL><INDENT>return WWWAuthenticate(on_update=on_update)<EOL><DEDENT>try:<EOL><INDENT>auth_type, auth_info = value.split(None, <NUM_LIT:1>)<EOL>auth_type = auth_type.lower()<EOL><DEDENT>except (ValueError, AttributeError):<EOL><INDENT>return WWWAuthenticate(value.strip().lower(), on_update=on_update)<EOL><...
Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` ...
f5884:m13
def parse_if_range_header(value):
if not value:<EOL><INDENT>return IfRange()<EOL><DEDENT>date = parse_date(value)<EOL>if date is not None:<EOL><INDENT>return IfRange(date=date)<EOL><DEDENT>return IfRange(unquote_etag(value)[<NUM_LIT:0>])<EOL>
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7
f5884:m14
def parse_range_header(value, make_inclusive=True):
if not value or '<STR_LIT:=>' not in value:<EOL><INDENT>return None<EOL><DEDENT>ranges = []<EOL>last_end = <NUM_LIT:0><EOL>units, rng = value.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>units = units.strip().lower()<EOL>for item in rng.split('<STR_LIT:U+002C>'):<EOL><INDENT>item = item.strip()<EOL>if '<STR_LIT:->' not in ite...
Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7
f5884:m15
def parse_content_range_header(value, on_update=None):
if value is None:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>units, rangedef = (value or '<STR_LIT>').strip().split(None, <NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT>if '<STR_LIT:/>' not in rangedef:<EOL><INDENT>return None<EOL><DEDENT>rng, length = rangedef.split('<STR_LIT...
Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible. .. versionadded:: 0.7 :param value: a content range header to be parsed. :param on_update: an optional callable that is called every time a value on the :c...
f5884:m16
def quote_etag(etag, weak=False):
if '<STR_LIT:">' in etag:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>etag = '<STR_LIT>' % etag<EOL>if weak:<EOL><INDENT>etag = '<STR_LIT>' + etag<EOL><DEDENT>return etag<EOL>
Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak".
f5884:m17
def unquote_etag(etag):
if not etag:<EOL><INDENT>return None, None<EOL><DEDENT>etag = etag.strip()<EOL>weak = False<EOL>if etag[:<NUM_LIT:2>] in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>weak = True<EOL>etag = etag[<NUM_LIT:2>:]<EOL><DEDENT>if etag[:<NUM_LIT:1>] == etag[-<NUM_LIT:1>:] == '<STR_LIT:">':<EOL><INDENT>etag = etag[<NUM_LIT:1>:-<NUM_...
Unquote a single etag: >>> unquote_etag('w/"bar"') ('bar', True) >>> unquote_etag('"bar"') ('bar', False) :param etag: the etag identifier to unquote. :return: a ``(etag, weak)`` tuple.
f5884:m18
def parse_etags(value):
if not value:<EOL><INDENT>return ETags()<EOL><DEDENT>strong = []<EOL>weak = []<EOL>end = len(value)<EOL>pos = <NUM_LIT:0><EOL>while pos < end:<EOL><INDENT>match = _etag_re.match(value, pos)<EOL>if match is None:<EOL><INDENT>break<EOL><DEDENT>is_weak, quoted, raw = match.groups()<EOL>if raw == '<STR_LIT:*>':<EOL><INDENT...
Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object.
f5884:m19
def generate_etag(data):
return md5(data).hexdigest()<EOL>
Generate an etag for some data.
f5884:m20
def parse_date(value):
if value:<EOL><INDENT>t = parsedate_tz(value.strip())<EOL>if t is not None:<EOL><INDENT>try:<EOL><INDENT>year = t[<NUM_LIT:0>]<EOL>if year >= <NUM_LIT:0> and year <= <NUM_LIT>:<EOL><INDENT>year += <NUM_LIT><EOL><DEDENT>elif year >= <NUM_LIT> and year <= <NUM_LIT>:<EOL><INDENT>year += <NUM_LIT><EOL><DEDENT>return dateti...
Parse one of the following date formats into a datetime object: .. sourcecode:: text 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 fail...
f5884:m21
def _dump_date(d, delim):
if d is None:<EOL><INDENT>d = gmtime()<EOL><DEDENT>elif isinstance(d, datetime):<EOL><INDENT>d = d.utctimetuple()<EOL><DEDENT>elif isinstance(d, (integer_types, float)):<EOL><INDENT>d = gmtime(d)<EOL><DEDENT>return '<STR_LIT>' % (<EOL>('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_...
Used for `http_date` and `cookie_date`.
f5884:m22
def cookie_date(expires=None):
return _dump_date(expires, '<STR_LIT:->')<EOL>
Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ...
f5884:m23
def http_date(timestamp=None):
return _dump_date(timestamp, '<STR_LIT:U+0020>')<EOL>
Formats the time to match the RFC1123 date format. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS...
f5884:m24
def is_resource_modified(environ, etag=None, data=None, last_modified=None):
if etag is None and data is not None:<EOL><INDENT>etag = generate_etag(data)<EOL><DEDENT>elif data is not None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if environ['<STR_LIT>'] not in ('<STR_LIT:GET>', '<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>unmodified = False<EOL>if isinstance(last_modified, str...
Convenience method for conditional requests. :param environ: the WSGI environment of the request to be checked. :param etag: the etag for the response for comparison. :param data: or alternatively the data of the response to automatically generate an etag using :func:`generate_etag`. :...
f5884:m25
def remove_entity_headers(headers, allowed=('<STR_LIT>', '<STR_LIT>')):
allowed = set(x.lower() for x in allowed)<EOL>headers[:] = [(key, value) for key, value in headers if<EOL>not is_entity_header(key) or key.lower() in allowed]<EOL>
Remove all entity headers from a list or :class:`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. .. versionchanged:: 0.5 ...
f5884:m26
def remove_hop_by_hop_headers(headers):
headers[:] = [(key, value) for key, value in headers if<EOL>not is_hop_by_hop_header(key)]<EOL>
Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or :class:`Headers` object. This operation works in-place. .. versionadded:: 0.5 :param headers: a list or :class:`Headers` object.
f5884:m27
def is_entity_header(header):
return header.lower() in _entity_headers<EOL>
Check if a header is an entity header. .. versionadded:: 0.5 :param header: the header to test. :return: `True` if it's an entity header, `False` otherwise.
f5884:m28
def is_hop_by_hop_header(header):
return header.lower() in _hop_by_hop_headers<EOL>
Check if a header is an HTTP/1.1 "Hop-by-Hop" header. .. versionadded:: 0.5 :param header: the header to test. :return: `True` if it's an entity header, `False` otherwise.
f5884:m29
def parse_cookie(header, charset='<STR_LIT:utf-8>', errors='<STR_LIT:replace>', cls=None):
if isinstance(header, dict):<EOL><INDENT>header = header.get('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif header is None:<EOL><INDENT>header = '<STR_LIT>'<EOL><DEDENT>if isinstance(header, text_type):<EOL><INDENT>header = header.encode('<STR_LIT>', '<STR_LIT:replace>')<EOL><DEDENT>if cls is None:<EOL><INDENT>cls = TypeCo...
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 :exc:`HTTPUnicodeError` is raised. .. versionchanged:: 0.5 This function now returns a :clas...
f5884:m30