Fixed: #2914 (RFE for UTC support in TimedRotatingFileHandler) and #2929 (wrong filen...
[python.git] / Doc / library / urlparse.rst
blob0d83d779df4f839f71e00db2467c2a5e3abab704
1 :mod:`urlparse` --- Parse URLs into components
2 ==============================================
4 .. module:: urlparse
5    :synopsis: Parse URLs into or assemble them from components.
8 .. index::
9    single: WWW
10    single: World Wide Web
11    single: URL
12    pair: URL; parsing
13    pair: relative; URL
15 This module defines a standard interface to break Uniform Resource Locator (URL)
16 strings up in components (addressing scheme, network location, path etc.), to
17 combine the components back into a URL string, and to convert a "relative URL"
18 to an absolute URL given a "base URL."
20 The module has been designed to match the Internet RFC on Relative Uniform
21 Resource Locators (and discovered a bug in an earlier draft!). It supports the
22 following URL schemes: ``file``, ``ftp``, ``gopher``, ``hdl``, ``http``,
23 ``https``, ``imap``, ``mailto``, ``mms``, ``news``,  ``nntp``, ``prospero``,
24 ``rsync``, ``rtsp``, ``rtspu``,  ``sftp``, ``shttp``, ``sip``, ``sips``,
25 ``snews``, ``svn``,  ``svn+ssh``, ``telnet``, ``wais``.
27 .. versionadded:: 2.5
28    Support for the ``sftp`` and ``sips`` schemes.
30 The :mod:`urlparse` module defines the following functions:
33 .. function:: urlparse(urlstring[, default_scheme[, allow_fragments]])
35    Parse a URL into six components, returning a 6-tuple.  This corresponds to the
36    general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``.
37    Each tuple item is a string, possibly empty. The components are not broken up in
38    smaller parts (for example, the network location is a single string), and %
39    escapes are not expanded. The delimiters as shown above are not part of the
40    result, except for a leading slash in the *path* component, which is retained if
41    present.  For example:
43       >>> from urlparse import urlparse
44       >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
45       >>> o   # doctest: +NORMALIZE_WHITESPACE
46       ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
47                   params='', query='', fragment='')
48       >>> o.scheme
49       'http'
50       >>> o.port
51       80
52       >>> o.geturl()
53       'http://www.cwi.nl:80/%7Eguido/Python.html'
55    If the *default_scheme* argument is specified, it gives the default addressing
56    scheme, to be used only if the URL does not specify one.  The default value for
57    this argument is the empty string.
59    If the *allow_fragments* argument is false, fragment identifiers are not
60    allowed, even if the URL's addressing scheme normally does support them.  The
61    default value for this argument is :const:`True`.
63    The return value is actually an instance of a subclass of :class:`tuple`.  This
64    class has the following additional read-only convenience attributes:
66    +------------------+-------+--------------------------+----------------------+
67    | Attribute        | Index | Value                    | Value if not present |
68    +==================+=======+==========================+======================+
69    | :attr:`scheme`   | 0     | URL scheme specifier     | empty string         |
70    +------------------+-------+--------------------------+----------------------+
71    | :attr:`netloc`   | 1     | Network location part    | empty string         |
72    +------------------+-------+--------------------------+----------------------+
73    | :attr:`path`     | 2     | Hierarchical path        | empty string         |
74    +------------------+-------+--------------------------+----------------------+
75    | :attr:`params`   | 3     | Parameters for last path | empty string         |
76    |                  |       | element                  |                      |
77    +------------------+-------+--------------------------+----------------------+
78    | :attr:`query`    | 4     | Query component          | empty string         |
79    +------------------+-------+--------------------------+----------------------+
80    | :attr:`fragment` | 5     | Fragment identifier      | empty string         |
81    +------------------+-------+--------------------------+----------------------+
82    | :attr:`username` |       | User name                | :const:`None`        |
83    +------------------+-------+--------------------------+----------------------+
84    | :attr:`password` |       | Password                 | :const:`None`        |
85    +------------------+-------+--------------------------+----------------------+
86    | :attr:`hostname` |       | Host name (lower case)   | :const:`None`        |
87    +------------------+-------+--------------------------+----------------------+
88    | :attr:`port`     |       | Port number as integer,  | :const:`None`        |
89    |                  |       | if present               |                      |
90    +------------------+-------+--------------------------+----------------------+
92    See section :ref:`urlparse-result-object` for more information on the result
93    object.
95    .. versionchanged:: 2.5
96       Added attributes to return value.
99 .. function:: urlunparse(parts)
101    Construct a URL from a tuple as returned by ``urlparse()``. The *parts* argument
102    can be any six-item iterable. This may result in a slightly different, but
103    equivalent URL, if the URL that was parsed originally had unnecessary delimiters
104    (for example, a ? with an empty query; the RFC states that these are
105    equivalent).
108 .. function:: urlsplit(urlstring[, default_scheme[, allow_fragments]])
110    This is similar to :func:`urlparse`, but does not split the params from the URL.
111    This should generally be used instead of :func:`urlparse` if the more recent URL
112    syntax allowing parameters to be applied to each segment of the *path* portion
113    of the URL (see :rfc:`2396`) is wanted.  A separate function is needed to
114    separate the path segments and parameters.  This function returns a 5-tuple:
115    (addressing scheme, network location, path, query, fragment identifier).
117    The return value is actually an instance of a subclass of :class:`tuple`.  This
118    class has the following additional read-only convenience attributes:
120    +------------------+-------+-------------------------+----------------------+
121    | Attribute        | Index | Value                   | Value if not present |
122    +==================+=======+=========================+======================+
123    | :attr:`scheme`   | 0     | URL scheme specifier    | empty string         |
124    +------------------+-------+-------------------------+----------------------+
125    | :attr:`netloc`   | 1     | Network location part   | empty string         |
126    +------------------+-------+-------------------------+----------------------+
127    | :attr:`path`     | 2     | Hierarchical path       | empty string         |
128    +------------------+-------+-------------------------+----------------------+
129    | :attr:`query`    | 3     | Query component         | empty string         |
130    +------------------+-------+-------------------------+----------------------+
131    | :attr:`fragment` | 4     | Fragment identifier     | empty string         |
132    +------------------+-------+-------------------------+----------------------+
133    | :attr:`username` |       | User name               | :const:`None`        |
134    +------------------+-------+-------------------------+----------------------+
135    | :attr:`password` |       | Password                | :const:`None`        |
136    +------------------+-------+-------------------------+----------------------+
137    | :attr:`hostname` |       | Host name (lower case)  | :const:`None`        |
138    +------------------+-------+-------------------------+----------------------+
139    | :attr:`port`     |       | Port number as integer, | :const:`None`        |
140    |                  |       | if present              |                      |
141    +------------------+-------+-------------------------+----------------------+
143    See section :ref:`urlparse-result-object` for more information on the result
144    object.
146    .. versionadded:: 2.2
148    .. versionchanged:: 2.5
149       Added attributes to return value.
152 .. function:: urlunsplit(parts)
154    Combine the elements of a tuple as returned by :func:`urlsplit` into a complete
155    URL as a string. The *parts* argument can be any five-item iterable. This may
156    result in a slightly different, but equivalent URL, if the URL that was parsed
157    originally had unnecessary delimiters (for example, a ? with an empty query; the
158    RFC states that these are equivalent).
160    .. versionadded:: 2.2
163 .. function:: urljoin(base, url[, allow_fragments])
165    Construct a full ("absolute") URL by combining a "base URL" (*base*) with
166    another URL (*url*).  Informally, this uses components of the base URL, in
167    particular the addressing scheme, the network location and (part of) the path,
168    to provide missing components in the relative URL.  For example:
170       >>> from urlparse import urljoin
171       >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
172       'http://www.cwi.nl/%7Eguido/FAQ.html'
174    The *allow_fragments* argument has the same meaning and default as for
175    :func:`urlparse`.
177    .. note::
179       If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``),
180       the *url*'s host name and/or scheme will be present in the result.  For example:
182    .. doctest::
184       >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
185       ...         '//www.python.org/%7Eguido')
186       'http://www.python.org/%7Eguido'
188    If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and
189    :func:`urlunsplit`, removing possible *scheme* and *netloc* parts.
192 .. function:: urldefrag(url)
194    If *url* contains a fragment identifier, returns a modified version of *url*
195    with no fragment identifier, and the fragment identifier as a separate string.
196    If there is no fragment identifier in *url*, returns *url* unmodified and an
197    empty string.
200 .. seealso::
202    :rfc:`1738` - Uniform Resource Locators (URL)
203       This specifies the formal syntax and semantics of absolute URLs.
205    :rfc:`1808` - Relative Uniform Resource Locators
206       This Request For Comments includes the rules for joining an absolute and a
207       relative URL, including a fair number of "Abnormal Examples" which govern the
208       treatment of border cases.
210    :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax
211       Document describing the generic syntactic requirements for both Uniform Resource
212       Names (URNs) and Uniform Resource Locators (URLs).
215 .. _urlparse-result-object:
217 Results of :func:`urlparse` and :func:`urlsplit`
218 ------------------------------------------------
220 The result objects from the :func:`urlparse` and :func:`urlsplit` functions are
221 subclasses of the :class:`tuple` type.  These subclasses add the attributes
222 described in those functions, as well as provide an additional method:
225 .. method:: ParseResult.geturl()
227    Return the re-combined version of the original URL as a string. This may differ
228    from the original URL in that the scheme will always be normalized to lower case
229    and empty components may be dropped. Specifically, empty parameters, queries,
230    and fragment identifiers will be removed.
232    The result of this method is a fixpoint if passed back through the original
233    parsing function:
235       >>> import urlparse
236       >>> url = 'HTTP://www.Python.org/doc/#'
238       >>> r1 = urlparse.urlsplit(url)
239       >>> r1.geturl()
240       'http://www.Python.org/doc/'
242       >>> r2 = urlparse.urlsplit(r1.geturl())
243       >>> r2.geturl()
244       'http://www.Python.org/doc/'
246    .. versionadded:: 2.5
248 The following classes provide the implementations of the parse results::
251 .. class:: BaseResult
253    Base class for the concrete result classes.  This provides most of the attribute
254    definitions.  It does not provide a :meth:`geturl` method.  It is derived from
255    :class:`tuple`, but does not override the :meth:`__init__` or :meth:`__new__`
256    methods.
259 .. class:: ParseResult(scheme, netloc, path, params, query, fragment)
261    Concrete class for :func:`urlparse` results.  The :meth:`__new__` method is
262    overridden to support checking that the right number of arguments are passed.
265 .. class:: SplitResult(scheme, netloc, path, query, fragment)
267    Concrete class for :func:`urlsplit` results.  The :meth:`__new__` method is
268    overridden to support checking that the right number of arguments are passed.