blob: bae5a4b2f5b893d19e16bc24c0a5b990e7501de3 [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
25.. function:: urlopen(url[, data][, timeout])
26
27 Open the URL *url*, which can be either a string or a :class:`Request` object.
28
Senthil Kumaran30630b92010-10-05 18:45:00 +000029 .. warning::
30 HTTPS requests do not do any verification of the server's certificate.
31
Georg Brandl8ec7f652007-08-15 14:28:01 +000032 *data* may be a string specifying additional data to send to the server, or
33 ``None`` if no such data is needed. Currently HTTP requests are the only ones
34 that use *data*; the HTTP request will be a POST instead of a GET when the
35 *data* parameter is provided. *data* should be a buffer in the standard
36 :mimetype:`application/x-www-form-urlencoded` format. The
37 :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
Senthil Kumaranb7575ee2010-08-21 16:14:54 +000038 returns a string in this format. urllib2 module sends HTTP/1.1 requests with
Éric Araujoa7cbe282011-09-01 19:49:31 +020039 ``Connection:close`` header included.
Georg Brandl8ec7f652007-08-15 14:28:01 +000040
Georg Brandlab756f62008-05-11 11:09:35 +000041 The optional *timeout* parameter specifies a timeout in seconds for blocking
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000042 operations like the connection attempt (if not specified, the global default
Senthil Kumaran30630b92010-10-05 18:45:00 +000043 timeout setting will be used). This actually only works for HTTP, HTTPS and
44 FTP connections.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
46 This function returns a file-like object with two additional methods:
47
Georg Brandl586a57a2008-02-02 09:56:20 +000048 * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to
49 determine if a redirect was followed
Georg Brandl8ec7f652007-08-15 14:28:01 +000050
Senthil Kumaran8c996ef2010-06-28 17:07:40 +000051 * :meth:`info` --- return the meta-information of the page, such as headers,
52 in the form of an :class:`mimetools.Message` instance
Georg Brandl586a57a2008-02-02 09:56:20 +000053 (see `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
Georg Brandl8ec7f652007-08-15 14:28:01 +000054
Senthil Kumaran785d1b12013-02-07 00:51:34 -080055 * :meth:`getcode` --- return the HTTP status code of the response.
56
Georg Brandl8ec7f652007-08-15 14:28:01 +000057 Raises :exc:`URLError` on errors.
58
59 Note that ``None`` may be returned if no handler handles the request (though the
60 default installed global :class:`OpenerDirector` uses :class:`UnknownHandler` to
61 ensure this never happens).
62
Senthil Kumaran45a505f2009-10-18 01:24:41 +000063 In addition, default installed :class:`ProxyHandler` makes sure the requests
64 are handled through the proxy when they are set.
65
Georg Brandl8ec7f652007-08-15 14:28:01 +000066 .. versionchanged:: 2.6
67 *timeout* was added.
68
69
70.. function:: install_opener(opener)
71
72 Install an :class:`OpenerDirector` instance as the default global opener.
73 Installing an opener is only necessary if you want urlopen to use that opener;
74 otherwise, simply call :meth:`OpenerDirector.open` instead of :func:`urlopen`.
75 The code does not check for a real :class:`OpenerDirector`, and any class with
76 the appropriate interface will work.
77
78
79.. function:: build_opener([handler, ...])
80
81 Return an :class:`OpenerDirector` instance, which chains the handlers in the
82 order given. *handler*\s can be either instances of :class:`BaseHandler`, or
83 subclasses of :class:`BaseHandler` (in which case it must be possible to call
84 the constructor without any parameters). Instances of the following classes
85 will be in front of the *handler*\s, unless the *handler*\s contain them,
86 instances of them or subclasses of them: :class:`ProxyHandler`,
87 :class:`UnknownHandler`, :class:`HTTPHandler`, :class:`HTTPDefaultErrorHandler`,
88 :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
89 :class:`HTTPErrorProcessor`.
90
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000091 If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported),
Georg Brandl8ec7f652007-08-15 14:28:01 +000092 :class:`HTTPSHandler` will also be added.
93
94 Beginning in Python 2.3, a :class:`BaseHandler` subclass may also change its
Senthil Kumaran6f18b982011-07-04 12:50:02 -070095 :attr:`handler_order` attribute to modify its position in the handlers
Georg Brandl8ec7f652007-08-15 14:28:01 +000096 list.
97
98The following exceptions are raised as appropriate:
99
100
101.. exception:: URLError
102
103 The handlers raise this exception (or derived exceptions) when they run into a
104 problem. It is a subclass of :exc:`IOError`.
105
Georg Brandl586a57a2008-02-02 09:56:20 +0000106 .. attribute:: reason
107
108 The reason for this error. It can be a message string or another exception
109 instance (:exc:`socket.error` for remote URLs, :exc:`OSError` for local
110 URLs).
111
Georg Brandl8ec7f652007-08-15 14:28:01 +0000112
113.. exception:: HTTPError
114
Georg Brandl586a57a2008-02-02 09:56:20 +0000115 Though being an exception (a subclass of :exc:`URLError`), an :exc:`HTTPError`
116 can also function as a non-exceptional file-like return value (the same thing
117 that :func:`urlopen` returns). This is useful when handling exotic HTTP
118 errors, such as requests for authentication.
119
120 .. attribute:: code
121
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000122 An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_.
Georg Brandl586a57a2008-02-02 09:56:20 +0000123 This numeric value corresponds to a value found in the dictionary of
124 codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`.
125
Senthil Kumaranbfb09892012-12-09 13:36:40 -0800126 .. attribute:: reason
Georg Brandl586a57a2008-02-02 09:56:20 +0000127
Senthil Kumaranbfb09892012-12-09 13:36:40 -0800128 The reason for this error. It can be a message string or another exception
129 instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130
131The following classes are provided:
132
133
Georg Brandl586a57a2008-02-02 09:56:20 +0000134.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135
136 This class is an abstraction of a URL request.
137
138 *url* should be a string containing a valid URL.
139
140 *data* may be a string specifying additional data to send to the server, or
141 ``None`` if no such data is needed. Currently HTTP requests are the only ones
142 that use *data*; the HTTP request will be a POST instead of a GET when the
143 *data* parameter is provided. *data* should be a buffer in the standard
144 :mimetype:`application/x-www-form-urlencoded` format. The
145 :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
146 returns a string in this format.
147
148 *headers* should be a dictionary, and will be treated as if :meth:`add_header`
Georg Brandl586a57a2008-02-02 09:56:20 +0000149 was called with each key and value as arguments. This is often used to "spoof"
150 the ``User-Agent`` header, which is used by a browser to identify itself --
151 some HTTP servers only allow requests coming from common browsers as opposed
152 to scripts. For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0
153 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib2`'s
154 default user agent string is ``"Python-urllib/2.6"`` (on Python 2.6).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155
156 The final two arguments are only of interest for correct handling of third-party
157 HTTP cookies:
158
159 *origin_req_host* should be the request-host of the origin transaction, as
160 defined by :rfc:`2965`. It defaults to ``cookielib.request_host(self)``. This
161 is the host name or IP address of the original request that was initiated by the
162 user. For example, if the request is for an image in an HTML document, this
163 should be the request-host of the request for the page containing the image.
164
165 *unverifiable* should indicate whether the request is unverifiable, as defined
166 by RFC 2965. It defaults to False. An unverifiable request is one whose URL
167 the user did not have the option to approve. For example, if the request is for
168 an image in an HTML document, and the user had no option to approve the
169 automatic fetching of the image, this should be true.
170
171
172.. class:: OpenerDirector()
173
174 The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained
175 together. It manages the chaining of handlers, and recovery from errors.
176
177
178.. class:: BaseHandler()
179
180 This is the base class for all registered handlers --- and handles only the
181 simple mechanics of registration.
182
183
184.. class:: HTTPDefaultErrorHandler()
185
186 A class which defines a default handler for HTTP error responses; all responses
187 are turned into :exc:`HTTPError` exceptions.
188
189
190.. class:: HTTPRedirectHandler()
191
192 A class to handle redirections.
193
194
195.. class:: HTTPCookieProcessor([cookiejar])
196
197 A class to handle HTTP Cookies.
198
199
200.. class:: ProxyHandler([proxies])
201
202 Cause requests to go through a proxy. If *proxies* is given, it must be a
Senthil Kumaran45a505f2009-10-18 01:24:41 +0000203 dictionary mapping protocol names to URLs of proxies. The default is to read
204 the list of proxies from the environment variables
205 :envvar:`<protocol>_proxy`. If no proxy environment variables are set, in a
206 Windows environment, proxy settings are obtained from the registry's
207 Internet Settings section and in a Mac OS X environment, proxy information
Senthil Kumaran83f1ef62009-10-18 01:58:45 +0000208 is retrieved from the OS X System Configuration Framework.
Senthil Kumaran45a505f2009-10-18 01:24:41 +0000209
Sean Reifscheider45ea86c2008-03-20 03:20:48 +0000210 To disable autodetected proxy pass an empty dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
212
213.. class:: HTTPPasswordMgr()
214
215 Keep a database of ``(realm, uri) -> (user, password)`` mappings.
216
217
218.. class:: HTTPPasswordMgrWithDefaultRealm()
219
220 Keep a database of ``(realm, uri) -> (user, password)`` mappings. A realm of
221 ``None`` is considered a catch-all realm, which is searched if no other realm
222 fits.
223
224
225.. class:: AbstractBasicAuthHandler([password_mgr])
226
227 This is a mixin class that helps with HTTP authentication, both to the remote
228 host and to a proxy. *password_mgr*, if given, should be something that is
229 compatible with :class:`HTTPPasswordMgr`; refer to section
230 :ref:`http-password-mgr` for information on the interface that must be
231 supported.
232
233
234.. class:: HTTPBasicAuthHandler([password_mgr])
235
236 Handle authentication with the remote host. *password_mgr*, if given, should be
237 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
238 :ref:`http-password-mgr` for information on the interface that must be
239 supported.
240
241
242.. class:: ProxyBasicAuthHandler([password_mgr])
243
244 Handle authentication with the proxy. *password_mgr*, if given, should be
245 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
246 :ref:`http-password-mgr` for information on the interface that must be
247 supported.
248
249
250.. class:: AbstractDigestAuthHandler([password_mgr])
251
252 This is a mixin class that helps with HTTP authentication, both to the remote
253 host and to a proxy. *password_mgr*, if given, should be something that is
254 compatible with :class:`HTTPPasswordMgr`; refer to section
255 :ref:`http-password-mgr` for information on the interface that must be
256 supported.
257
258
259.. class:: HTTPDigestAuthHandler([password_mgr])
260
261 Handle authentication with the remote host. *password_mgr*, if given, should be
262 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
263 :ref:`http-password-mgr` for information on the interface that must be
264 supported.
265
266
267.. class:: ProxyDigestAuthHandler([password_mgr])
268
269 Handle authentication with the proxy. *password_mgr*, if given, should be
270 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
271 :ref:`http-password-mgr` for information on the interface that must be
272 supported.
273
274
275.. class:: HTTPHandler()
276
277 A class to handle opening of HTTP URLs.
278
279
280.. class:: HTTPSHandler()
281
282 A class to handle opening of HTTPS URLs.
283
284
285.. class:: FileHandler()
286
287 Open local files.
288
289
290.. class:: FTPHandler()
291
292 Open FTP URLs.
293
294
295.. class:: CacheFTPHandler()
296
297 Open FTP URLs, keeping a cache of open FTP connections to minimize delays.
298
299
300.. class:: UnknownHandler()
301
302 A catch-all class to handle unknown URLs.
303
304
Senthil Kumaran612b2b32011-07-18 06:44:11 +0800305.. class:: HTTPErrorProcessor()
306
307 Process HTTP error responses.
308
309
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310.. _request-objects:
311
312Request Objects
313---------------
314
315The following methods describe all of :class:`Request`'s public interface, and
316so all must be overridden in subclasses.
317
318
319.. method:: Request.add_data(data)
320
321 Set the :class:`Request` data to *data*. This is ignored by all handlers except
322 HTTP handlers --- and there it should be a byte string, and will change the
323 request to be ``POST`` rather than ``GET``.
324
325
326.. method:: Request.get_method()
327
328 Return a string indicating the HTTP request method. This is only meaningful for
329 HTTP requests, and currently always returns ``'GET'`` or ``'POST'``.
330
331
332.. method:: Request.has_data()
333
334 Return whether the instance has a non-\ ``None`` data.
335
336
337.. method:: Request.get_data()
338
339 Return the instance's data.
340
341
342.. method:: Request.add_header(key, val)
343
344 Add another header to the request. Headers are currently ignored by all
345 handlers except HTTP handlers, where they are added to the list of headers sent
346 to the server. Note that there cannot be more than one header with the same
347 name, and later calls will overwrite previous calls in case the *key* collides.
348 Currently, this is no loss of HTTP functionality, since all headers which have
349 meaning when used more than once have a (header-specific) way of gaining the
350 same functionality using only one header.
351
352
353.. method:: Request.add_unredirected_header(key, header)
354
355 Add a header that will not be added to a redirected request.
356
357 .. versionadded:: 2.4
358
359
360.. method:: Request.has_header(header)
361
362 Return whether the instance has the named header (checks both regular and
363 unredirected).
364
365 .. versionadded:: 2.4
366
367
368.. method:: Request.get_full_url()
369
370 Return the URL given in the constructor.
371
372
373.. method:: Request.get_type()
374
375 Return the type of the URL --- also known as the scheme.
376
377
378.. method:: Request.get_host()
379
380 Return the host to which a connection will be made.
381
382
383.. method:: Request.get_selector()
384
385 Return the selector --- the part of the URL that is sent to the server.
386
387
Senthil Kumaran429d3112012-04-29 11:52:59 +0800388.. method:: Request.get_header(header_name, default=None)
389
390 Return the value of the given header. If the header is not present, return
391 the default value.
392
393
394.. method:: Request.header_items()
395
396 Return a list of tuples (header_name, header_value) of the Request headers.
397
398
Georg Brandl8ec7f652007-08-15 14:28:01 +0000399.. method:: Request.set_proxy(host, type)
400
401 Prepare the request by connecting to a proxy server. The *host* and *type* will
402 replace those of the instance, and the instance's selector will be the original
403 URL given in the constructor.
404
405
406.. method:: Request.get_origin_req_host()
407
408 Return the request-host of the origin transaction, as defined by :rfc:`2965`.
409 See the documentation for the :class:`Request` constructor.
410
411
412.. method:: Request.is_unverifiable()
413
414 Return whether the request is unverifiable, as defined by RFC 2965. See the
415 documentation for the :class:`Request` constructor.
416
417
418.. _opener-director-objects:
419
420OpenerDirector Objects
421----------------------
422
423:class:`OpenerDirector` instances have the following methods:
424
425
426.. method:: OpenerDirector.add_handler(handler)
427
Georg Brandld0eb8f92009-01-01 11:53:55 +0000428 *handler* should be an instance of :class:`BaseHandler`. The following
429 methods are searched, and added to the possible chains (note that HTTP errors
430 are a special case).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000431
Georg Brandld0eb8f92009-01-01 11:53:55 +0000432 * :samp:`{protocol}_open` --- signal that the handler knows how to open
433 *protocol* URLs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000434
Georg Brandld0eb8f92009-01-01 11:53:55 +0000435 * :samp:`http_error_{type}` --- signal that the handler knows how to handle
436 HTTP errors with HTTP error code *type*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000437
Georg Brandld0eb8f92009-01-01 11:53:55 +0000438 * :samp:`{protocol}_error` --- signal that the handler knows how to handle
439 errors from (non-\ ``http``) *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440
Georg Brandld0eb8f92009-01-01 11:53:55 +0000441 * :samp:`{protocol}_request` --- signal that the handler knows how to
442 pre-process *protocol* requests.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000443
Georg Brandld0eb8f92009-01-01 11:53:55 +0000444 * :samp:`{protocol}_response` --- signal that the handler knows how to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000445 post-process *protocol* responses.
446
447
448.. method:: OpenerDirector.open(url[, data][, timeout])
449
450 Open the given *url* (which can be a request object or a string), optionally
Georg Brandlab756f62008-05-11 11:09:35 +0000451 passing the given *data*. Arguments, return values and exceptions raised are
452 the same as those of :func:`urlopen` (which simply calls the :meth:`open`
453 method on the currently installed global :class:`OpenerDirector`). The
454 optional *timeout* parameter specifies a timeout in seconds for blocking
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000455 operations like the connection attempt (if not specified, the global default
Georg Brandlda69add2010-05-21 20:52:46 +0000456 timeout setting will be used). The timeout feature actually works only for
Senthil Kumaran30630b92010-10-05 18:45:00 +0000457 HTTP, HTTPS and FTP connections).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000458
459 .. versionchanged:: 2.6
460 *timeout* was added.
461
462
463.. method:: OpenerDirector.error(proto[, arg[, ...]])
464
465 Handle an error of the given protocol. This will call the registered error
466 handlers for the given protocol with the given arguments (which are protocol
467 specific). The HTTP protocol is a special case which uses the HTTP response
468 code to determine the specific error handler; refer to the :meth:`http_error_\*`
469 methods of the handler classes.
470
471 Return values and exceptions raised are the same as those of :func:`urlopen`.
472
473OpenerDirector objects open URLs in three stages:
474
475The order in which these methods are called within each stage is determined by
476sorting the handler instances.
477
Georg Brandld0eb8f92009-01-01 11:53:55 +0000478#. Every handler with a method named like :samp:`{protocol}_request` has that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000479 method called to pre-process the request.
480
Georg Brandld0eb8f92009-01-01 11:53:55 +0000481#. Handlers with a method named like :samp:`{protocol}_open` are called to handle
Georg Brandl8ec7f652007-08-15 14:28:01 +0000482 the request. This stage ends when a handler either returns a non-\ :const:`None`
483 value (ie. a response), or raises an exception (usually :exc:`URLError`).
484 Exceptions are allowed to propagate.
485
486 In fact, the above algorithm is first tried for methods named
Georg Brandld0eb8f92009-01-01 11:53:55 +0000487 :meth:`default_open`. If all such methods return :const:`None`, the
488 algorithm is repeated for methods named like :samp:`{protocol}_open`. If all
489 such methods return :const:`None`, the algorithm is repeated for methods
490 named :meth:`unknown_open`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000491
492 Note that the implementation of these methods may involve calls of the parent
Georg Brandl821fc082010-08-01 21:26:45 +0000493 :class:`OpenerDirector` instance's :meth:`~OpenerDirector.open` and
494 :meth:`~OpenerDirector.error` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000495
Georg Brandld0eb8f92009-01-01 11:53:55 +0000496#. Every handler with a method named like :samp:`{protocol}_response` has that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497 method called to post-process the response.
498
499
500.. _base-handler-objects:
501
502BaseHandler Objects
503-------------------
504
505:class:`BaseHandler` objects provide a couple of methods that are directly
506useful, and others that are meant to be used by derived classes. These are
507intended for direct use:
508
509
510.. method:: BaseHandler.add_parent(director)
511
512 Add a director as parent.
513
514
515.. method:: BaseHandler.close()
516
517 Remove any parents.
518
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700519The following attributes and methods should only be used by classes derived from
Georg Brandl8ec7f652007-08-15 14:28:01 +0000520:class:`BaseHandler`.
521
522.. note::
523
524 The convention has been adopted that subclasses defining
525 :meth:`protocol_request` or :meth:`protocol_response` methods are named
526 :class:`\*Processor`; all others are named :class:`\*Handler`.
527
528
529.. attribute:: BaseHandler.parent
530
531 A valid :class:`OpenerDirector`, which can be used to open using a different
532 protocol, or handle errors.
533
534
535.. method:: BaseHandler.default_open(req)
536
537 This method is *not* defined in :class:`BaseHandler`, but subclasses should
538 define it if they want to catch all URLs.
539
540 This method, if implemented, will be called by the parent
541 :class:`OpenerDirector`. It should return a file-like object as described in
542 the return value of the :meth:`open` of :class:`OpenerDirector`, or ``None``.
543 It should raise :exc:`URLError`, unless a truly exceptional thing happens (for
544 example, :exc:`MemoryError` should not be mapped to :exc:`URLError`).
545
546 This method will be called before any protocol-specific open method.
547
548
549.. method:: BaseHandler.protocol_open(req)
550 :noindex:
551
Georg Brandld0eb8f92009-01-01 11:53:55 +0000552 ("protocol" is to be replaced by the protocol name.)
553
Georg Brandl8ec7f652007-08-15 14:28:01 +0000554 This method is *not* defined in :class:`BaseHandler`, but subclasses should
Georg Brandld0eb8f92009-01-01 11:53:55 +0000555 define it if they want to handle URLs with the given *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000556
557 This method, if defined, will be called by the parent :class:`OpenerDirector`.
558 Return values should be the same as for :meth:`default_open`.
559
560
561.. method:: BaseHandler.unknown_open(req)
562
563 This method is *not* defined in :class:`BaseHandler`, but subclasses should
564 define it if they want to catch all URLs with no specific registered handler to
565 open it.
566
567 This method, if implemented, will be called by the :attr:`parent`
568 :class:`OpenerDirector`. Return values should be the same as for
569 :meth:`default_open`.
570
571
572.. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs)
573
574 This method is *not* defined in :class:`BaseHandler`, but subclasses should
575 override it if they intend to provide a catch-all for otherwise unhandled HTTP
576 errors. It will be called automatically by the :class:`OpenerDirector` getting
577 the error, and should not normally be called in other circumstances.
578
579 *req* will be a :class:`Request` object, *fp* will be a file-like object with
580 the HTTP error body, *code* will be the three-digit code of the error, *msg*
581 will be the user-visible explanation of the code and *hdrs* will be a mapping
582 object with the headers of the error.
583
584 Return values and exceptions raised should be the same as those of
585 :func:`urlopen`.
586
587
588.. method:: BaseHandler.http_error_nnn(req, fp, code, msg, hdrs)
589
590 *nnn* should be a three-digit HTTP error code. This method is also not defined
591 in :class:`BaseHandler`, but will be called, if it exists, on an instance of a
592 subclass, when an HTTP error with code *nnn* occurs.
593
594 Subclasses should override this method to handle specific HTTP errors.
595
596 Arguments, return values and exceptions raised should be the same as for
597 :meth:`http_error_default`.
598
599
600.. method:: BaseHandler.protocol_request(req)
601 :noindex:
602
Georg Brandld0eb8f92009-01-01 11:53:55 +0000603 ("protocol" is to be replaced by the protocol name.)
604
Georg Brandl8ec7f652007-08-15 14:28:01 +0000605 This method is *not* defined in :class:`BaseHandler`, but subclasses should
Georg Brandld0eb8f92009-01-01 11:53:55 +0000606 define it if they want to pre-process requests of the given *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000607
608 This method, if defined, will be called by the parent :class:`OpenerDirector`.
609 *req* will be a :class:`Request` object. The return value should be a
610 :class:`Request` object.
611
612
613.. method:: BaseHandler.protocol_response(req, response)
614 :noindex:
615
Georg Brandld0eb8f92009-01-01 11:53:55 +0000616 ("protocol" is to be replaced by the protocol name.)
617
Georg Brandl8ec7f652007-08-15 14:28:01 +0000618 This method is *not* defined in :class:`BaseHandler`, but subclasses should
Georg Brandld0eb8f92009-01-01 11:53:55 +0000619 define it if they want to post-process responses of the given *protocol*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000620
621 This method, if defined, will be called by the parent :class:`OpenerDirector`.
622 *req* will be a :class:`Request` object. *response* will be an object
623 implementing the same interface as the return value of :func:`urlopen`. The
624 return value should implement the same interface as the return value of
625 :func:`urlopen`.
626
627
628.. _http-redirect-handler:
629
630HTTPRedirectHandler Objects
631---------------------------
632
633.. note::
634
635 Some HTTP redirections require action from this module's client code. If this
636 is the case, :exc:`HTTPError` is raised. See :rfc:`2616` for details of the
637 precise meanings of the various redirection codes.
638
639
Georg Brandl8fba5b32009-02-13 10:40:14 +0000640.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000641
642 Return a :class:`Request` or ``None`` in response to a redirect. This is called
643 by the default implementations of the :meth:`http_error_30\*` methods when a
644 redirection is received from the server. If a redirection should take place,
645 return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the
Georg Brandl8fba5b32009-02-13 10:40:14 +0000646 redirect to *newurl*. Otherwise, raise :exc:`HTTPError` if no other handler
647 should try to handle this URL, or return ``None`` if you can't but another
648 handler might.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000649
650 .. note::
651
652 The default implementation of this method does not strictly follow :rfc:`2616`,
653 which says that 301 and 302 responses to ``POST`` requests must not be
654 automatically redirected without confirmation by the user. In reality, browsers
655 do allow automatic redirection of these responses, changing the POST to a
656 ``GET``, and the default implementation reproduces this behavior.
657
658
659.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)
660
Georg Brandl8fba5b32009-02-13 10:40:14 +0000661 Redirect to the ``Location:`` or ``URI:`` URL. This method is called by the
662 parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000663
664
665.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)
666
667 The same as :meth:`http_error_301`, but called for the 'found' response.
668
669
670.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)
671
672 The same as :meth:`http_error_301`, but called for the 'see other' response.
673
674
675.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)
676
677 The same as :meth:`http_error_301`, but called for the 'temporary redirect'
678 response.
679
680
681.. _http-cookie-processor:
682
683HTTPCookieProcessor Objects
684---------------------------
685
686.. versionadded:: 2.4
687
688:class:`HTTPCookieProcessor` instances have one attribute:
689
690
691.. attribute:: HTTPCookieProcessor.cookiejar
692
693 The :class:`cookielib.CookieJar` in which cookies are stored.
694
695
696.. _proxy-handler:
697
698ProxyHandler Objects
699--------------------
700
701
702.. method:: ProxyHandler.protocol_open(request)
703 :noindex:
704
Georg Brandld0eb8f92009-01-01 11:53:55 +0000705 ("protocol" is to be replaced by the protocol name.)
706
707 The :class:`ProxyHandler` will have a method :samp:`{protocol}_open` for every
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708 *protocol* which has a proxy in the *proxies* dictionary given in the
709 constructor. The method will modify requests to go through the proxy, by
710 calling ``request.set_proxy()``, and call the next handler in the chain to
711 actually execute the protocol.
712
713
714.. _http-password-mgr:
715
716HTTPPasswordMgr Objects
717-----------------------
718
719These methods are available on :class:`HTTPPasswordMgr` and
720:class:`HTTPPasswordMgrWithDefaultRealm` objects.
721
722
723.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd)
724
725 *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and
726 *passwd* must be strings. This causes ``(user, passwd)`` to be used as
727 authentication tokens when authentication for *realm* and a super-URI of any of
728 the given URIs is given.
729
730
731.. method:: HTTPPasswordMgr.find_user_password(realm, authuri)
732
733 Get user/password for given realm and URI, if any. This method will return
734 ``(None, None)`` if there is no matching user/password.
735
736 For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be
737 searched if the given *realm* has no matching user/password.
738
739
740.. _abstract-basic-auth-handler:
741
742AbstractBasicAuthHandler Objects
743--------------------------------
744
745
746.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
747
748 Handle an authentication request by getting a user/password pair, and re-trying
749 the request. *authreq* should be the name of the header where the information
750 about the realm is included in the request, *host* specifies the URL and path to
751 authenticate for, *req* should be the (failed) :class:`Request` object, and
752 *headers* should be the error headers.
753
754 *host* is either an authority (e.g. ``"python.org"``) or a URL containing an
755 authority component (e.g. ``"http://python.org/"``). In either case, the
756 authority must not contain a userinfo component (so, ``"python.org"`` and
757 ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not).
758
759
760.. _http-basic-auth-handler:
761
762HTTPBasicAuthHandler Objects
763----------------------------
764
765
766.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)
767
768 Retry the request with authentication information, if available.
769
770
771.. _proxy-basic-auth-handler:
772
773ProxyBasicAuthHandler Objects
774-----------------------------
775
776
777.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)
778
779 Retry the request with authentication information, if available.
780
781
782.. _abstract-digest-auth-handler:
783
784AbstractDigestAuthHandler Objects
785---------------------------------
786
787
788.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
789
790 *authreq* should be the name of the header where the information about the realm
791 is included in the request, *host* should be the host to authenticate to, *req*
792 should be the (failed) :class:`Request` object, and *headers* should be the
793 error headers.
794
795
796.. _http-digest-auth-handler:
797
798HTTPDigestAuthHandler Objects
799-----------------------------
800
801
802.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)
803
804 Retry the request with authentication information, if available.
805
806
807.. _proxy-digest-auth-handler:
808
809ProxyDigestAuthHandler Objects
810------------------------------
811
812
813.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)
814
815 Retry the request with authentication information, if available.
816
817
818.. _http-handler-objects:
819
820HTTPHandler Objects
821-------------------
822
823
824.. method:: HTTPHandler.http_open(req)
825
826 Send an HTTP request, which can be either GET or POST, depending on
827 ``req.has_data()``.
828
829
830.. _https-handler-objects:
831
832HTTPSHandler Objects
833--------------------
834
835
836.. method:: HTTPSHandler.https_open(req)
837
838 Send an HTTPS request, which can be either GET or POST, depending on
839 ``req.has_data()``.
840
841
842.. _file-handler-objects:
843
844FileHandler Objects
845-------------------
846
847
848.. method:: FileHandler.file_open(req)
849
850 Open the file locally, if there is no host name, or the host name is
851 ``'localhost'``. Change the protocol to ``ftp`` otherwise, and retry opening it
852 using :attr:`parent`.
853
854
855.. _ftp-handler-objects:
856
857FTPHandler Objects
858------------------
859
860
861.. method:: FTPHandler.ftp_open(req)
862
863 Open the FTP file indicated by *req*. The login is always done with empty
864 username and password.
865
866
867.. _cacheftp-handler-objects:
868
869CacheFTPHandler Objects
870-----------------------
871
872:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the
873following additional methods:
874
875
876.. method:: CacheFTPHandler.setTimeout(t)
877
878 Set timeout of connections to *t* seconds.
879
880
881.. method:: CacheFTPHandler.setMaxConns(m)
882
883 Set maximum number of cached connections to *m*.
884
885
886.. _unknown-handler-objects:
887
888UnknownHandler Objects
889----------------------
890
891
892.. method:: UnknownHandler.unknown_open()
893
894 Raise a :exc:`URLError` exception.
895
896
897.. _http-error-processor-objects:
898
899HTTPErrorProcessor Objects
900--------------------------
901
902.. versionadded:: 2.4
903
904
Senthil Kumarana2dd57a2011-07-18 07:16:02 +0800905.. method:: HTTPErrorProcessor.http_response()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000906
907 Process HTTP error responses.
908
909 For 200 error codes, the response object is returned immediately.
910
911 For non-200 error codes, this simply passes the job on to the
Georg Brandld0eb8f92009-01-01 11:53:55 +0000912 :samp:`{protocol}_error_code` handler methods, via
913 :meth:`OpenerDirector.error`. Eventually,
914 :class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no
915 other handler handles the error.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000916
Senthil Kumarana2dd57a2011-07-18 07:16:02 +0800917.. method:: HTTPErrorProcessor.https_response()
918
Senthil Kumaran1c0ebc02011-07-18 07:18:40 +0800919 Process HTTPS error responses.
920
Senthil Kumarana2dd57a2011-07-18 07:16:02 +0800921 The behavior is same as :meth:`http_response`.
922
Georg Brandl8ec7f652007-08-15 14:28:01 +0000923
924.. _urllib2-examples:
925
926Examples
927--------
928
929This example gets the python.org main page and displays the first 100 bytes of
930it::
931
932 >>> import urllib2
933 >>> f = urllib2.urlopen('http://www.python.org/')
934 >>> print f.read(100)
935 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
936 <?xml-stylesheet href="./css/ht2html
937
938Here we are sending a data-stream to the stdin of a CGI and reading the data it
939returns to us. Note that this example will only work when the Python
940installation supports SSL. ::
941
942 >>> import urllib2
943 >>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',
944 ... data='This data is passed to stdin of the CGI')
945 >>> f = urllib2.urlopen(req)
946 >>> print f.read()
947 Got Data: "This data is passed to stdin of the CGI"
948
949The code for the sample CGI used in the above example is::
950
951 #!/usr/bin/env python
952 import sys
953 data = sys.stdin.read()
954 print 'Content-type: text-plain\n\nGot Data: "%s"' % data
955
956Use of Basic HTTP Authentication::
957
958 import urllib2
959 # Create an OpenerDirector with support for Basic HTTP Authentication...
960 auth_handler = urllib2.HTTPBasicAuthHandler()
961 auth_handler.add_password(realm='PDQ Application',
962 uri='https://mahler:8092/site-updates.py',
963 user='klem',
964 passwd='kadidd!ehopper')
965 opener = urllib2.build_opener(auth_handler)
966 # ...and install it globally so it can be used with urlopen.
967 urllib2.install_opener(opener)
968 urllib2.urlopen('http://www.example.com/login.html')
969
970:func:`build_opener` provides many handlers by default, including a
971:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment
972variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme
973involved. For example, the :envvar:`http_proxy` environment variable is read to
974obtain the HTTP proxy's URL.
975
976This example replaces the default :class:`ProxyHandler` with one that uses
Benjamin Peterson90f36732008-07-12 20:16:19 +0000977programmatically-supplied proxy URLs, and adds proxy authorization support with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000978:class:`ProxyBasicAuthHandler`. ::
979
980 proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
Senthil Kumaranf9a21f42009-12-24 02:18:14 +0000981 proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000982 proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
983
Senthil Kumaranf9a21f42009-12-24 02:18:14 +0000984 opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000985 # This time, rather than install the OpenerDirector, we use it directly:
986 opener.open('http://www.example.com/login.html')
987
988Adding HTTP headers:
989
990Use the *headers* argument to the :class:`Request` constructor, or::
991
992 import urllib2
993 req = urllib2.Request('http://www.example.com/')
994 req.add_header('Referer', 'http://www.python.org/')
995 r = urllib2.urlopen(req)
996
997:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
998every :class:`Request`. To change this::
999
1000 import urllib2
1001 opener = urllib2.build_opener()
1002 opener.addheaders = [('User-agent', 'Mozilla/5.0')]
1003 opener.open('http://www.example.com/')
1004
1005Also, remember that a few standard headers (:mailheader:`Content-Length`,
1006:mailheader:`Content-Type` and :mailheader:`Host`) are added when the
1007:class:`Request` is passed to :func:`urlopen` (or :meth:`OpenerDirector.open`).
1008