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