~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Doc/library/urllib.parse.rst

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
Import upstream version 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
:mod:`urllib.parse` --- Parse URLs into components
 
2
==================================================
 
3
 
 
4
.. module:: urllib.parse
 
5
   :synopsis: Parse URLs into or assemble them from components.
 
6
 
 
7
 
 
8
.. index::
 
9
   single: WWW
 
10
   single: World Wide Web
 
11
   single: URL
 
12
   pair: URL; parsing
 
13
   pair: relative; URL
 
14
 
 
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."
 
19
 
 
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``.
 
26
 
 
27
The :mod:`urllib.parse` module defines the following functions:
 
28
 
 
29
.. function:: urlparse(urlstring[, default_scheme[, allow_fragments]])
 
30
 
 
31
   Parse a URL into six components, returning a 6-tuple.  This corresponds to the
 
32
   general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``.
 
33
   Each tuple item is a string, possibly empty. The components are not broken up in
 
34
   smaller parts (for example, the network location is a single string), and %
 
35
   escapes are not expanded. The delimiters as shown above are not part of the
 
36
   result, except for a leading slash in the *path* component, which is retained if
 
37
   present.  For example:
 
38
 
 
39
      >>> from urllib.parse import urlparse
 
40
      >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
 
41
      >>> o   # doctest: +NORMALIZE_WHITESPACE
 
42
      ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
 
43
                  params='', query='', fragment='')
 
44
      >>> o.scheme
 
45
      'http'
 
46
      >>> o.port
 
47
      80
 
48
      >>> o.geturl()
 
49
      'http://www.cwi.nl:80/%7Eguido/Python.html'
 
50
 
 
51
   If the *default_scheme* argument is specified, it gives the default addressing
 
52
   scheme, to be used only if the URL does not specify one.  The default value for
 
53
   this argument is the empty string.
 
54
 
 
55
   If the *allow_fragments* argument is false, fragment identifiers are not
 
56
   allowed, even if the URL's addressing scheme normally does support them.  The
 
57
   default value for this argument is :const:`True`.
 
58
 
 
59
   The return value is actually an instance of a subclass of :class:`tuple`.  This
 
60
   class has the following additional read-only convenience attributes:
 
61
 
 
62
   +------------------+-------+--------------------------+----------------------+
 
63
   | Attribute        | Index | Value                    | Value if not present |
 
64
   +==================+=======+==========================+======================+
 
65
   | :attr:`scheme`   | 0     | URL scheme specifier     | empty string         |
 
66
   +------------------+-------+--------------------------+----------------------+
 
67
   | :attr:`netloc`   | 1     | Network location part    | empty string         |
 
68
   +------------------+-------+--------------------------+----------------------+
 
69
   | :attr:`path`     | 2     | Hierarchical path        | empty string         |
 
70
   +------------------+-------+--------------------------+----------------------+
 
71
   | :attr:`params`   | 3     | Parameters for last path | empty string         |
 
72
   |                  |       | element                  |                      |
 
73
   +------------------+-------+--------------------------+----------------------+
 
74
   | :attr:`query`    | 4     | Query component          | empty string         |
 
75
   +------------------+-------+--------------------------+----------------------+
 
76
   | :attr:`fragment` | 5     | Fragment identifier      | empty string         |
 
77
   +------------------+-------+--------------------------+----------------------+
 
78
   | :attr:`username` |       | User name                | :const:`None`        |
 
79
   +------------------+-------+--------------------------+----------------------+
 
80
   | :attr:`password` |       | Password                 | :const:`None`        |
 
81
   +------------------+-------+--------------------------+----------------------+
 
82
   | :attr:`hostname` |       | Host name (lower case)   | :const:`None`        |
 
83
   +------------------+-------+--------------------------+----------------------+
 
84
   | :attr:`port`     |       | Port number as integer,  | :const:`None`        |
 
85
   |                  |       | if present               |                      |
 
86
   +------------------+-------+--------------------------+----------------------+
 
87
 
 
88
   See section :ref:`urlparse-result-object` for more information on the result
 
89
   object.
 
90
 
 
91
 
 
92
.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing]])
 
93
 
 
94
   Parse a query string given as a string argument (data of type
 
95
   :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a
 
96
   dictionary.  The dictionary keys are the unique query variable names and the
 
97
   values are lists of values for each name.
 
98
 
 
99
   The optional argument *keep_blank_values* is a flag indicating whether blank
 
100
   values in URL encoded queries should be treated as blank strings.   A true value
 
101
   indicates that blanks should be retained as  blank strings.  The default false
 
102
   value indicates that blank values are to be ignored and treated as if they were
 
103
   not included.
 
104
 
 
105
   The optional argument *strict_parsing* is a flag indicating what to do with
 
106
   parsing errors.  If false (the default), errors are silently ignored.  If true,
 
107
   errors raise a :exc:`ValueError` exception.
 
108
 
 
109
   Use the :func:`urllib.parse.urlencode` function to convert such
 
110
   dictionaries into query strings.
 
111
 
 
112
 
 
113
.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing]])
 
