werkzeug.urls
werkzeug.urls
used to provide several wrapper functions for Python 2
urlparse, whose main purpose were to work around the behavior of the Py2
stdlib and its lack of unicode support. While this was already a somewhat
inconvenient situation, it got even more complicated because Python 3’s
urllib.parse
actually does handle unicode properly. In other words,
this module would wrap two libraries with completely different behavior. So
now this module contains a 2-and-3-compatible backport of Python 3’s
urllib.parse
, which is mostly API-compatible.
- 2014 by the Werkzeug Team, see AUTHORS for more details.
class werkzeug.urls.BaseURL
Superclass of URL
and BytesURL
.
ascii_host
Works exactly like 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.
auth
The authentication part in the URL if available, [UNKNOWN NODE title_reference] otherwise.
decode_netloc()
Decodes the netloc part into a string.
decode_query(*args, **kwargs)
Decodes the query part of the URL. Ths is a shortcut for
calling url_decode()
on the query argument. The arguments and
keyword arguments are forwarded to url_decode()
unchanged.
get_file_location(pathformat=None)
Returns a tuple with the location of the file in the form
(server, location)
. If the netloc is empty in the URL or
points to localhost, it’s represented as None
.
The [UNKNOWN NODE title_reference] by default is autodetection but needs to be set
when working with URLs of a specific system. The supported values
are 'windows'
when working with Windows or DOS paths and
'posix'
when working with posix paths.
If the URL does not point to to a local file, the server and location
are both represented as None
.
'windows'
and 'posix'
are
supported. Defaults to None
which is
autodetect.host
The host part of the URL if available, otherwise [UNKNOWN NODE title_reference]. The host is either the hostname or the IP address mentioned in the URL. It will not contain the port.
join(*args, **kwargs)
Joins this URL with another one. This is just a convenience
function for calling into url_join()
and then parsing the
return value again.
password
The password if it was part of the URL, [UNKNOWN NODE title_reference] otherwise. This undergoes URL decoding and will always be a unicode string.
port
The port in the URL as an integer if it was present, [UNKNOWN NODE title_reference] otherwise. This does not fill in default ports.
raw_password
The password if it was part of the URL, [UNKNOWN NODE title_reference] otherwise.
Unlike password
this one is not being decoded.
raw_username
The username if it was part of the URL, [UNKNOWN NODE title_reference] otherwise.
Unlike username
this one is not being decoded.
replace(**kwargs)
Return an URL with the same values, except for those parameters given new values by whichever keyword arguments are specified.
to_iri_tuple()
Returns a 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 uri_to_iri()
which
will return a string.
to_uri_tuple()
Returns a 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 iri_to_uri()
which
will return a string.
to_url()
Returns a URL string or bytes depending on the type of the
information stored. This is just a convenience function
for calling url_unparse()
for this URL.
username
The username if it was part of the URL, [UNKNOWN NODE title_reference] otherwise. This undergoes URL decoding and will always be a unicode string.
class werkzeug.urls.BytesURL
Represents a parsed URL in bytes.
decode(charset='utf-8', errors='replace')
Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment.
encode_netloc()
Returns the netloc unchanged as bytes.
class werkzeug.urls.Href(base='./', charset='utf-8', sort=False, key=None)
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:
[UNKNOWN NODE doctest_block]If any of the arguments (positional or keyword) evaluates to [UNKNOWN NODE title_reference] 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:
Combining of both methods is not allowed:
[UNKNOWN NODE doctest_block]Accessing attributes on the href object creates a new href object with the attribute name as prefix:
[UNKNOWN NODE doctest_block]If [UNKNOWN NODE title_reference] is set to [UNKNOWN NODE title_reference] the items are sorted by [UNKNOWN NODE title_reference] or the default sorting algorithm:
[UNKNOWN NODE doctest_block]New in version 0.5: [UNKNOWN NODE title_reference] and [UNKNOWN NODE title_reference] were added.
class werkzeug.urls.URL
Represents a parsed URL. This behaves like a regular tuple but also has some extra attributes that give further insight into the URL.
encode(charset='utf-8', errors='replace')
Encodes the URL to a tuple made out of bytes. The charset is only being used for the path, query and fragment.
encode_netloc()
Encodes the netloc part to an ASCII safe URL as bytes.
werkzeug.urls.iri_to_uri(iri, charset='utf-8', errors='strict', safe_conversion=False)
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:
[UNKNOWN NODE doctest_block]There is a general problem with IRI and URI conversion with some protocols that appear in the wild that are in violation of the URI specification. In places where Werkzeug goes through a forced IRI to URI conversion it will set the [UNKNOWN NODE title_reference] flag which will not perform a conversion if the end result is already ASCII. This can mean that the return value is not an entirely correct URI but it will not destroy such invalid URLs in the process.
As an example consider the following two IRIs:
magnet:?xt=uri:whatever
itms-services://?action=download-manifest
The internal representation after parsing of those URLs is the same and there is no way to reconstruct the original one. If safe conversion is enabled however this function becomes a noop for both of those strings as they both can be considered URIs.
New in version 0.6.
Changed in version 0.9.6: The [UNKNOWN NODE title_reference] parameter was added.
- iri – The IRI to convert.
- charset – The charset for the URI.
- safe_conversion – indicates if a safe conversion should take place. For more information see the explanation above.
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:
[UNKNOWN NODE doctest_block]Query strings are left unchanged:
[UNKNOWN NODE doctest_block]New in version 0.6.
- uri – The URI to convert.
- charset – The charset of the URI.
- errors – The error handling on decode.
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 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 [UNKNOWN NODE title_reference] to [UNKNOWN NODE title_reference].
If the charset is set to [UNKNOWN NODE title_reference] no unicode decoding will happen and raw bytes will be returned.
Per default a missing value for a key will default to an empty key. If you don’t want that behavior you can set [UNKNOWN NODE title_reference] to [UNKNOWN NODE title_reference].
Per default encoding errors are ignored. If you want a different behavior
you can set [UNKNOWN NODE title_reference] to 'replace'
or 'strict'
. In strict mode a
[UNKNOWN NODE title_reference] 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 [UNKNOWN NODE title_reference] can be provided.
The [UNKNOWN NODE title_reference] parameter was added.
- s – a string with the query string to decode.
- charset – the charset of the query string. If set to [UNKNOWN NODE title_reference] no unicode decoding will take place.
- decode_keys – Used on Python 2.x to control whether keys should be forced to be unicode objects. If set to [UNKNOWN NODE title_reference] then keys will be unicode in all cases. Otherwise, they remain [UNKNOWN NODE title_reference] if they fit into ASCII.
- include_empty – Set to [UNKNOWN NODE title_reference] if you don’t want empty values to appear in the dict.
- errors – the decoding error behavior.
- separator – the pair separator to be used, defaults to
&
- cls – an optional dict class to use. If this is not specified
or [UNKNOWN NODE title_reference] the default
MultiDict
is used.
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()
but decodes a stream. The behavior
of stream and limit follows functions like
make_line_iter()
. The generator of pairs is
directly fed to the [UNKNOWN NODE title_reference] so you can consume the data while it’s
parsed.
New in version 0.8.
- stream – a stream with the encoded querystring
- charset – the charset of the query string. If set to [UNKNOWN NODE title_reference] no unicode decoding will take place.
- decode_keys – Used on Python 2.x to control whether keys should be forced to be unicode objects. If set to [UNKNOWN NODE title_reference], keys will be unicode in all cases. Otherwise, they remain [UNKNOWN NODE title_reference] if they fit into ASCII.
- include_empty – Set to [UNKNOWN NODE title_reference] if you don’t want empty values to appear in the dict.
- errors – the decoding error behavior.
- separator – the pair separator to be used, defaults to
&
- cls – an optional dict class to use. If this is not specified
or [UNKNOWN NODE title_reference] the default
MultiDict
is used. - limit – the content length of the URL data. Not necessary if a limited stream is provided.
- return_iterator – if set to [UNKNOWN NODE title_reference] the [UNKNOWN NODE title_reference] argument is ignored and an iterator over all decoded pairs is returned
werkzeug.urls.url_encode(obj, charset='utf-8', encode_keys=False, sort=False, key=None, separator='&')
URL encode a dict/[UNKNOWN NODE title_reference]. If a value is [UNKNOWN NODE title_reference] it will not appear
in the result string. Per default only values are encoded into the target
charset strings. If [UNKNOWN NODE title_reference] is set to True
unicode keys are
supported too.
If [UNKNOWN NODE title_reference] is set to [UNKNOWN NODE title_reference] the items are sorted by [UNKNOWN NODE title_reference] or the default sorting algorithm.
New in version 0.5: [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], and [UNKNOWN NODE title_reference] were added.
- obj – the object to encode into a query string.
- charset – the charset of the query string.
- encode_keys – set to [UNKNOWN NODE title_reference] if you have unicode keys. (Ignored on Python 3.x)
- sort – set to [UNKNOWN NODE title_reference] if you want parameters to be sorted by [UNKNOWN NODE title_reference].
- separator – the separator to be used for the pairs.
- key – an optional function to be used for sorting. For more details
check out the
sorted()
documentation.
werkzeug.urls.url_encode_stream(obj, stream=None, charset='utf-8', encode_keys=False, sort=False, key=None, separator='&')
Like url_encode()
but writes the results to a stream
object. If the stream is [UNKNOWN NODE title_reference] a generator over all encoded
pairs is returned.
New in version 0.8.
- obj – the object to encode into a query string.
- stream – a stream to write the encoded object into or [UNKNOWN NODE title_reference] if an iterator over the encoded pairs should be returned. In that case the separator argument is ignored.
- charset – the charset of the query string.
- encode_keys – set to [UNKNOWN NODE title_reference] if you have unicode keys. (Ignored on Python 3.x)
- sort – set to [UNKNOWN NODE title_reference] if you want parameters to be sorted by [UNKNOWN NODE title_reference].
- separator – the separator to be used for the pairs.
- key – an optional function to be used for sorting. For more details
check out the
sorted()
documentation.
werkzeug.urls.url_fix(s, charset='utf-8')
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:
[UNKNOWN NODE doctest_block]- s – the string with the URL to fix.
- charset – The target charset for the URL if the url was given as unicode string.
werkzeug.urls.url_join(base, url, allow_fragments=True)
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.
- base – the base URL for the join operation.
- url – the URL to join.
- allow_fragments – indicates whether fragments should be allowed.
werkzeug.urls.url_parse(url, scheme=None, allow_fragments=True)
Parses a URL from a string into a 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 [UNKNOWN NODE title_reference] to [UNKNOWN NODE title_reference].
The inverse of this function is url_unparse()
.
- url – the URL to parse.
- scheme – the default schema to use if the URL is schemaless.
- allow_fragments – if set to [UNKNOWN NODE title_reference] a fragment will be removed from the URL.
werkzeug.urls.url_quote(string, charset='utf-8', errors='strict', safe='/:', unsafe='')
URL encode a single string with a given encoding.
- s – the string to quote.
- charset – the charset to be used.
- safe – an optional sequence of safe characters.
- unsafe – an optional sequence of unsafe characters.
New in version 0.9.2: The [UNKNOWN NODE title_reference] 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 convert whitespace to “+”.
- s – The string to quote.
- charset – The charset to be used.
- safe – An optional sequence of safe characters.
werkzeug.urls.url_unparse(components)
The reverse operation to url_parse()
. This accepts arbitrary
as well as URL
tuples and returns a URL as a string.
werkzeug.urls.url_unquote(string, charset='utf-8', errors='replace', unsafe='')
URL decode a single string with a given encoding. If the charset is set to [UNKNOWN NODE title_reference] no unicode decoding is performed and raw bytes are returned.
- s – the string to unquote.
- charset – the charset of the query string. If set to [UNKNOWN NODE title_reference] no unicode decoding will take place.
- errors – the error handling for the charset decoding.
werkzeug.urls.url_unquote_plus(s, charset='utf-8', errors='replace')
URL decode a single string with the given [UNKNOWN NODE title_reference] and decode “+” to whitespace.
Per default encoding errors are ignored. If you want a different behavior
you can set [UNKNOWN NODE title_reference] to 'replace'
or 'strict'
. In strict mode a
HTTPUnicodeError
is raised.
- s – The string to unquote.
- charset – the charset of the query string. If set to [UNKNOWN NODE title_reference] no unicode decoding will take place.
- errors – The error handling for the [UNKNOWN NODE title_reference] decoding.