rest25/library/urllib.rst => rest262/library/urllib.rst
n1- 
2:mod:`urllib` --- Open arbitrary resources by URL
3=================================================
4
5.. module:: urllib
6   :synopsis: Open an arbitrary network resource by URL (requires sockets).
7
n7+.. note::
8+    The :mod:`urllib` module has been split into parts and renamed in
9+    Python 3.0 to :mod:`urllib.request`, :mod:`urllib.parse`,
10+    and :mod:`urllib.error`. The :term:`2to3` tool will automatically adapt
11+    imports when converting your sources to 3.0.
12+    Also note that the :func:`urllib.urlopen` function has been removed in
13+    Python 3.0 in favor of :func:`urllib2.urlopen`.
8
9.. index::
10   single: WWW
11   single: World Wide Web
12   single: URL
13
14This module provides a high-level interface for fetching data across the World
n15-Wide Web.  In particular, the :func:`urlopen` function is similar to the built-
n21+Wide Web.  In particular, the :func:`urlopen` function is similar to the
16-in function :func:`open`, but accepts Universal Resource Locators (URLs) instead
22+built-in function :func:`open`, but accepts Universal Resource Locators (URLs)
17-of filenames.  Some restrictions apply --- it can only open URLs for reading,
23+instead of filenames.  Some restrictions apply --- it can only open URLs for
18-and no seek operations are available.
24+reading, and no seek operations are available.
19
n20-It defines the following public functions:
n26+High-level interface
21- 
27+--------------------
22
23.. function:: urlopen(url[, data[, proxies]])
24
25   Open a network object denoted by a URL for reading.  If the URL does not have a
26   scheme identifier, or if it has :file:`file:` as its scheme identifier, this
27   opens a local file (without universal newlines); otherwise it opens a socket to
28   a server somewhere on the network.  If the connection cannot be made the
29   :exc:`IOError` exception is raised.  If all went well, a file-like object is
30   returned.  This supports the following methods: :meth:`read`, :meth:`readline`,
n31-   :meth:`readlines`, :meth:`fileno`, :meth:`close`, :meth:`info` and
n37+   :meth:`readlines`, :meth:`fileno`, :meth:`close`, :meth:`info`, :meth:`getcode` and
32-   :meth:`geturl`.  It also has proper support for the iterator protocol. One
38+   :meth:`geturl`.  It also has proper support for the :term:`iterator` protocol. One
33   caveat: the :meth:`read` method, if the size argument is omitted or negative,
34   may not read until the end of the data stream; there is no good way to determine
35   that the entire stream from a socket has been read in the general case.
36
n37-   Except for the :meth:`info` and :meth:`geturl` methods, these methods have the
n43+   Except for the :meth:`info`, :meth:`getcode` and :meth:`geturl` methods,
38-   same interface as for file objects --- see section :ref:`bltin-file-objects` in
44+   these methods have the same interface as for file objects --- see section
39-   this manual.  (It is not a built-in file object, however, so it can't be used at
45+   :ref:`bltin-file-objects` in this manual.  (It is not a built-in file object,
40-   those few places where a true built-in file object is required.)
46+   however, so it can't be used at those few places where a true built-in file
47+   object is required.)
41
42   .. index:: module: mimetools
43
44   The :meth:`info` method returns an instance of the class
n45-   :class:`mimetools.Message` containing meta-information associated with the URL.
n52+   :class:`httplib.HTTPMessage` containing meta-information associated with the
46-   When the method is HTTP, these headers are those returned by the server at the
53+   URL.  When the method is HTTP, these headers are those returned by the server
47-   head of the retrieved HTML page (including Content-Length and Content-Type).
54+   at the head of the retrieved HTML page (including Content-Length and
48-   When the method is FTP, a Content-Length header will be present if (as is now
55+   Content-Type).  When the method is FTP, a Content-Length header will be
49-   usual) the server passed back a file length in response to the FTP retrieval
56+   present if (as is now usual) the server passed back a file length in response
50-   request. A Content-Type header will be present if the MIME type can be guessed.
57+   to the FTP retrieval request. A Content-Type header will be present if the
51-   When the method is local-file, returned headers will include a Date representing
58+   MIME type can be guessed.  When the method is local-file, returned headers
52-   the file's last-modified time, a Content-Length giving file size, and a Content-
59+   will include a Date representing the file's last-modified time, a
53-   Type containing a guess at the file's type. See also the description of the
60+   Content-Length giving file size, and a Content-Type containing a guess at the
54-   :mod:`mimetools` module.
61+   file's type. See also the description of the :mod:`mimetools` module.
55
56   The :meth:`geturl` method returns the real URL of the page.  In some cases, the
57   HTTP server redirects a client to another URL.  The :func:`urlopen` function
58   handles this transparently, but in some cases the caller needs to know which URL
59   the client was redirected to.  The :meth:`geturl` method can be used to get at
60   this redirected URL.
61
n69+   The :meth:`getcode` method returns the HTTP status code that was sent with the
70+   response, or ``None`` if the URL is no HTTP URL.
71+ 
62   If the *url* uses the :file:`http:` scheme identifier, the optional *data*
63   argument may be given to specify a ``POST`` request (normally the request type
64   is ``GET``).  The *data* argument must be in standard
65   :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
66   function below.
67
68   The :func:`urlopen` function works transparently with proxies which do not
69   require authentication.  In a Unix or Windows environment, set the
n70-   :envvar:`http_proxy`, :envvar:`ftp_proxy` or :envvar:`gopher_proxy` environment
n80+   :envvar:`http_proxy`, or :envvar:`ftp_proxy` environment variables to a URL that
71-   variables to a URL that identifies the proxy server before starting the Python
81+   identifies the proxy server before starting the Python interpreter.  For example
72-   interpreter.  For example (the ``'%'`` is the command prompt)::
82+   (the ``'%'`` is the command prompt)::
73
74      % http_proxy="http://www.someproxy.com:3128"
75      % export http_proxy
76      % python
77      ...
n88+ 
89+   The :envvar:`no_proxy` environment variable can be used to specify hosts which
90+   shouldn't be reached via proxy; if set, it should be a comma-separated list
91+   of hostname suffixes, optionally with ``:port`` appended, for example
92+   ``cern.ch,ncsa.uiuc.edu,some.host:8080``.
78
79   In a Windows environment, if no proxy environment variables are set, proxy
80   settings are obtained from the registry's Internet Settings section.
81
82   .. index:: single: Internet Config
83
84   In a Macintosh environment, :func:`urlopen` will retrieve proxy information from
85   Internet Config.
94      proxies = {'http': 'http://www.someproxy.com:3128'}
95      filehandle = urllib.urlopen(some_url, proxies=proxies)
96      # Don't use any proxies
97      filehandle = urllib.urlopen(some_url, proxies={})
98      # Use proxies from environment - both versions are equivalent
99      filehandle = urllib.urlopen(some_url, proxies=None)
100      filehandle = urllib.urlopen(some_url)
101
n102-   The :func:`urlopen` function does not support explicit proxy specification.  If
103-   you need to override environmental proxy settings, use :class:`URLopener`, or a
104-   subclass such as :class:`FancyURLopener`.
105- 
106   Proxies which require authentication for use are not currently supported; this
107   is considered an implementation limitation.
108
109   .. versionchanged:: 2.3
110      Added the *proxies* support.
n122+ 
123+   .. versionchanged:: 2.6
124+      Added :meth:`getcode` to returned object and support for the
125+      :envvar:`no_proxy` environment variable.
126+ 
127+   .. deprecated:: 2.6
128+      The :func:`urlopen` function has been removed in Python 3.0 in favor
129+      of :func:`urllib2.urlopen`.
111
112
113.. function:: urlretrieve(url[, filename[, reporthook[, data]]])
114
115   Copy a network object denoted by a URL to a local file, if necessary. If the URL
116   points to a local file, or a valid cached copy of the object exists, the object
117   is not copied.  Return a tuple ``(filename, headers)`` where *filename* is the
118   local file name under which the object can be found, and *headers* is whatever
172      urllib._urlopener = AppURLopener()
173
174
175.. function:: urlcleanup()
176
177   Clear the cache that may have been built up by previous calls to
178   :func:`urlretrieve`.
179
n199+ 
200+Utility functions
201+-----------------
180
181.. function:: quote(string[, safe])
182
183   Replace special characters in *string* using the ``%xx`` escape. Letters,
184   digits, and the characters ``'_.-'`` are never quoted. The optional *safe*
185   parameter specifies additional characters that should not be quoted --- its
186   default value is ``'/'``.
187
215   argument.  This is useful to pass a dictionary of form fields to a ``POST``
216   request.  The resulting string is a series of ``key=value`` pairs separated by
217   ``'&'`` characters, where both *key* and *value* are quoted using
218   :func:`quote_plus` above.  If the optional parameter *doseq* is present and
219   evaluates to true, individual ``key=value`` pairs are generated for each element
220   of the sequence. When a sequence of two-element tuples is used as the *query*
221   argument, the first element of each tuple is a key and the second is a value.
222   The order of parameters in the encoded string will match the order of parameter
n223-   tuples in the sequence. The :mod:`cgi` module provides the functions
n245+   tuples in the sequence. The :mod:`urlparse` module provides the functions
224   :func:`parse_qs` and :func:`parse_qsl` which are used to parse query strings
225   into Python data structures.
226
227
228.. function:: pathname2url(path)
229
230   Convert the pathname *path* from the local syntax for a path to the form used in
231   the path component of a URL.  This does not produce a complete URL.  The return
234
235.. function:: url2pathname(path)
236
237   Convert the path component *path* from an encoded URL to the local syntax for a
238   path.  This does not accept a complete URL.  This function uses :func:`unquote`
239   to decode *path*.
240
241
n264+URL Opener objects
265+------------------
266+ 
242.. class:: URLopener([proxies[, **x509]])
243
244   Base class for opening and reading URLs.  Unless you need to support opening
n245-   objects using schemes other than :file:`http:`, :file:`ftp:`, :file:`gopher:` or
n270+   objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
246-   :file:`file:`, you probably want to use :class:`FancyURLopener`.
271+   you probably want to use :class:`FancyURLopener`.
247
248   By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header
249   of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number.
250   Applications can define their own :mailheader:`User-Agent` header by subclassing
251   :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute
252   :attr:`version` to an appropriate string value in the subclass definition.
253
254   The optional *proxies* parameter should be a dictionary mapping scheme names to
258
259   Additional keyword parameters, collected in *x509*, may be used for
260   authentication of the client when using the :file:`https:` scheme.  The keywords
261   *key_file* and *cert_file* are supported to provide an  SSL key and certificate;
262   both are needed to support client authentication.
263
264   :class:`URLopener` objects will raise an :exc:`IOError` exception if the server
265   returns an error code.
n291+ 
292+    .. method:: open(fullurl[, data])
293+ 
294+       Open *fullurl* using the appropriate protocol.  This method sets up cache and
295+       proxy information, then calls the appropriate open method with its input
296+       arguments.  If the scheme is not recognized, :meth:`open_unknown` is called.
297+       The *data* argument has the same meaning as the *data* argument of
298+       :func:`urlopen`.
299+ 
300+ 
301+    .. method:: open_unknown(fullurl[, data])
302+ 
303+       Overridable interface to open unknown URL types.
304+ 
305+ 
306+    .. method:: retrieve(url[, filename[, reporthook[, data]]])
307+ 
308+       Retrieves the contents of *url* and places it in *filename*.  The return value
309+       is a tuple consisting of a local filename and either a
310+       :class:`mimetools.Message` object containing the response headers (for remote
311+       URLs) or ``None`` (for local URLs).  The caller must then open and read the
312+       contents of *filename*.  If *filename* is not given and the URL refers to a
313+       local file, the input filename is returned.  If the URL is non-local and
314+       *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
315+       with a suffix that matches the suffix of the last path component of the input
316+       URL.  If *reporthook* is given, it must be a function accepting three numeric
317+       parameters.  It will be called after each chunk of data is read from the
318+       network.  *reporthook* is ignored for local URLs.
319+ 
320+       If the *url* uses the :file:`http:` scheme identifier, the optional *data*
321+       argument may be given to specify a ``POST`` request (normally the request type
322+       is ``GET``).  The *data* argument must in standard
323+       :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
324+       function below.
325+ 
326+ 
327+    .. attribute:: version
328+ 
329+       Variable that specifies the user agent of the opener object.  To get
330+       :mod:`urllib` to tell servers that it is a particular user agent, set this in a
331+       subclass as a class variable or in the constructor before calling the base
332+       constructor.
266
267
268.. class:: FancyURLopener(...)
269
270   :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling
271   for the following HTTP response codes: 301, 302, 303, 307 and 401.  For the 30x
272   response codes listed above, the :mailheader:`Location` header is used to fetch
273   the actual URL.  For 401 response codes (authentication required), basic HTTP
288
289   .. note::
290
291      When performing basic authentication, a :class:`FancyURLopener` instance calls
292      its :meth:`prompt_user_passwd` method.  The default implementation asks the
293      users for the required information on the controlling terminal.  A subclass may
294      override this method to support more appropriate behavior if needed.
295
n363+    The :class:`FancyURLopener` class offers one additional method that should be
364+    overloaded to provide the appropriate behavior:
365+ 
366+    .. method:: prompt_user_passwd(host, realm)
367+ 
368+       Return information needed to authenticate the user at the given host in the
369+       specified security realm.  The return value should be a tuple, ``(user,
370+       password)``, which can be used for basic authentication.
371+ 
372+       The implementation prompts for this information on the terminal; an application
373+       should override this method to use an appropriate interaction model in the local
374+       environment.
296
297.. exception:: ContentTooShortError(msg[, content])
298
299   This exception is raised when the :func:`urlretrieve` function detects that the
300   amount of the downloaded data is less than the  expected amount (given by the
301   *Content-Length* header). The :attr:`content` attribute stores the downloaded
302   (and supposedly truncated) data.
303
304   .. versionadded:: 2.5
305
n306-Restrictions:
n385+ 
386+:mod:`urllib` Restrictions
387+--------------------------
307
308  .. index::
309     pair: HTTP; protocol
n310-     pair: Gopher; protocol
311     pair: FTP; protocol
312
313* Currently, only the following protocols are supported: HTTP, (versions 0.9 and
n314-  1.0), Gopher (but not Gopher-+), FTP, and local files.
n394+  1.0),  FTP, and local files.
315
316* The caching feature of :func:`urlretrieve` has been disabled until I find the
317  time to hack proper processing of Expiration time headers.
318
319* There should be a function to query whether a particular URL is in the cache.
320
321* For backward compatibility, if a URL appears to point to a local file but the
322  file can't be opened, the URL is re-interpreted using the FTP protocol.  This
325* The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily
326  long delays while waiting for a network connection to be set up.  This means
327  that it is difficult to build an interactive Web client using these functions
328  without using threads.
329
330  .. index::
331     single: HTML
332     pair: HTTP; protocol
n333-     pair: Gopher; protocol
334     module: htmllib
335
336* The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data
337  returned by the server.  This may be binary data (such as an image), plain text
338  or (for example) HTML.  The HTTP protocol provides type information in the reply
339  header, which can be inspected by looking at the :mailheader:`Content-Type`
n340-  header.  For the Gopher protocol, type information is encoded in the URL; there
n419+  header.  If the returned data is HTML, you can use the module :mod:`htmllib` to
341-  is currently no easy way to extract it.  If the returned data is HTML, you can
420+  parse it.
342-  use the module :mod:`htmllib` to parse it.
343
344  .. index:: single: FTP
345
346* The code handling the FTP protocol cannot differentiate between a file and a
347  directory.  This can lead to unexpected behavior when attempting to read a URL
348  that points to a file that is not accessible.  If the URL ends in a ``/``, it is
349  assumed to refer to a directory and will be handled accordingly.  But if an
350  attempt to read a file leads to a 550 error (meaning the URL cannot be found or
362
363  .. index:: module: urlparse
364
365* Although the :mod:`urllib` module contains (undocumented) routines to parse
366  and unparse URL strings, the recommended interface for URL manipulation is in
367  module :mod:`urlparse`.
368
369
n370-.. _urlopener-objs:
n448+.. _urllib-examples:
371- 
372-URLopener Objects
373------------------
374- 
375-.. sectionauthor:: Skip Montanaro <skip@mojam.com>
376- 
377- 
378-:class:`URLopener` and :class:`FancyURLopener` objects have the following
379-attributes.
380- 
381- 
382-.. method:: URLopener.open(fullurl[, data])
383- 
384-   Open *fullurl* using the appropriate protocol.  This method sets up cache and
385-   proxy information, then calls the appropriate open method with its input
386-   arguments.  If the scheme is not recognized, :meth:`open_unknown` is called.
387-   The *data* argument has the same meaning as the *data* argument of
388-   :func:`urlopen`.
389- 
390- 
391-.. method:: URLopener.open_unknown(fullurl[, data])
392- 
393-   Overridable interface to open unknown URL types.
394- 
395- 
396-.. method:: URLopener.retrieve(url[, filename[, reporthook[, data]]])
397- 
398-   Retrieves the contents of *url* and places it in *filename*.  The return value
399-   is a tuple consisting of a local filename and either a
400-   :class:`mimetools.Message` object containing the response headers (for remote
401-   URLs) or ``None`` (for local URLs).  The caller must then open and read the
402-   contents of *filename*.  If *filename* is not given and the URL refers to a
403-   local file, the input filename is returned.  If the URL is non-local and
404-   *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
405-   with a suffix that matches the suffix of the last path component of the input
406-   URL.  If *reporthook* is given, it must be a function accepting three numeric
407-   parameters.  It will be called after each chunk of data is read from the
408-   network.  *reporthook* is ignored for local URLs.
409- 
410-   If the *url* uses the :file:`http:` scheme identifier, the optional *data*
411-   argument may be given to specify a ``POST`` request (normally the request type
412-   is ``GET``).  The *data* argument must in standard
413-   :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
414-   function below.
415- 
416- 
417-.. attribute:: URLopener.version
418- 
419-   Variable that specifies the user agent of the opener object.  To get
420-   :mod:`urllib` to tell servers that it is a particular user agent, set this in a
421-   subclass as a class variable or in the constructor before calling the base
422-   constructor.
423- 
424-The :class:`FancyURLopener` class offers one additional method that should be
425-overloaded to provide the appropriate behavior:
426- 
427- 
428-.. method:: FancyURLopener.prompt_user_passwd(host, realm)
429- 
430-   Return information needed to authenticate the user at the given host in the
431-   specified security realm.  The return value should be a tuple, ``(user,
432-   password)``, which can be used for basic authentication.
433- 
434-   The implementation prompts for this information on the terminal; an application
435-   should override this method to use an appropriate interaction model in the local
436-   environment.
437- 
438
439Examples
440--------
t441- 
442-.. _urllib examples:
443
444Here is an example session that uses the ``GET`` method to retrieve a URL
445containing parameters::
446
447   >>> import urllib
448   >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
449   >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
450   >>> print f.read()
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op