114
 
 
115
   Parse a query string given as a string argument (data of type
 
116
   :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a list of
 
117
   name, value pairs.
 
118
 
 
119
   The optional argument *keep_blank_values* is a flag indicating whether blank
 
120
   values in URL encoded queries should be treated as blank strings.   A true value
 
121
   indicates that blanks should be retained as  blank strings.  The default false
 
122
   value indicates that blank values are to be ignored and treated as if they were
 
123
   not included.
 
124
 
 
125
   The optional argument *strict_parsing* is a flag indicating what to do with
 
126
   parsing errors.  If false (the default), errors are silently ignored.  If true,
 
127
   errors raise a :exc:`ValueError` exception.
 
128
 
 
129
   Use the :func:`urllib.parse.urlencode` function to convert such lists of pairs into
 
130
   query strings.
 
131
 
 
132
 
 
133
.. function:: urlunparse(parts)
 
134
 
 
135
   Construct a URL from a tuple as returned by ``urlparse()``. The *parts*
 
136
   argument can be any six-item iterable. This may result in a slightly
 
137
   different, but equivalent URL, if the URL that was parsed originally had
 
138
   unnecessary delimiters (for example, a ``?`` with an empty query; the RFC
 
139
   states that these are equivalent).
 
140
 
 
141
 
 
142
.. function:: urlsplit(urlstring[, default_scheme[, allow_fragments]])
 
143
 
 
144
   This is similar to :func:`urlparse`, but does not split the params from the URL.
 
145
   This should generally be used instead of :func:`urlparse` if the more recent URL
 
146
   syntax allowing parameters to be applied to each segment of the *path* portion
 
147
   of the URL (see :rfc:`2396`) is wanted.  A separate function is needed to
 
148
   separate the path segments and parameters.  This function returns a 5-tuple:
 
149
   (addressing scheme, network location, path, query, fragment identifier).
 
150
 
 
151
   The return value is actually an instance of a subclass of :class:`tuple`.  This
 
152
   class has the following additional read-only convenience attributes:
 
153
 
 
154
   +------------------+-------+-------------------------+----------------------+
 
155
   | Attribute        | Index | Value                   | Value if not present |
 
156
   +==================+=======+=========================+======================+
 
157
   | :attr:`scheme`   | 0     | URL scheme specifier    | empty string         |
 
158
   +------------------+-------+-------------------------+----------------------+
 
159
   | :attr:`netloc`   | 1     | Network location part   | empty string         |
 
160
   +------------------+-------+-------------------------+----------------------+
 
161
   | :attr:`path`     | 2     | Hierarchical path       | empty string         |
 
162
   +------------------+-------+-------------------------+----------------------+
 
163
   | :attr:`query`    | 3     | Query component         | empty string         |
 
164
   +------------------+-------+-------------------------+----------------------+
 
165
   | :attr:`fragment` | 4     | Fragment identifier     | empty string         |
 
166
   +------------------+-------+-------------------------+----------------------+
 
167
   | :attr:`username` |       | User name               | :const:`None`        |
 
168
   +------------------+-------+-------------------------+----------------------+
 
169
   | :attr:`password` |       | Password                | :const:`None`        |
 
170
   +------------------+-------+-------------------------+----------------------+
 
171
   | :attr:`hostname` |       | Host name (lower case)  | :const:`None`        |
 
172
   +------------------+-------+-------------------------+----------------------+
 
173
   | :attr:`port`     |       | Port number as integer, | :const:`None`        |
 
174
   |                  |       | if present              |                      |
 
175
   +------------------+-------+-------------------------+----------------------+
 
176
 
 
177
   See section :ref:`urlparse-result-object` for more information on the result
 
178
   object.
 
179
 
 
180
 
 
181
.. function:: urlunsplit(parts)
 
182
 
 
183
   Combine the elements of a tuple as returned by :func:`urlsplit` into a
 
184
   complete URL as a string. The *parts* argument can be any five-item
 
185
   iterable. This may result in a slightly different, but equivalent URL, if the
 
186
   URL that was parsed originally had unnecessary delimiters (for example, a ?
 
187
   with an empty query; the RFC states that these are equivalent).
 
188
 
 
189
 
 
190
.. function:: urljoin(base, url[, allow_fragments])
 
191
 
 
192
   Construct a full ("absolute") URL by combining a "base URL" (*base*) with
 
193
   another URL (*url*).  Informally, this uses components of the base URL, in
 
194
   particular the addressing scheme, the network location and (part of) the
 
195
   path, to provide missing components in the relative URL.  For example:
 
196
 
 
197
      >>> from urllib.parse import urljoin
 
198
      >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
 
199
      'http://www.cwi.nl/%7Eguido/FAQ.html'
 
200
 
 
201
   The *allow_fragments* argument has the same meaning and default as for
 
202
   :func:`urlparse`.
 
203
 
 
204
   .. note::
 
205
 
 
206
      If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``),
 
