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