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