207
      the *url*'s host name and/or scheme will be present in the result.  For example:
 
208
 
 
209
   .. doctest::
 
210
 
 
211
      >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
 
212
      ...         '//www.python.org/%7Eguido')
 
213
      'http://www.python.org/%7Eguido'
 
214
 
 
215
   If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and
 
216
   :func:`urlunsplit`, removing possible *scheme* and *netloc* parts.
 
217
 
 
218
 
 
219
.. function:: urldefrag(url)
 
220
 
 
221
   If *url* contains a fragment identifier, return a modified version of *url*
 
222
   with no fragment identifier, and the fragment identifier as a separate
 
223
   string.  If there is no fragment identifier in *url*, return *url* unmodified
 
224
   and an empty string.
 
225
 
 
226
.. function:: quote(string[, safe[, encoding[, errors]]])
 
227
 
 
228
   Replace special characters in *string* using the ``%xx`` escape. Letters,
 
229
   digits, and the characters ``'_.-'`` are never quoted. The optional *safe*
 
230
   parameter specifies additional ASCII characters that should not be quoted
 
231
   --- its default value is ``'/'``.
 
232
 
 
233
   *string* may be either a :class:`str` or a :class:`bytes`.
 
234
 
 
235
   The optional *encoding* and *errors* parameters specify how to deal with
 
236
   non-ASCII characters, as accepted by the :meth:`str.encode` method.
 
237
   *encoding* defaults to ``'utf-8'``.
 
238
   *errors* defaults to ``'strict'``, meaning unsupported characters raise a
 
239
   :class:`UnicodeEncodeError`.
 
240
   *encoding* and *errors* must not be supplied if *string* is a
 
241
   :class:`bytes`, or a :class:`TypeError` is raised.
 
242
 
 
243
   Note that ``quote(string, safe, encoding, errors)`` is equivalent to
 
244
   ``quote_from_bytes(string.encode(encoding, errors), safe)``.
 
245
 
 
246
   Example: ``quote('/El Niño/')`` yields ``'/El%20Ni%C3%B1o/'``.
 
247
 
 
248
 
 
249
.. function:: quote_plus(string[, safe[, encoding[, errors]]])
 
250
 
 
251
   Like :func:`quote`, but also replace spaces by plus signs, as required for
 
252
   quoting HTML form values.  Plus signs in the original string are escaped
 
253
   unless they are included in *safe*.  It also does not have *safe* default to
 
254
   ``'/'``.
 
255
 
 
256
   Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``.
 
257
 
 
258
.. function:: quote_from_bytes(bytes[, safe])
 
259
 
 
260
   Like :func:`quote`, but accepts a :class:`bytes` object rather than a
 
261
   :class:`str`, and does not perform string-to-bytes encoding.
 
262
 
 
263
   Example: ``quote_from_bytes(b'a&\xef')`` yields
 
264
   ``'a%26%EF'``.
 
265
 
 
266
.. function:: unquote(string[, encoding[, errors]])
 
267
 
 
268
   Replace ``%xx`` escapes by their single-character equivalent.
 
269
   The optional *encoding* and *errors* parameters specify how to decode
 
270
   percent-encoded sequences into Unicode characters, as accepted by the
 
271
   :meth:`bytes.decode` method.
 
272
 
 
273
   *string* must be a :class:`str`.
 
274
 
 
275
   *encoding* defaults to ``'utf-8'``.
 
276
   *errors* defaults to ``'replace'``, meaning invalid sequences are replaced
 
277
   by a placeholder character.
 
278
 
 
279
   Example: ``unquote('/El%20Ni%C3%B1o/')`` yields ``'/El Niño/'``.
 
280
 
 
281
 
 
282
.. function:: unquote_plus(string[, encoding[, errors]])
 
283
 
 
284
   Like :func:`unquote`, but also replace plus signs by spaces, as required for
 
285
   unquoting HTML form values.
 
286
 
 
287
   *string* must be a :class:`str`.
 
288
 
 
289
   Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``.
 
