blob: f599894adcbc2555dd4bb6b678196007d3ac2a84 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`urllib2` --- extensible library for opening URLs
2======================================================
3
4.. module:: urllib2
5 :synopsis: Next generation URL opening library.
6.. moduleauthor:: Jeremy Hylton <jhylton@users.sourceforge.net>
7.. sectionauthor:: Moshe Zadka <moshez@users.sourceforge.net>
8
9
Brett Cannon97aa1ae2008-07-11 00:12:52 +000010.. note::
11 The :mod:`urllib2` module has been split across several modules in
Ezio Melotti510ff542012-05-03 19:21:40 +030012 Python 3 named :mod:`urllib.request` and :mod:`urllib.error`.
Brett Cannon97aa1ae2008-07-11 00:12:52 +000013 The :term:`2to3` tool will automatically adapt imports when converting
Ezio Melotti510ff542012-05-03 19:21:40 +030014 your sources to Python 3.
Brett Cannon97aa1ae2008-07-11 00:12:52 +000015
16
Georg Brandl8ec7f652007-08-15 14:28:01 +000017The :mod:`urllib2` module defines functions and classes which help in opening
18URLs (mostly HTTP) in a complex world --- basic and digest authentication,
19redirections, cookies and more.
20
Antoine Pitrou66bfda82010-09-29 11:30:52 +000021
Georg Brandl8ec7f652007-08-15 14:28:01 +000022The :mod:`urllib2` module defines the following functions:
23
24
Benjamin Petersonfcfb18e2014-11-23 11:42:45 -060025.. function:: urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000026
27 Open the URL *url*, which can be either a string or a :class:`Request` object.
28
29 *data* may be a string specifying additional data to send to the server, or
30 ``None`` if no such data is needed. Currently HTTP requests are the only ones
31 that use *data*; the HTTP request will be a POST instead of a GET when the
32 *data* parameter is provided. *data* should be a buffer in the standard
33 :mimetype:`application/x-www-form-urlencoded` format. The
34 :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
Senthil Kumaranb7575ee2010-08-21 16:14:54 +000035 returns a string in this format. urllib2 module sends HTTP/1.1 requests with
Éric Araujoa7cbe282011-09-01 19:49:31 +020036 ``Connection:close`` header included.
Georg Brandl8ec7f652007-08-15 14:28:01 +000037
Georg Brandlab756f62008-05-11 11:09:35 +000038 The optional *timeout* parameter specifies a timeout in seconds for blocking
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000039 operations like the connection attempt (if not specified, the global default
Senthil Kumaran30630b92010-10-05 18:45:00 +000040 timeout setting will be used). This actually only works for HTTP, HTTPS and
Ned Deily40ce0142014-11-23 20:55:55 -080041 FTP connections.
Benjamin Petersonfcfb18e2014-11-23 11:42:45 -060042
43 If *context* is specified, it must be a :class:`ssl.SSLContext` instance
44 describing the various SSL options. See :class:`~httplib.HTTPSConnection` for
45 more details.
46
47 The optional *cafile* and *capath* parameters specify a set of trusted CA
48 certificates for HTTPS requests. *cafile* should point to a single file
49 containing a bundle of CA certificates, whereas *capath* should point to a
50 directory of hashed certificate files. More information can be found in
51 :meth:`ssl.SSLContext.load_verify_locations`.
52
53 The *cadefault* parameter is ignored.
Georg Brandl8ec7f652007-08-15 14:28:01 +000054
Berker Peksag86af3102014-06-28 03:12:37 +030055 This function returns a file-like object with three additional methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +000056
Georg Brandl586a57a2008-02-02 09:56:20 +000057 * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to
58 determine if a redirect was followed
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
Senthil Kumaran8c996ef2010-06-28 17:07:40 +000060 * :meth:`info` --- return the meta-information of the page, such as headers,
61 in the form of an :class:`mimetools.Message` instance
Georg Brandl586a57a2008-02-02 09:56:20 +000062 (see `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
Senthil Kumaran785d1b12013-02-07 00:51:34 -080064 * :meth:`getcode` --- return the HTTP status code of the response.
65
Georg Brandl8ec7f652007-08-15 14:28:01 +000066 Raises :exc:`URLError` on errors.
67
68 Note that ``None`` may be returned if no handler handles the request (though the
69 default installed global :class:`OpenerDirector` uses :class:`UnknownHandler` to
70 ensure this never happens).
71
R David Murray806c1c92013-04-28 11:16:21 -040072 In addition, if proxy settings are detected (for example, when a ``*_proxy``
73 environment variable like :envvar:`http_proxy` is set),
74 :class:`ProxyHandler` is default installed and makes sure the requests are
75 handled through the proxy.
Senthil Kumaran45a505f2009-10-18 01:24:41 +000076
Georg Brandl8ec7f652007-08-15 14:28:01 +000077 .. versionchanged:: 2.6
Benjamin Petersonfcfb18e2014-11-23 11:42:45 -060078 *timeout* was added.
79
80 .. versionchanged:: 2.7.9
81 *cafile*, *capath*, *cadefault*, and *context* were added.
Georg Brandl8ec7f652007-08-15 14:28:01 +000082
83
84.. function:: install_opener(opener)
85
86 Install an :class:`OpenerDirector` instance as the default global opener.
87 Installing an opener is only necessary if you want urlopen to use that opener;
88 otherwise, simply call :meth:`OpenerDirector.open` instead of :func:`urlopen`.
89 The code does not check for a real :class:`OpenerDirector`, and any class with
90 the appropriate interface will work.
91
92
93.. function:: build_opener([handler, ...])
94
95 Return an :class:`OpenerDirector` instance, which chains the handlers in the
96 order given. *handler*\s can be either instances of :class:`BaseHandler`, or
97 subclasses of :class:`BaseHandler` (in which case it must be possible to call
98 the constructor without any parameters). Instances of the following classes
99 will be in front of the *handler*\s, unless the *handler*\s contain them,
R David Murray806c1c92013-04-28 11:16:21 -0400100 instances of them or subclasses of them: :class:`ProxyHandler` (if proxy
101 settings are detected),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000102 :class:`UnknownHandler`, :class:`HTTPHandler`, :class:`HTTPDefaultErrorHandler`,
103 :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
104 :class:`HTTPErrorProcessor`.
105
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000106 If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107 :class:`HTTPSHandler` will also be added.
108
109 Beginning in Python 2.3, a :class:`BaseHandler` subclass may also change its
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700110 :attr:`handler_order` attribute to modify its position in the handlers
Georg Brandl8ec7f652007-08-15 14:28:01 +0000111 list.
112
113The following exceptions are raised as appropriate:
114
115
116.. exception:: URLError
117
118 The handlers raise this exception (or derived exceptions) when they run into a
119 problem. It is a subclass of :exc:`IOError`.
120
Georg Brandl586a57a2008-02-02 09:56:20 +0000121 .. attribute:: reason
122
123 The reason for this error. It can be a message string or another exception
124 instance (:exc:`socket.error` for remote URLs, :exc:`OSError` for local
125 URLs).
126
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128.. exception:: HTTPError
129
Georg Brandl586a57a2008-02-02 09:56:20 +0000130 Though being an exception (a subclass of :exc:`URLError`), an :exc:`HTTPError`
131 can also function as a non-exceptional file-like return value (the same thing
132 that :func:`urlopen` returns). This is useful when handling exotic HTTP
133 errors, such as requests for authentication.
134
135 .. attribute:: code
136
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000137 An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_.
Georg Brandl586a57a2008-02-02 09:56:20 +0000138 This numeric value corresponds to a value found in the dictionary of
139 codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`.
140
Senthil Kumaranbfb09892012-12-09 13:36:40 -0800141 .. attribute:: reason
Georg Brandl586a57a2008-02-02 09:56:20 +0000142
Senthil Kumaranbfb09892012-12-09 13:36:40 -0800143 The reason for this error. It can be a message string or another exception
144 instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000145
146The following classes are provided:
147
148
Georg Brandl586a57a2008-02-02 09:56:20 +0000149.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151 This class is an abstraction of a URL request.
152
153 *url* should be a string containing a valid URL.
154
155 *data* may be a string specifying additional data to send to the server, or
156 ``None`` if no such data is needed. Currently HTTP requests are the only ones
157 that use *data*; the HTTP request will be a POST instead of a GET when the
158 *data* parameter is provided. *data* should be a buffer in the standard
159 :mimetype:`application/x-www-form-urlencoded` format. The
160 :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
161 returns a string in this format.
162
163 *headers* should be a dictionary, and will be treated as if :meth:`add_header`
Georg Brandl586a57a2008-02-02 09:56:20 +0000164 was called with each key and value as arguments. This is often used to "spoof"
165 the ``User-Agent`` header, which is used by a browser to identify itself --
166 some HTTP servers only allow requests coming from common browsers as opposed
167 to scripts. For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0
168 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib2`'s
169 default user agent string is ``"Python-urllib/2.6"`` (on Python 2.6).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000170
171 The final two arguments are only of interest for correct handling of third-party
172 HTTP cookies:
173
174 *origin_req_host* should be the request-host of the origin transaction, as
175 defined by :rfc:`2965`. It defaults to ``cookielib.request_host(self)``. This
176 is the host name or IP address of the original request that was initiated by the
177 user. For example, if the request is for an image in an HTML document, this
178 should be the request-host of the request for the page containing the image.
179
180 *unverifiable* should indicate whether the request is unverifiable, as defined
Serhiy Storchaka26d936a2013-11-29 12:16:53 +0200181 by RFC 2965. It defaults to ``False``. An unverifiable request is one whose URL
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182 the user did not have the option to approve. For example, if the request is for
183 an image in an HTML document, and the user had no option to approve the
184 automatic fetching of the image, this should be true.
185
186
187.. class:: OpenerDirector()
188
189 The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained
190 together. It manages the chaining of handlers, and recovery from errors.
191
192
193.. class:: BaseHandler()
194
195 This is the base class for all registered handlers --- and handles only the
196 simple mechanics of registration.
197
198
199.. class:: HTTPDefaultErrorHandler()
200
201 A class which defines a default handler for HTTP error responses; all responses
202 are turned into :exc:`HTTPError` exceptions.
203
204
205.. class:: HTTPRedirectHandler()
206
207 A class to handle redirections.
208
209
210.. class:: HTTPCookieProcessor([cookiejar])
211
212 A class to handle HTTP Cookies.
213
214
215.. class:: ProxyHandler([proxies])
216
217 Cause requests to go through a proxy. If *proxies* is given, it must be a
Senthil Kumaran45a505f2009-10-18 01:24:41 +0000218 dictionary mapping protocol names to URLs of proxies. The default is to read
219 the list of proxies from the environment variables
R David Murray806c1c92013-04-28 11:16:21 -0400220 :envvar:`<protocol>_proxy`. If no proxy environment variables are set, then
221 in a Windows environment proxy settings are obtained from the registry's
222 Internet Settings section, and in a Mac OS X environment proxy information
Senthil Kumaran83f1ef62009-10-18 01:58:45 +0000223 is retrieved from the OS X System Configuration Framework.
Senthil Kumaran45a505f2009-10-18 01:24:41 +0000224
Sean Reifscheider45ea86c2008-03-20 03:20:48 +0000225 To disable autodetected proxy pass an empty dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
227
228.. class:: HTTPPasswordMgr()
229
230 Keep a database of ``(realm, uri) -> (user, password)`` mappings.
231
232
233.. class:: HTTPPasswordMgrWithDefaultRealm()
234
235 Keep a database of ``(realm, uri) -> (user, password)`` mappings. A realm of
236 ``None`` is considered a catch-all realm, which is searched if no other realm
237 fits.
238
239
240.. class:: AbstractBasicAuthHandler([password_mgr])
241
242 This is a mixin class that helps with HTTP authentication, both to the remote
243 host and to a proxy. *password_mgr*, if given, should be something that is
244 compatible with :class:`HTTPPasswordMgr`; refer to section
245 :ref:`http-password-mgr` for information on the interface that must be
246 supported.
247
248
249.. class:: HTTPBasicAuthHandler([password_mgr])
250
251 Handle authentication with the remote host. *password_mgr*, if given, should be
252 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
253 :ref:`http-password-mgr` for information on the interface that must be
254 supported.
255
256
257.. class:: ProxyBasicAuthHandler([password_mgr])
258
259 Handle authentication with the proxy. *password_mgr*, if given, should be
260 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
261 :ref:`http-password-mgr` for information on the interface that must be
262 supported.
263
264
265.. class:: AbstractDigestAuthHandler([password_mgr])
266
267 This is a mixin class that helps with HTTP authentication, both to the remote
268 host and to a proxy. *password_mgr*, if given, should be something that is
269 compatible with :class:`HTTPPasswordMgr`; refer to section
270 :ref:`http-password-mgr` for information on the interface that must be
271 supported.
272
273
274.. class:: HTTPDigestAuthHandler([password_mgr])
275
276 Handle authentication with the remote host. *password_mgr*, if given, should be
277 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
278 :ref:`http-password-mgr` for information on the interface that must be
279 supported.
280
281
282.. class:: ProxyDigestAuthHandler([password_mgr])
283
284 Handle authentication with the proxy. *password_mgr*, if given, should be
285 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
286 :ref:`http-password-mgr` for information on the interface that must be
287 supported.
288
289
290.. class:: HTTPHandler()
291
292 A class to handle opening of HTTP URLs.
293
294
Benjamin Peterson73d50312014-12-07 14:25:38 -0500295.. class:: HTTPSHandler([debuglevel[, context]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296
Benjamin Peterson73d50312014-12-07 14:25:38 -0500297 A class to handle opening of HTTPS URLs. *context* has the same meaning as
298 for :class:`httplib.HTTPSConnection`.
Benjamin Petersonfcfb18e2014-11-23 11:42:45 -0600299
300 .. versionchanged:: 2.7.9
Benjamin Peterson73d50312014-12-07 14:25:38 -0500301 *context* added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
303
304.. class:: FileHandler()
305
306 Open local files.
307
308
309.. class:: FTPHandler()
310
311 Open FTP URLs.
312
313
314.. class:: CacheFTPHandler()
315
316 Open FTP URLs, keeping a cache of open FTP connections to minimize delays.
317
318
319.. class:: UnknownHandler()
320
321 A catch-all class to handle unknown URLs.
322
323
Senthil Kumaran612b2b32011-07-18 06:44:11 +0800324.. class:: HTTPErrorProcessor()
325
326 Process HTTP error responses.
327
328
Georg Brandl8ec7f652007-08-15 14:28:01 +0000329.. _request-objects:
330
331Request Objects
332---------------
333
334The following methods describe all of :class:`Request`'s public interface, and
335so all must be overridden in subclasses.
336
337
338.. method:: Request.add_data(data)
339
340 Set the :class:`Request` data to *data*. This is ignored by all handlers except
341 HTTP handlers --- and there it should be a byte string, and will change the
342 request to be ``POST`` rather than ``GET``.
343
344
345.. method:: Request.get_method()
346
347 Return a string indicating the HTTP request method. This is only meaningful for
348 HTTP requests, and currently always returns ``'GET'`` or ``'POST'``.
349
350
351.. method:: Request.has_data()
352
353 Return whether the instance has a non-\ ``None`` data.
354
355
356.. method:: Request.get_data()
357
358 Return the instance's data.
359
360
361.. method:: Request.add_header(key, val)
362
363 Add another header to the request. Headers are currently ignored by all
364 handlers except HTTP handlers, where they are added to the list of headers sent
365 to the server. Note that there cannot be more than one header with the same
366 name, and later calls will overwrite previous calls in case the *key* collides.
367 Currently, this is no loss of HTTP functionality, since all headers which have
368 meaning when used more than once have a (header-specific) way of gaining the
369 same functionality using only one header.
370
371
372.. method:: Request.add_unredirected_header(key, header)
373
374 Add a header that will not be added to a redirected request.
375
376 .. versionadded:: 2.4
377
378
379.. method:: Request.has_header(header)
380
381 Return whether the instance has the named header (checks both regular and
382 unredirected).
383
384 .. versionadded:: 2.4
385
386
387.. method:: Request.get_full_url()
388
389 Return the URL given in the constructor.
390
391
392.. method:: Request.get_type()
393
394 Return the type of the URL --- also known as the scheme.
395
396
397.. method:: Request.get_host()
398
399 Return the host to which a connection will be made.
400
401
402.. method:: Request.get_selector()
403
404 Return the selector --- the part of the URL that is sent to the server.
405
406
Senthil Kumaran429d3112012-04-29 11:52:59 +0800407.. method:: Request.get_header(header_name, default=None)
408
409 Return the value of the given header. If the header is not present, return
410 the default value.
411
412
413.. method:: Request.header_items()
414
415 Return a list of tuples (header_name, header_value) of the Request headers.
416
417
Georg Brandl8ec7f652007-08-15 14:28:01 +0000418.. method:: Request.set_proxy(host, type)
419
420 Prepare the request by connecting to a proxy server. The *host* and *type* will
421 replace those of the instance, and the instance's selector will be the original
422 URL given in the constructor.
423
424
425.. method:: Request.get_origin_req_host()
426
427 Return the request-host of the origin transaction, as defined by :rfc:`2965`.
428 See the documentation for the :class:`Request` constructor.
429
430
431.. method:: Request.is_unverifiable()
432
433 Return whether the request is unverifiable, as defined by RFC 2965. See the
434 documentation for the :class:`Request` constructor.
435
436
437.. _opener-director-objects:
438
439OpenerDirector Objects
440----------------------
441
442:class:`OpenerDirector` instances have the following methods:
443
444
445.. method:: OpenerDirector.add_handler(handler)
446
Georg Brandld0eb8f92009-01-01 11:53:55 +0000447 *handler* should be an instance of :class:`BaseHandler`. The following
448 methods are searched, and added to the possible chains (note that HTTP errors
449 are a special case).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000450
Georg Brandld0eb8f92009-01-01 11:53:55 +0000451 * :samp:`{protocol}_open` --- signal that the handler knows how to open
452 *protocol* URLs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000453
Georg Brandld0eb8f92009-01-01 11:53:55 +0000454 * :samp:`http_error_{type}` --- signal that the handler knows how to handle
455 HTTP errors with HTTP error code *type*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456
Georg Brandld0eb8f92009-01-01 11:53:55 +0000457 * :samp:`{protocol}_error` --- signal that the handler knows how to handle
458 errors from (non-\ ``http``) *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000459
Georg Brandld0eb8f92009-01-01 11:53:55 +0000460 * :samp:`{protocol}_request` --- signal that the handler knows how to
461 pre-process *protocol* requests.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000462
Georg Brandld0eb8f92009-01-01 11:53:55 +0000463 * :samp:`{protocol}_response` --- signal that the handler knows how to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000464 post-process *protocol* responses.
465
466
467.. method:: OpenerDirector.open(url[, data][, timeout])
468
469 Open the given *url* (which can be a request object or a string), optionally
Georg Brandlab756f62008-05-11 11:09:35 +0000470 passing the given *data*. Arguments, return values and exceptions raised are
471 the same as those of :func:`urlopen` (which simply calls the :meth:`open`
472 method on the currently installed global :class:`OpenerDirector`). The
473 optional *timeout* parameter specifies a timeout in seconds for blocking
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000474 operations like the connection attempt (if not specified, the global default
Georg Brandlda69add2010-05-21 20:52:46 +0000475 timeout setting will be used). The timeout feature actually works only for
Senthil Kumaran30630b92010-10-05 18:45:00 +0000476 HTTP, HTTPS and FTP connections).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000477
478 .. versionchanged:: 2.6
479 *timeout* was added.
480
481
482.. method:: OpenerDirector.error(proto[, arg[, ...]])
483
484 Handle an error of the given protocol. This will call the registered error
485 handlers for the given protocol with the given arguments (which are protocol
486 specific). The HTTP protocol is a special case which uses the HTTP response
487 code to determine the specific error handler; refer to the :meth:`http_error_\*`
488 methods of the handler classes.
489
490 Return values and exceptions raised are the same as those of :func:`urlopen`.
491
492OpenerDirector objects open URLs in three stages:
493
494The order in which these methods are called within each stage is determined by
495sorting the handler instances.
496
Georg Brandld0eb8f92009-01-01 11:53:55 +0000497#. Every handler with a method named like :samp:`{protocol}_request` has that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498 method called to pre-process the request.
499
Georg Brandld0eb8f92009-01-01 11:53:55 +0000500#. Handlers with a method named like :samp:`{protocol}_open` are called to handle
Georg Brandl8ec7f652007-08-15 14:28:01 +0000501 the request. This stage ends when a handler either returns a non-\ :const:`None`
502 value (ie. a response), or raises an exception (usually :exc:`URLError`).
503 Exceptions are allowed to propagate.
504
505 In fact, the above algorithm is first tried for methods named
Georg Brandld0eb8f92009-01-01 11:53:55 +0000506 :meth:`default_open`. If all such methods return :const:`None`, the
507 algorithm is repeated for methods named like :samp:`{protocol}_open`. If all
508 such methods return :const:`None`, the algorithm is repeated for methods
509 named :meth:`unknown_open`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000510
511 Note that the implementation of these methods may involve calls of the parent
Georg Brandl821fc082010-08-01 21:26:45 +0000512 :class:`OpenerDirector` instance's :meth:`~OpenerDirector.open` and
513 :meth:`~OpenerDirector.error` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000514
Georg Brandld0eb8f92009-01-01 11:53:55 +0000515#. Every handler with a method named like :samp:`{protocol}_response` has that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000516 method called to post-process the response.
517
518
519.. _base-handler-objects:
520
521BaseHandler Objects
522-------------------
523
524:class:`BaseHandler` objects provide a couple of methods that are directly
525useful, and others that are meant to be used by derived classes. These are
526intended for direct use:
527
528
529.. method:: BaseHandler.add_parent(director)
530
531 Add a director as parent.
532
533
534.. method:: BaseHandler.close()
535
536 Remove any parents.
537
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700538The following attributes and methods should only be used by classes derived from
Georg Brandl8ec7f652007-08-15 14:28:01 +0000539:class:`BaseHandler`.
540
541.. note::
542
543 The convention has been adopted that subclasses defining
544 :meth:`protocol_request` or :meth:`protocol_response` methods are named
545 :class:`\*Processor`; all others are named :class:`\*Handler`.
546
547
548.. attribute:: BaseHandler.parent
549
550 A valid :class:`OpenerDirector`, which can be used to open using a different
551 protocol, or handle errors.
552
553
554.. method:: BaseHandler.default_open(req)
555
556 This method is *not* defined in :class:`BaseHandler`, but subclasses should
557 define it if they want to catch all URLs.
558
559 This method, if implemented, will be called by the parent
560 :class:`OpenerDirector`. It should return a file-like object as described in
561 the return value of the :meth:`open` of :class:`OpenerDirector`, or ``None``.
562 It should raise :exc:`URLError`, unless a truly exceptional thing happens (for
563 example, :exc:`MemoryError` should not be mapped to :exc:`URLError`).
564
565 This method will be called before any protocol-specific open method.
566
567
568.. method:: BaseHandler.protocol_open(req)
569 :noindex:
570
Georg Brandld0eb8f92009-01-01 11:53:55 +0000571 ("protocol" is to be replaced by the protocol name.)
572
Georg Brandl8ec7f652007-08-15 14:28:01 +0000573 This method is *not* defined in :class:`BaseHandler`, but subclasses should
Georg Brandld0eb8f92009-01-01 11:53:55 +0000574 define it if they want to handle URLs with the given *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575
576 This method, if defined, will be called by the parent :class:`OpenerDirector`.
577 Return values should be the same as for :meth:`default_open`.
578
579
580.. method:: BaseHandler.unknown_open(req)
581
582 This method is *not* defined in :class:`BaseHandler`, but subclasses should
583 define it if they want to catch all URLs with no specific registered handler to
584 open it.
585
586 This method, if implemented, will be called by the :attr:`parent`
587 :class:`OpenerDirector`. Return values should be the same as for
588 :meth:`default_open`.
589
590
591.. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs)
592
593 This method is *not* defined in :class:`BaseHandler`, but subclasses should
594 override it if they intend to provide a catch-all for otherwise unhandled HTTP
595 errors. It will be called automatically by the :class:`OpenerDirector` getting
596 the error, and should not normally be called in other circumstances.
597
598 *req* will be a :class:`Request` object, *fp* will be a file-like object with
599 the HTTP error body, *code* will be the three-digit code of the error, *msg*
600 will be the user-visible explanation of the code and *hdrs* will be a mapping
601 object with the headers of the error.
602
603 Return values and exceptions raised should be the same as those of
604 :func:`urlopen`.
605
606
607.. method:: BaseHandler.http_error_nnn(req, fp, code, msg, hdrs)
608
609 *nnn* should be a three-digit HTTP error code. This method is also not defined
610 in :class:`BaseHandler`, but will be called, if it exists, on an instance of a
611 subclass, when an HTTP error with code *nnn* occurs.
612
613 Subclasses should override this method to handle specific HTTP errors.
614
615 Arguments, return values and exceptions raised should be the same as for
616 :meth:`http_error_default`.
617
618
619.. method:: BaseHandler.protocol_request(req)
620 :noindex:
621
Georg Brandld0eb8f92009-01-01 11:53:55 +0000622 ("protocol" is to be replaced by the protocol name.)
623
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624 This method is *not* defined in :class:`BaseHandler`, but subclasses should
Georg Brandld0eb8f92009-01-01 11:53:55 +0000625 define it if they want to pre-process requests of the given *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000626
627 This method, if defined, will be called by the parent :class:`OpenerDirector`.
628 *req* will be a :class:`Request` object. The return value should be a
629 :class:`Request` object.
630
631
632.. method:: BaseHandler.protocol_response(req, response)
633 :noindex:
634
Georg Brandld0eb8f92009-01-01 11:53:55 +0000635 ("protocol" is to be replaced by the protocol name.)
636
Georg Brandl8ec7f652007-08-15 14:28:01 +0000637 This method is *not* defined in :class:`BaseHandler`, but subclasses should
Georg Brandld0eb8f92009-01-01 11:53:55 +0000638 define it if they want to post-process responses of the given *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000639
640 This method, if defined, will be called by the parent :class:`OpenerDirector`.
641 *req* will be a :class:`Request` object. *response* will be an object
642 implementing the same interface as the return value of :func:`urlopen`. The
643 return value should implement the same interface as the return value of
644 :func:`urlopen`.
645
646
647.. _http-redirect-handler:
648
649HTTPRedirectHandler Objects
650---------------------------
651
652.. note::
653
654 Some HTTP redirections require action from this module's client code. If this
655 is the case, :exc:`HTTPError` is raised. See :rfc:`2616` for details of the
656 precise meanings of the various redirection codes.
657
658
Georg Brandl8fba5b32009-02-13 10:40:14 +0000659.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000660
661 Return a :class:`Request` or ``None`` in response to a redirect. This is called
662 by the default implementations of the :meth:`http_error_30\*` methods when a
663 redirection is received from the server. If a redirection should take place,
664 return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the
Georg Brandl8fba5b32009-02-13 10:40:14 +0000665 redirect to *newurl*. Otherwise, raise :exc:`HTTPError` if no other handler
666 should try to handle this URL, or return ``None`` if you can't but another
667 handler might.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000668
669 .. note::
670
671 The default implementation of this method does not strictly follow :rfc:`2616`,
672 which says that 301 and 302 responses to ``POST`` requests must not be
673 automatically redirected without confirmation by the user. In reality, browsers
674 do allow automatic redirection of these responses, changing the POST to a
675 ``GET``, and the default implementation reproduces this behavior.
676
677
678.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)
679
Georg Brandl8fba5b32009-02-13 10:40:14 +0000680 Redirect to the ``Location:`` or ``URI:`` URL. This method is called by the
681 parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000682
683
684.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)
685
686 The same as :meth:`http_error_301`, but called for the 'found' response.
687
688
689.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)
690
691 The same as :meth:`http_error_301`, but called for the 'see other' response.
692
693
694.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)
695
696 The same as :meth:`http_error_301`, but called for the 'temporary redirect'
697 response.
698
699
700.. _http-cookie-processor:
701
702HTTPCookieProcessor Objects
703---------------------------
704
705.. versionadded:: 2.4
706
707:class:`HTTPCookieProcessor` instances have one attribute:
708
709
710.. attribute:: HTTPCookieProcessor.cookiejar
711
712 The :class:`cookielib.CookieJar` in which cookies are stored.
713
714
715.. _proxy-handler:
716
717ProxyHandler Objects
718--------------------
719
720
721.. method:: ProxyHandler.protocol_open(request)
722 :noindex:
723
Georg Brandld0eb8f92009-01-01 11:53:55 +0000724 ("protocol" is to be replaced by the protocol name.)
725
726 The :class:`ProxyHandler` will have a method :samp:`{protocol}_open` for every
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727 *protocol* which has a proxy in the *proxies* dictionary given in the
728 constructor. The method will modify requests to go through the proxy, by
729 calling ``request.set_proxy()``, and call the next handler in the chain to
730 actually execute the protocol.
731
732
733.. _http-password-mgr:
734
735HTTPPasswordMgr Objects
736-----------------------
737
738These methods are available on :class:`HTTPPasswordMgr` and
739:class:`HTTPPasswordMgrWithDefaultRealm` objects.
740
741
742.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd)
743
744 *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and
745 *passwd* must be strings. This causes ``(user, passwd)`` to be used as
746 authentication tokens when authentication for *realm* and a super-URI of any of
747 the given URIs is given.
748
749
750.. method:: HTTPPasswordMgr.find_user_password(realm, authuri)
751
752 Get user/password for given realm and URI, if any. This method will return
753 ``(None, None)`` if there is no matching user/password.
754
755 For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be
756 searched if the given *realm* has no matching user/password.
757
758
759.. _abstract-basic-auth-handler:
760
761AbstractBasicAuthHandler Objects
762--------------------------------
763
764
765.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
766
767 Handle an authentication request by getting a user/password pair, and re-trying
768 the request. *authreq* should be the name of the header where the information
769 about the realm is included in the request, *host* specifies the URL and path to
770 authenticate for, *req* should be the (failed) :class:`Request` object, and
771 *headers* should be the error headers.
772
773 *host* is either an authority (e.g. ``"python.org"``) or a URL containing an
774 authority component (e.g. ``"http://python.org/"``). In either case, the
775 authority must not contain a userinfo component (so, ``"python.org"`` and
776 ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not).
777
778
779.. _http-basic-auth-handler:
780
781HTTPBasicAuthHandler Objects
782----------------------------
783
784
785.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)
786
787 Retry the request with authentication information, if available.
788
789
790.. _proxy-basic-auth-handler:
791
792ProxyBasicAuthHandler Objects
793-----------------------------
794
795
796.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)
797
798 Retry the request with authentication information, if available.
799
800
801.. _abstract-digest-auth-handler:
802
803AbstractDigestAuthHandler Objects
804---------------------------------
805
806
807.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
808
809 *authreq* should be the name of the header where the information about the realm
810 is included in the request, *host* should be the host to authenticate to, *req*
811 should be the (failed) :class:`Request` object, and *headers* should be the
812 error headers.
813
814
815.. _http-digest-auth-handler:
816
817HTTPDigestAuthHandler Objects
818-----------------------------
819
820
821.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)
822
823 Retry the request with authentication information, if available.
824
825
826.. _proxy-digest-auth-handler:
827
828ProxyDigestAuthHandler Objects
829------------------------------
830
831
832.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)
833
834 Retry the request with authentication information, if available.
835
836
837.. _http-handler-objects:
838
839HTTPHandler Objects
840-------------------
841
842
843.. method:: HTTPHandler.http_open(req)
844
845 Send an HTTP request, which can be either GET or POST, depending on
846 ``req.has_data()``.
847
848
849.. _https-handler-objects:
850
851HTTPSHandler Objects
852--------------------
853
854
855.. method:: HTTPSHandler.https_open(req)
856
857 Send an HTTPS request, which can be either GET or POST, depending on
858 ``req.has_data()``.
859
860
861.. _file-handler-objects:
862
863FileHandler Objects
864-------------------
865
866
867.. method:: FileHandler.file_open(req)
868
869 Open the file locally, if there is no host name, or the host name is
870 ``'localhost'``. Change the protocol to ``ftp`` otherwise, and retry opening it
871 using :attr:`parent`.
872
873
874.. _ftp-handler-objects:
875
876FTPHandler Objects
877------------------
878
879
880.. method:: FTPHandler.ftp_open(req)
881
882 Open the FTP file indicated by *req*. The login is always done with empty
883 username and password.
884
885
886.. _cacheftp-handler-objects:
887
888CacheFTPHandler Objects
889-----------------------
890
891:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the
892following additional methods:
893
894
895.. method:: CacheFTPHandler.setTimeout(t)
896
897 Set timeout of connections to *t* seconds.
898
899
900.. method:: CacheFTPHandler.setMaxConns(m)
901
902 Set maximum number of cached connections to *m*.
903
904
905.. _unknown-handler-objects:
906
907UnknownHandler Objects
908----------------------
909
910
911.. method:: UnknownHandler.unknown_open()
912
913 Raise a :exc:`URLError` exception.
914
915
916.. _http-error-processor-objects:
917
918HTTPErrorProcessor Objects
919--------------------------
920
921.. versionadded:: 2.4
922
923
Senthil Kumarana2dd57a2011-07-18 07:16:02 +0800924.. method:: HTTPErrorProcessor.http_response()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000925
926 Process HTTP error responses.
927
928 For 200 error codes, the response object is returned immediately.
929
930 For non-200 error codes, this simply passes the job on to the
Georg Brandld0eb8f92009-01-01 11:53:55 +0000931 :samp:`{protocol}_error_code` handler methods, via
932 :meth:`OpenerDirector.error`. Eventually,
933 :class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no
934 other handler handles the error.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000935
Senthil Kumarana2dd57a2011-07-18 07:16:02 +0800936.. method:: HTTPErrorProcessor.https_response()
937
Senthil Kumaran1c0ebc02011-07-18 07:18:40 +0800938 Process HTTPS error responses.
939
Senthil Kumarana2dd57a2011-07-18 07:16:02 +0800940 The behavior is same as :meth:`http_response`.
941
Georg Brandl8ec7f652007-08-15 14:28:01 +0000942
943.. _urllib2-examples:
944
945Examples
946--------
947
948This example gets the python.org main page and displays the first 100 bytes of
949it::
950
951 >>> import urllib2
952 >>> f = urllib2.urlopen('http://www.python.org/')
953 >>> print f.read(100)
954 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
955 <?xml-stylesheet href="./css/ht2html
956
957Here we are sending a data-stream to the stdin of a CGI and reading the data it
958returns to us. Note that this example will only work when the Python
959installation supports SSL. ::
960
961 >>> import urllib2
962 >>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',
963 ... data='This data is passed to stdin of the CGI')
964 >>> f = urllib2.urlopen(req)
965 >>> print f.read()
966 Got Data: "This data is passed to stdin of the CGI"
967
968The code for the sample CGI used in the above example is::
969
970 #!/usr/bin/env python
971 import sys
972 data = sys.stdin.read()
973 print 'Content-type: text-plain\n\nGot Data: "%s"' % data
974
975Use of Basic HTTP Authentication::
976
977 import urllib2
978 # Create an OpenerDirector with support for Basic HTTP Authentication...
979 auth_handler = urllib2.HTTPBasicAuthHandler()
980 auth_handler.add_password(realm='PDQ Application',
981 uri='https://mahler:8092/site-updates.py',
982 user='klem',
983 passwd='kadidd!ehopper')
984 opener = urllib2.build_opener(auth_handler)
985 # ...and install it globally so it can be used with urlopen.
986 urllib2.install_opener(opener)
987 urllib2.urlopen('http://www.example.com/login.html')
988
989:func:`build_opener` provides many handlers by default, including a
990:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment
991variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme
992involved. For example, the :envvar:`http_proxy` environment variable is read to
993obtain the HTTP proxy's URL.
994
995This example replaces the default :class:`ProxyHandler` with one that uses
Benjamin Peterson90f36732008-07-12 20:16:19 +0000996programmatically-supplied proxy URLs, and adds proxy authorization support with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000997:class:`ProxyBasicAuthHandler`. ::
998
999 proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
Senthil Kumaranf9a21f42009-12-24 02:18:14 +00001000 proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001001 proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
1002
Senthil Kumaranf9a21f42009-12-24 02:18:14 +00001003 opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001004 # This time, rather than install the OpenerDirector, we use it directly:
1005 opener.open('http://www.example.com/login.html')
1006
1007Adding HTTP headers:
1008
1009Use the *headers* argument to the :class:`Request` constructor, or::
1010
1011 import urllib2
1012 req = urllib2.Request('http://www.example.com/')
1013 req.add_header('Referer', 'http://www.python.org/')
1014 r = urllib2.urlopen(req)
1015
1016:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
1017every :class:`Request`. To change this::
1018
1019 import urllib2
1020 opener = urllib2.build_opener()
1021 opener.addheaders = [('User-agent', 'Mozilla/5.0')]
1022 opener.open('http://www.example.com/')
1023
1024Also, remember that a few standard headers (:mailheader:`Content-Length`,
1025:mailheader:`Content-Type` and :mailheader:`Host`) are added when the
1026:class:`Request` is passed to :func:`urlopen` (or :meth:`OpenerDirector.open`).
1027