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