290
 
 
291
.. function:: unquote_to_bytes(string)
 
292
 
 
293
   Replace ``%xx`` escapes by their single-octet equivalent, and return a
 
294
   :class:`bytes` object.
 
295
 
 
296
   *string* may be either a :class:`str` or a :class:`bytes`.
 
297
 
 
298
   If it is a :class:`str`, unescaped non-ASCII characters in *string*
 
299
   are encoded into UTF-8 bytes.
 
300
 
 
301
   Example: ``unquote_to_bytes('a%26%EF')`` yields
 
302
   ``b'a&\xef'``.
 
303
 
 
304
 
 
305
.. function:: urlencode(query[, doseq])
 
306
 
 
307
   Convert a mapping object or a sequence of two-element tuples  to a "url-encoded"
 
308
   string, suitable to pass to :func:`urlopen` above as the optional *data*
 
309
   argument.  This is useful to pass a dictionary of form fields to a ``POST``
 
310
   request.  The resulting string is a series of ``key=value`` pairs separated by
 
311
   ``'&'`` characters, where both *key* and *value* are quoted using
 
312
   :func:`quote_plus` above.  If the optional parameter *doseq* is present and
 
313
   evaluates to true, individual ``key=value`` pairs are generated for each element
 
314
   of the sequence. When a sequence of two-element tuples is used as the *query*
 
315
   argument, the first element of each tuple is a key and the second is a value.
 
316
   The order of parameters in the encoded string will match the order of parameter
 
317
   tuples in the sequence. This module provides the functions
 
318
   :func:`parse_qs` and :func:`parse_qsl` which are used to parse query strings
 
319
   into Python data structures.
 
320
 
 
321
 
 
322
.. seealso::
 
323
 
 
324
   :rfc:`1738` - Uniform Resource Locators (URL)
 
325
      This specifies the formal syntax and semantics of absolute URLs.
 
326
 
 
327
   :rfc:`1808` - Relative Uniform Resource Locators
 
328
      This Request For Comments includes the rules for joining an absolute and a
 
329
      relative URL, including a fair number of "Abnormal Examples" which govern the
 
330
      treatment of border cases.
 
331
 
 
332
   :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax
 
333
      Document describing the generic syntactic requirements for both Uniform Resource
 
334
      Names (URNs) and Uniform Resource Locators (URLs).
 
335
 
 
336
 
 
337
.. _urlparse-result-object:
 
338
 
 
339
Results of :func:`urlparse` and :func:`urlsplit`
 
340
------------------------------------------------
 
341
 
 
342
The result objects from the :func:`urlparse` and :func:`urlsplit` functions are
 
343
subclasses of the :class:`tuple` type.  These subclasses add the attributes
 
344
described in those functions, as well as provide an additional method:
 
345
 
 
346
.. method:: ParseResult.geturl()
 
347
 
 
348
   Return the re-combined version of the original URL as a string. This may differ
 
349
   from the original URL in that the scheme will always be normalized to lower case
 
350
   and empty components may be dropped. Specifically, empty parameters, queries,
 
351
   and fragment identifiers will be removed.
 
352
 
 
353
   The result of this method is a fixpoint if passed back through the original
 
354
   parsing function:
 
355
 
 
356
      >>> import urllib.parse
 
357
      >>> url = 'HTTP://www.Python.org/doc/#'
 
358
 
 
359
      >>> r1 = urllib.parse.urlsplit(url)
 
360
      >>> r1.geturl()
 
361
      'http://www.Python.org/doc/'
 
362
 
 
363
      >>> r2 = urllib.parse.urlsplit(r1.geturl())
 
364
      >>> r2.geturl()
 
365
      'http://www.Python.org/doc/'
 
366
 
 
367
 
 
368
The following classes provide the implementations of the parse results:
 
369
 
 
370
.. class:: BaseResult
 
371
 
 
372
   Base class for the concrete result classes.  This provides most of the
 
373
   attribute definitions.  It does not provide a :meth:`geturl` method.  It is
 
374
   derived from :class:`tuple`, but does not override the :meth:`__init__` or
 
375
   :meth:`__new__` methods.
 
376
 
 
377
 
 
378
.. class:: ParseResult(scheme, netloc, path, params, query, fragment)
 
379
 
 
380
   Concrete class for :func:`urlparse` results.  The :meth:`__new__` method is
 
381
   overridden to support checking that the right number of arguments are passed.
 
382
 
 
383
 
 
384
.. class:: SplitResult(scheme, netloc, path, query, fragment)
 
385
 
 
386
   Concrete class for :func:`urlsplit` results.  The :meth:`__new__` method is
 
387
   overridden to support checking that the right number of arguments are passed.
 
388