rest25/library/urllib2.rst => rest262/library/urllib2.rst
n1- 
2:mod:`urllib2` --- extensible library for opening URLs
3======================================================
4
5.. module:: urllib2
n5+   :synopsis: Next generation URL opening library.
6.. moduleauthor:: Jeremy Hylton <jhylton@users.sourceforge.net>
7.. sectionauthor:: Moshe Zadka <moshez@users.sourceforge.net>
8
9
n10+.. note::
11+   The :mod:`urllib2` module has been split across several modules in
12+   Python 3.0 named :mod:`urllib.request` and :mod:`urllib.error`.
13+   The :term:`2to3` tool will automatically adapt imports when converting
14+   your sources to 3.0.
10
11
12The :mod:`urllib2` module defines functions and classes which help in opening
13URLs (mostly HTTP) in a complex world --- basic and digest authentication,
14redirections, cookies and more.
15
16The :mod:`urllib2` module defines the following functions:
17
18
n19-.. function:: urlopen(url[, data])
n24+.. function:: urlopen(url[, data][, timeout])
20
21   Open the URL *url*, which can be either a string or a :class:`Request` object.
22
23   *data* may be a string specifying additional data to send to the server, or
24   ``None`` if no such data is needed.  Currently HTTP requests are the only ones
25   that use *data*; the HTTP request will be a POST instead of a GET when the
26   *data* parameter is provided.  *data* should be a buffer in the standard
27   :mimetype:`application/x-www-form-urlencoded` format.  The
28   :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
29   returns a string in this format.
30
n36+   The optional *timeout* parameter specifies a timeout in seconds for blocking
37+   operations like the connection attempt (if not specified, the global default
38+   timeout setting will be used).  This actually only works for HTTP, HTTPS,
39+   FTP and FTPS connections.
40+ 
31   This function returns a file-like object with two additional methods:
32
n33-* :meth:`geturl` --- return the URL of the resource retrieved
n43+   * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to
44+     determine if a redirect was followed
34
n35-* :meth:`info` --- return the meta-information of the page, as a dictionary-like
n46+   * :meth:`info` --- return the meta-information of the page, such as headers, in
36-     object
47+     the form of an ``httplib.HTTPMessage`` instance
48+     (see `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
37
38   Raises :exc:`URLError` on errors.
39
40   Note that ``None`` may be returned if no handler handles the request (though the
41   default installed global :class:`OpenerDirector` uses :class:`UnknownHandler` to
42   ensure this never happens).
n55+ 
56+   .. versionchanged:: 2.6
57+      *timeout* was added.
43
44
45.. function:: install_opener(opener)
46
47   Install an :class:`OpenerDirector` instance as the default global opener.
48   Installing an opener is only necessary if you want urlopen to use that opener;
49   otherwise, simply call :meth:`OpenerDirector.open` instead of :func:`urlopen`.
50   The code does not check for a real :class:`OpenerDirector`, and any class with
51   the appropriate interface will work.
52
53
54.. function:: build_opener([handler, ...])
55
56   Return an :class:`OpenerDirector` instance, which chains the handlers in the
n57-   order given. *handler*s can be either instances of :class:`BaseHandler`, or
n72+   order given. *handler*\s can be either instances of :class:`BaseHandler`, or
58   subclasses of :class:`BaseHandler` (in which case it must be possible to call
59   the constructor without any parameters).  Instances of the following classes
n60-   will be in front of the *handler*s, unless the *handler*s contain them,
n75+   will be in front of the *handler*\s, unless the *handler*\s contain them,
61   instances of them or subclasses of them: :class:`ProxyHandler`,
62   :class:`UnknownHandler`, :class:`HTTPHandler`, :class:`HTTPDefaultErrorHandler`,
63   :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
64   :class:`HTTPErrorProcessor`.
65
n66-   If the Python installation has SSL support (:func:`socket.ssl` exists),
n81+   If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported),
67   :class:`HTTPSHandler` will also be added.
68
69   Beginning in Python 2.3, a :class:`BaseHandler` subclass may also change its
70   :attr:`handler_order` member variable to modify its position in the handlers
71   list.
72
73The following exceptions are raised as appropriate:
74
75
76.. exception:: URLError
77
78   The handlers raise this exception (or derived exceptions) when they run into a
79   problem.  It is a subclass of :exc:`IOError`.
80
n96+   .. attribute:: reason
97+ 
98+      The reason for this error.  It can be a message string or another exception
99+      instance (:exc:`socket.error` for remote URLs, :exc:`OSError` for local
100+      URLs).
101+ 
81
82.. exception:: HTTPError
83
n84-   A subclass of :exc:`URLError`, it can also function as a  non-exceptional file-
n105+   Though being an exception (a subclass of :exc:`URLError`), an :exc:`HTTPError`
85-   like return value (the same thing that :func:`urlopen` returns).  This is useful
106+   can also function as a non-exceptional file-like return value (the same thing
107+   that :func:`urlopen` returns).  This is useful when handling exotic HTTP
86-   when handling exotic HTTP errors, such as requests for authentication.
108+   errors, such as requests for authentication.
87
n110+   .. attribute:: code
88
n89-.. exception:: GopherError
n112+      An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_.
113+      This numeric value corresponds to a value found in the dictionary of
114+      codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`.
90
n91-   A subclass of :exc:`URLError`, this is the error raised by the Gopher handler.
n116+ 
92
93The following classes are provided:
94
95
n96-.. class:: Request(url[, data][, headers] [, origin_req_host][, unverifiable])
n121+.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable])
97
98   This class is an abstraction of a URL request.
99
100   *url* should be a string containing a valid URL.
101
102   *data* may be a string specifying additional data to send to the server, or
103   ``None`` if no such data is needed.  Currently HTTP requests are the only ones
104   that use *data*; the HTTP request will be a POST instead of a GET when the
105   *data* parameter is provided.  *data* should be a buffer in the standard
106   :mimetype:`application/x-www-form-urlencoded` format.  The
107   :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
108   returns a string in this format.
109
110   *headers* should be a dictionary, and will be treated as if :meth:`add_header`
n111-   was called with each key and value as arguments.
n136+   was called with each key and value as arguments.  This is often used to "spoof"
137+   the ``User-Agent`` header, which is used by a browser to identify itself --
138+   some HTTP servers only allow requests coming from common browsers as opposed
139+   to scripts.  For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0
140+   (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib2`'s
141+   default user agent string is ``"Python-urllib/2.6"`` (on Python 2.6).
112
113   The final two arguments are only of interest for correct handling of third-party
114   HTTP cookies:
115
116   *origin_req_host* should be the request-host of the origin transaction, as
117   defined by :rfc:`2965`.  It defaults to ``cookielib.request_host(self)``.  This
118   is the host name or IP address of the original request that was initiated by the
119   user.  For example, if the request is for an image in an HTML document, this
154   A class to handle HTTP Cookies.
155
156
157.. class:: ProxyHandler([proxies])
158
159   Cause requests to go through a proxy. If *proxies* is given, it must be a
160   dictionary mapping protocol names to URLs of proxies. The default is to read the
161   list of proxies from the environment variables :envvar:`<protocol>_proxy`.
n192+   To disable autodetected proxy pass an empty dictionary.
162
163
164.. class:: HTTPPasswordMgr()
165
166   Keep a database of  ``(realm, uri) -> (user, password)`` mappings.
167
168
169.. class:: HTTPPasswordMgrWithDefaultRealm()
241.. class:: FTPHandler()
242
243   Open FTP URLs.
244
245
246.. class:: CacheFTPHandler()
247
248   Open FTP URLs, keeping a cache of open FTP connections to minimize delays.
n249- 
250- 
251-.. class:: GopherHandler()
252- 
253-   Open gopher URLs.
254
255
256.. class:: UnknownHandler()
257
258   A catch-all class to handle unknown URLs.
259
260
261.. _request-objects:
360OpenerDirector Objects
361----------------------
362
363:class:`OpenerDirector` instances have the following methods:
364
365
366.. method:: OpenerDirector.add_handler(handler)
367
n368-   *handler* should be an instance of :class:`BaseHandler`.  The following methods
n394+   *handler* should be an instance of :class:`BaseHandler`.  The following
369-   are searched, and added to the possible chains (note that HTTP errors are a
395+   methods are searched, and added to the possible chains (note that HTTP errors
370-   special case).
396+   are a special case).
371
n372-* :meth:`protocol_open` --- signal that the handler knows how to open *protocol*
n398+   * :samp:`{protocol}_open` --- signal that the handler knows how to open
373-     URLs.
399+     *protocol* URLs.
374
n375-* :meth:`http_error_type` --- signal that the handler knows how to handle HTTP
n401+   * :samp:`http_error_{type}` --- signal that the handler knows how to handle
376-     errors with HTTP error code *type*.
402+     HTTP errors with HTTP error code *type*.
377
n378-* :meth:`protocol_error` --- signal that the handler knows how to handle errors
n404+   * :samp:`{protocol}_error` --- signal that the handler knows how to handle
379-     from (non-\ ``http``) *protocol*.
405+     errors from (non-\ ``http``) *protocol*.
380
n381-* :meth:`protocol_request` --- signal that the handler knows how to pre-process
n407+   * :samp:`{protocol}_request` --- signal that the handler knows how to
382-     *protocol* requests.
408+     pre-process *protocol* requests.
383
n384-* :meth:`protocol_response` --- signal that the handler knows how to post-
n410+   * :samp:`{protocol}_response` --- signal that the handler knows how to
385-     process *protocol* responses.
411+     post-process *protocol* responses.
386
387
n388-.. method:: OpenerDirector.open(url[, data])
n414+.. method:: OpenerDirector.open(url[, data][, timeout])
389
390   Open the given *url* (which can be a request object or a string), optionally
n391-   passing the given *data*. Arguments, return values and exceptions raised are the
n417+   passing the given *data*. Arguments, return values and exceptions raised are
392-   same as those of :func:`urlopen` (which simply calls the :meth:`open` method on
418+   the same as those of :func:`urlopen` (which simply calls the :meth:`open`
393-   the currently installed global :class:`OpenerDirector`).
419+   method on the currently installed global :class:`OpenerDirector`).  The
420+   optional *timeout* parameter specifies a timeout in seconds for blocking
421+   operations like the connection attempt (if not specified, the global default
422+   timeout setting will be usedi). The timeout feature actually works only for
423+   HTTP, HTTPS, FTP and FTPS connections).
424+ 
425+   .. versionchanged:: 2.6
426+      *timeout* was added.
394
395
396.. method:: OpenerDirector.error(proto[, arg[, ...]])
397
398   Handle an error of the given protocol.  This will call the registered error
399   handlers for the given protocol with the given arguments (which are protocol
400   specific).  The HTTP protocol is a special case which uses the HTTP response
401   code to determine the specific error handler; refer to the :meth:`http_error_\*`
403
404   Return values and exceptions raised are the same as those of :func:`urlopen`.
405
406OpenerDirector objects open URLs in three stages:
407
408The order in which these methods are called within each stage is determined by
409sorting the handler instances.
410
n411-#. Every handler with a method named like :meth:`protocol_request` has that
n444+#. Every handler with a method named like :samp:`{protocol}_request` has that
412   method called to pre-process the request.
413
n414-#. Handlers with a method named like :meth:`protocol_open` are called to handle
n447+#. Handlers with a method named like :samp:`{protocol}_open` are called to handle
415   the request. This stage ends when a handler either returns a non-\ :const:`None`
416   value (ie. a response), or raises an exception (usually :exc:`URLError`).
417   Exceptions are allowed to propagate.
418
419   In fact, the above algorithm is first tried for methods named
n420-   :meth:`default_open`.  If all such methods return :const:`None`, the algorithm
n453+   :meth:`default_open`.  If all such methods return :const:`None`, the
421-   is repeated for methods named like :meth:`protocol_open`.  If all such methods
454+   algorithm is repeated for methods named like :samp:`{protocol}_open`.  If all
422-   return :const:`None`, the algorithm is repeated for methods named
455+   such methods return :const:`None`, the algorithm is repeated for methods
423-   :meth:`unknown_open`.
456+   named :meth:`unknown_open`.
424
425   Note that the implementation of these methods may involve calls of the parent
426   :class:`OpenerDirector` instance's :meth:`.open` and :meth:`.error` methods.
427
n428-#. Every handler with a method named like :meth:`protocol_response` has that
n461+#. Every handler with a method named like :samp:`{protocol}_response` has that
429   method called to post-process the response.
430
431
432.. _base-handler-objects:
433
434BaseHandler Objects
435-------------------
436
476   example, :exc:`MemoryError` should not be mapped to :exc:`URLError`).
477
478   This method will be called before any protocol-specific open method.
479
480
481.. method:: BaseHandler.protocol_open(req)
482   :noindex:
483
n517+   ("protocol" is to be replaced by the protocol name.)
518+ 
484   This method is *not* defined in :class:`BaseHandler`, but subclasses should
n485-   define it if they want to handle URLs with the given protocol.
n520+   define it if they want to handle URLs with the given *protocol*.
486
487   This method, if defined, will be called by the parent :class:`OpenerDirector`.
488   Return values should be the same as for  :meth:`default_open`.
489
490
491.. method:: BaseHandler.unknown_open(req)
492
493   This method is *not* defined in :class:`BaseHandler`, but subclasses should
525
526   Arguments, return values and exceptions raised should be the same as for
527   :meth:`http_error_default`.
528
529
530.. method:: BaseHandler.protocol_request(req)
531   :noindex:
532
n568+   ("protocol" is to be replaced by the protocol name.)
569+ 
533   This method is *not* defined in :class:`BaseHandler`, but subclasses should
n534-   define it if they want to pre-process requests of the given protocol.
n571+   define it if they want to pre-process requests of the given *protocol*.
535
536   This method, if defined, will be called by the parent :class:`OpenerDirector`.
537   *req* will be a :class:`Request` object. The return value should be a
538   :class:`Request` object.
539
540
541.. method:: BaseHandler.protocol_response(req, response)
542   :noindex:
543
n581+   ("protocol" is to be replaced by the protocol name.)
582+ 
544   This method is *not* defined in :class:`BaseHandler`, but subclasses should
n545-   define it if they want to post-process responses of the given protocol.
n584+   define it if they want to post-process responses of the given *protocol*.
546
547   This method, if defined, will be called by the parent :class:`OpenerDirector`.
548   *req* will be a :class:`Request` object. *response* will be an object
549   implementing the same interface as the return value of :func:`urlopen`.  The
550   return value should implement the same interface as the return value of
551   :func:`urlopen`.
552
553
558
559.. note::
560
561   Some HTTP redirections require action from this module's client code.  If this
562   is the case, :exc:`HTTPError` is raised.  See :rfc:`2616` for details of the
563   precise meanings of the various redirection codes.
564
565
n566-.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs)
n605+.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)
567
568   Return a :class:`Request` or ``None`` in response to a redirect. This is called
569   by the default implementations of the :meth:`http_error_30\*` methods when a
570   redirection is received from the server.  If a redirection should take place,
571   return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the
n572-   redirect.  Otherwise, raise :exc:`HTTPError` if no other handler should try to
n611+   redirect to *newurl*.  Otherwise, raise :exc:`HTTPError` if no other handler
573-   handle this URL, or return ``None`` if you can't but another handler might.
612+   should try to handle this URL, or return ``None`` if you can't but another
613+   handler might.
574
575   .. note::
576
577      The default implementation of this method does not strictly follow :rfc:`2616`,
578      which says that 301 and 302 responses to ``POST`` requests must not be
579      automatically redirected without confirmation by the user.  In reality, browsers
580      do allow automatic redirection of these responses, changing the POST to a
581      ``GET``, and the default implementation reproduces this behavior.
582
583
584.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)
585
n586-   Redirect to the ``Location:`` URL.  This method is called by the parent
n626+   Redirect to the ``Location:`` or ``URI:`` URL.  This method is called by the
587-   :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.
627+   parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.
588
589
590.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)
591
592   The same as :meth:`http_error_301`, but called for the 'found' response.
593
594
595.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)
608HTTPCookieProcessor Objects
609---------------------------
610
611.. versionadded:: 2.4
612
613:class:`HTTPCookieProcessor` instances have one attribute:
614
615
n616-.. attribute:: XXX Class.cookiejar
n656+.. attribute:: HTTPCookieProcessor.cookiejar
617
618   The :class:`cookielib.CookieJar` in which cookies are stored.
619
620
621.. _proxy-handler:
622
623ProxyHandler Objects
624--------------------
625
626
627.. method:: ProxyHandler.protocol_open(request)
628   :noindex:
629
n670+   ("protocol" is to be replaced by the protocol name.)
671+ 
630-   The :class:`ProxyHandler` will have a method :meth:`protocol_open` for every
672+   The :class:`ProxyHandler` will have a method :samp:`{protocol}_open` for every
631   *protocol* which has a proxy in the *proxies* dictionary given in the
632   constructor.  The method will modify requests to go through the proxy, by
633   calling ``request.set_proxy()``, and call the next handler in the chain to
634   actually execute the protocol.
635
636
637.. _http-password-mgr:
638
801   Set timeout of connections to *t* seconds.
802
803
804.. method:: CacheFTPHandler.setMaxConns(m)
805
806   Set maximum number of cached connections to *m*.
807
808
n809-.. _gopher-handler:
810- 
811-GopherHandler Objects
812----------------------
813- 
814- 
815-.. method:: GopherHandler.gopher_open(req)
816- 
817-   Open the gopher resource indicated by *req*.
818- 
819- 
820.. _unknown-handler-objects:
821
822UnknownHandler Objects
823----------------------
824
825
826.. method:: UnknownHandler.unknown_open()
827
838
839.. method:: HTTPErrorProcessor.unknown_open()
840
841   Process HTTP error responses.
842
843   For 200 error codes, the response object is returned immediately.
844
845   For non-200 error codes, this simply passes the job on to the
n846-   :meth:`protocol_error_code` handler methods, via :meth:`OpenerDirector.error`.
n877+   :samp:`{protocol}_error_code` handler methods, via
878+   :meth:`OpenerDirector.error`.  Eventually,
847-   Eventually, :class:`urllib2.HTTPDefaultErrorHandler` will raise an
879+   :class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no
848-   :exc:`HTTPError` if no other handler handles the error.
880+   other handler handles the error.
849
850
851.. _urllib2-examples:
852
853Examples
854--------
855
856This example gets the python.org main page and displays the first 100 bytes of
880   data = sys.stdin.read()
881   print 'Content-type: text-plain\n\nGot Data: "%s"' % data
882
883Use of Basic HTTP Authentication::
884
885   import urllib2
886   # Create an OpenerDirector with support for Basic HTTP Authentication...
887   auth_handler = urllib2.HTTPBasicAuthHandler()
n888-   auth_handler.add_password('realm', 'host', 'username', 'password')
n920+   auth_handler.add_password(realm='PDQ Application',
921+                             uri='https://mahler:8092/site-updates.py',
922+                             user='klem',
923+                             passwd='kadidd!ehopper')
889   opener = urllib2.build_opener(auth_handler)
890   # ...and install it globally so it can be used with urlopen.
891   urllib2.install_opener(opener)
892   urllib2.urlopen('http://www.example.com/login.html')
893
894:func:`build_opener` provides many handlers by default, including a
895:class:`ProxyHandler`.  By default, :class:`ProxyHandler` uses the environment
896variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme
897involved.  For example, the :envvar:`http_proxy` environment variable is read to
898obtain the HTTP proxy's URL.
899
900This example replaces the default :class:`ProxyHandler` with one that uses
t901-programatically-supplied proxy URLs, and adds proxy authorization support with
t936+programmatically-supplied proxy URLs, and adds proxy authorization support with
902:class:`ProxyBasicAuthHandler`. ::
903
904   proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
905   proxy_auth_handler = urllib2.HTTPBasicAuthHandler()
906   proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
907
908   opener = build_opener(proxy_handler, proxy_auth_handler)
909   # This time, rather than install the OpenerDirector, we use it directly:
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op