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