blob: bce00b3a25439e35d2271bf6fd320afcfdb3a4cc [file] [log] [blame]
Georg Brandl8175dae2010-11-29 14:53:15 +00001:mod:`urllib.request` --- Extensible library for opening URLs
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00002=============================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00004.. module:: urllib.request
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07005 :synopsis: Extensible library for opening URLs.
Jeremy Hyltone2573162009-03-31 14:38:13 +00006.. moduleauthor:: Jeremy Hylton <jeremy@alum.mit.edu>
Georg Brandl116aa622007-08-15 14:28:22 +00007.. sectionauthor:: Moshe Zadka <moshez@users.sourceforge.net>
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07008.. sectionauthor:: Senthil Kumaran <senthil@uthcode.com>
Georg Brandl116aa622007-08-15 14:28:22 +00009
10
Georg Brandl0f7ede42008-06-23 11:23:31 +000011The :mod:`urllib.request` module defines functions and classes which help in
12opening URLs (mostly HTTP) in a complex world --- basic and digest
13authentication, redirections, cookies and more.
Georg Brandl116aa622007-08-15 14:28:22 +000014
Antoine Pitrou79ecd762010-09-29 11:24:21 +000015
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000016The :mod:`urllib.request` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +000017
18
Antoine Pitrou803e6d62010-10-13 10:36:15 +000019.. function:: urlopen(url, data=None[, timeout], *, cafile=None, capath=None)
Georg Brandl116aa622007-08-15 14:28:22 +000020
Jeremy Hyltone2573162009-03-31 14:38:13 +000021 Open the URL *url*, which can be either a string or a
22 :class:`Request` object.
Georg Brandl116aa622007-08-15 14:28:22 +000023
Senthil Kumaran6b3434a2012-03-15 18:11:16 -070024 *data* must be a bytes object specifying additional data to be sent to the
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000025 server, or ``None`` if no such data is needed. *data* may also be an
26 iterable object and in that case Content-Length value must be specified in
27 the headers. Currently HTTP requests are the only ones that use *data*; the
28 HTTP request will be a POST instead of a GET when the *data* parameter is
Senthil Kumaran6b3434a2012-03-15 18:11:16 -070029 provided.
30
31 *data* should be a buffer in the standard
Georg Brandl116aa622007-08-15 14:28:22 +000032 :mimetype:`application/x-www-form-urlencoded` format. The
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000033 :func:`urllib.parse.urlencode` function takes a mapping or sequence of
Senthil Kumaran6b3434a2012-03-15 18:11:16 -070034 2-tuples and returns a string in this format. It should be encoded to bytes
35 before being used as the *data* parameter. The charset parameter in
36 ``Content-Type`` header may be used to specify the encoding. If charset
37 parameter is not sent with the Content-Type header, the server following the
38 HTTP 1.1 recommendation may assume that the data is encoded in ISO-8859-1
39 encoding. It is advisable to use charset parameter with encoding used in
40 ``Content-Type`` header with the :class:`Request`.
41
42 urllib.request module uses HTTP/1.1 and includes ``Connection:close`` header
43 in its HTTP requests.
Georg Brandl116aa622007-08-15 14:28:22 +000044
Jeremy Hyltone2573162009-03-31 14:38:13 +000045 The optional *timeout* parameter specifies a timeout in seconds for
46 blocking operations like the connection attempt (if not specified,
47 the global default timeout setting will be used). This actually
Senthil Kumaranc08d9072010-10-05 18:46:56 +000048 only works for HTTP, HTTPS and FTP connections.
Georg Brandl116aa622007-08-15 14:28:22 +000049
Antoine Pitrou803e6d62010-10-13 10:36:15 +000050 The optional *cafile* and *capath* parameters specify a set of trusted
51 CA certificates for HTTPS requests. *cafile* should point to a single
52 file containing a bundle of CA certificates, whereas *capath* should
53 point to a directory of hashed certificate files. More information can
54 be found in :meth:`ssl.SSLContext.load_verify_locations`.
55
56 .. warning::
57 If neither *cafile* nor *capath* is specified, an HTTPS request
58 will not do any verification of the server's certificate.
59
Senthil Kumaran21c71ba2012-03-13 19:47:51 -070060 This function returns a file-like object that works as a :term:`context manager`,
61 with two additional methods from the :mod:`urllib.response` module
Georg Brandl116aa622007-08-15 14:28:22 +000062
Jeremy Hyltone2573162009-03-31 14:38:13 +000063 * :meth:`geturl` --- return the URL of the resource retrieved,
64 commonly used to determine if a redirect was followed
Georg Brandl116aa622007-08-15 14:28:22 +000065
Georg Brandl2dd01042009-02-27 16:46:46 +000066 * :meth:`info` --- return the meta-information of the page, such as headers,
Senthil Kumaran13a7eb42010-06-28 17:31:40 +000067 in the form of an :func:`email.message_from_string` instance (see
68 `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
Georg Brandl116aa622007-08-15 14:28:22 +000069
70 Raises :exc:`URLError` on errors.
71
Georg Brandl2dd01042009-02-27 16:46:46 +000072 Note that ``None`` may be returned if no handler handles the request (though
73 the default installed global :class:`OpenerDirector` uses
74 :class:`UnknownHandler` to ensure this never happens).
75
Senthil Kumarana51a1b32009-10-18 01:42:33 +000076 In addition, default installed :class:`ProxyHandler` makes sure the requests
77 are handled through the proxy when they are set.
78
Georg Brandl2dd01042009-02-27 16:46:46 +000079 The legacy ``urllib.urlopen`` function from Python 2.6 and earlier has been
Senthil Kumaran6b3434a2012-03-15 18:11:16 -070080 discontinued; :func:`urllib.request.urlopen` corresponds to the old
81 ``urllib2.urlopen``. Proxy handling, which was done by passing a dictionary
82 parameter to ``urllib.urlopen``, can be obtained by using
83 :class:`ProxyHandler` objects.
Georg Brandl116aa622007-08-15 14:28:22 +000084
Antoine Pitrou803e6d62010-10-13 10:36:15 +000085 .. versionchanged:: 3.2
86 *cafile* and *capath* were added.
87
Antoine Pitroud5323212010-10-22 18:19:07 +000088 .. versionchanged:: 3.2
89 HTTPS virtual hosts are now supported if possible (that is, if
90 :data:`ssl.HAS_SNI` is true).
91
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000092 .. versionadded:: 3.2
93 *data* can be an iterable object.
94
Georg Brandl116aa622007-08-15 14:28:22 +000095.. function:: install_opener(opener)
96
97 Install an :class:`OpenerDirector` instance as the default global opener.
Senthil Kumaran6b3434a2012-03-15 18:11:16 -070098 Installing an opener is only necessary if you want urlopen to use that
99 opener; otherwise, simply call :meth:`OpenerDirector.open` instead of
100 :func:`~urllib.request.urlopen`. The code does not check for a real
101 :class:`OpenerDirector`, and any class with the appropriate interface will
102 work.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104
105.. function:: build_opener([handler, ...])
106
107 Return an :class:`OpenerDirector` instance, which chains the handlers in the
108 order given. *handler*\s can be either instances of :class:`BaseHandler`, or
109 subclasses of :class:`BaseHandler` (in which case it must be possible to call
110 the constructor without any parameters). Instances of the following classes
111 will be in front of the *handler*\s, unless the *handler*\s contain them,
112 instances of them or subclasses of them: :class:`ProxyHandler`,
113 :class:`UnknownHandler`, :class:`HTTPHandler`, :class:`HTTPDefaultErrorHandler`,
114 :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
115 :class:`HTTPErrorProcessor`.
116
Georg Brandl7f01a132009-09-16 15:58:14 +0000117 If the Python installation has SSL support (i.e., if the :mod:`ssl` module
118 can be imported), :class:`HTTPSHandler` will also be added.
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Georg Brandle6bcc912008-05-12 18:05:20 +0000120 A :class:`BaseHandler` subclass may also change its :attr:`handler_order`
Senthil Kumarana6bac952011-07-04 11:28:30 -0700121 attribute to modify its position in the handlers list.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Georg Brandl7f01a132009-09-16 15:58:14 +0000123
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000124.. function:: pathname2url(path)
Christian Heimes292d3512008-02-03 16:51:08 +0000125
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000126 Convert the pathname *path* from the local syntax for a path to the form used in
127 the path component of a URL. This does not produce a complete URL. The return
128 value will already be quoted using the :func:`quote` function.
Christian Heimes292d3512008-02-03 16:51:08 +0000129
130
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000131.. function:: url2pathname(path)
132
Senthil Kumaranf0769e82010-08-09 19:53:52 +0000133 Convert the path component *path* from a percent-encoded URL to the local syntax for a
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000134 path. This does not accept a complete URL. This function uses :func:`unquote`
135 to decode *path*.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
Senthil Kumaran7e557a62010-02-26 00:53:23 +0000137.. function:: getproxies()
138
139 This helper function returns a dictionary of scheme to proxy server URL
Senthil Kumaran19d85c22012-01-11 01:29:08 +0800140 mappings. It scans the environment for variables named ``<scheme>_proxy``,
141 in a case insensitive approach, for all operating systems first, and when it
142 cannot find it, looks for proxy information from Mac OSX System
143 Configuration for Mac OS X and Windows Systems Registry for Windows.
Senthil Kumaran7e557a62010-02-26 00:53:23 +0000144
Georg Brandl7f01a132009-09-16 15:58:14 +0000145
Georg Brandl116aa622007-08-15 14:28:22 +0000146The following classes are provided:
147
Senthil Kumarande49d642011-10-16 23:54:44 +0800148.. class:: Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150 This class is an abstraction of a URL request.
151
152 *url* should be a string containing a valid URL.
153
Senthil Kumaran6b3434a2012-03-15 18:11:16 -0700154 *data* must be a bytes object specifying additional data to send to the
Senthil Kumaran87684e62012-03-14 18:08:13 -0700155 server, or ``None`` if no such data is needed. Currently HTTP requests are
156 the only ones that use *data*; the HTTP request will be a POST instead of a
157 GET when the *data* parameter is provided. *data* should be a buffer in the
Senthil Kumaran6b3434a2012-03-15 18:11:16 -0700158 standard :mimetype:`application/x-www-form-urlencoded` format.
159
160 The :func:`urllib.parse.urlencode` function takes a mapping or sequence of
161 2-tuples and returns a string in this format. It should be encoded to bytes
162 before being used as the *data* parameter. The charset parameter in
163 ``Content-Type`` header may be used to specify the encoding. If charset
164 parameter is not sent with the Content-Type header, the server following the
165 HTTP 1.1 recommendation may assume that the data is encoded in ISO-8859-1
166 encoding. It is advisable to use charset parameter with encoding used in
167 ``Content-Type`` header with the :class:`Request`.
168
Georg Brandl116aa622007-08-15 14:28:22 +0000169
Jeremy Hyltone2573162009-03-31 14:38:13 +0000170 *headers* should be a dictionary, and will be treated as if
171 :meth:`add_header` was called with each key and value as arguments.
172 This is often used to "spoof" the ``User-Agent`` header, which is
173 used by a browser to identify itself -- some HTTP servers only
174 allow requests coming from common browsers as opposed to scripts.
175 For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0
176 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while
177 :mod:`urllib`'s default user agent string is
178 ``"Python-urllib/2.6"`` (on Python 2.6).
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Senthil Kumaran6b3434a2012-03-15 18:11:16 -0700180 An example of using ``Content-Type`` header with *data* argument would be
181 sending a dictionary like ``{"Content-Type":" application/x-www-form-urlencoded;charset=utf-8"}``
182
Jeremy Hyltone2573162009-03-31 14:38:13 +0000183 The final two arguments are only of interest for correct handling
184 of third-party HTTP cookies:
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Jeremy Hyltone2573162009-03-31 14:38:13 +0000186 *origin_req_host* should be the request-host of the origin
187 transaction, as defined by :rfc:`2965`. It defaults to
188 ``http.cookiejar.request_host(self)``. This is the host name or IP
189 address of the original request that was initiated by the user.
190 For example, if the request is for an image in an HTML document,
191 this should be the request-host of the request for the page
Georg Brandl24420152008-05-26 16:32:26 +0000192 containing the image.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Jeremy Hyltone2573162009-03-31 14:38:13 +0000194 *unverifiable* should indicate whether the request is unverifiable,
195 as defined by RFC 2965. It defaults to False. An unverifiable
196 request is one whose URL the user did not have the option to
197 approve. For example, if the request is for an image in an HTML
198 document, and the user had no option to approve the automatic
199 fetching of the image, this should be true.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Senthil Kumarande49d642011-10-16 23:54:44 +0800201 *method* should be a string that indicates the HTTP request method that
202 will be used (e.g. ``'HEAD'``). Its value is stored in the
Senthil Kumarana41c9422011-10-20 02:37:08 +0800203 :attr:`~Request.method` attribute and is used by :meth:`get_method()`.
Senthil Kumarande49d642011-10-16 23:54:44 +0800204
205 .. versionchanged:: 3.3
206 :attr:`Request.method` argument is added to the Request class.
207
Georg Brandl7f01a132009-09-16 15:58:14 +0000208
Georg Brandl116aa622007-08-15 14:28:22 +0000209.. class:: OpenerDirector()
210
211 The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained
212 together. It manages the chaining of handlers, and recovery from errors.
213
214
215.. class:: BaseHandler()
216
217 This is the base class for all registered handlers --- and handles only the
218 simple mechanics of registration.
219
220
221.. class:: HTTPDefaultErrorHandler()
222
223 A class which defines a default handler for HTTP error responses; all responses
224 are turned into :exc:`HTTPError` exceptions.
225
226
227.. class:: HTTPRedirectHandler()
228
229 A class to handle redirections.
230
231
Georg Brandl7f01a132009-09-16 15:58:14 +0000232.. class:: HTTPCookieProcessor(cookiejar=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234 A class to handle HTTP Cookies.
235
236
Georg Brandl7f01a132009-09-16 15:58:14 +0000237.. class:: ProxyHandler(proxies=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239 Cause requests to go through a proxy. If *proxies* is given, it must be a
240 dictionary mapping protocol names to URLs of proxies. The default is to read the
241 list of proxies from the environment variables :envvar:`<protocol>_proxy`.
Senthil Kumarana51a1b32009-10-18 01:42:33 +0000242 If no proxy environment variables are set, in a Windows environment, proxy
243 settings are obtained from the registry's Internet Settings section and in a
244 Mac OS X environment, proxy information is retrieved from the OS X System
245 Configuration Framework.
246
Christian Heimese25f35e2008-03-20 10:49:03 +0000247 To disable autodetected proxy pass an empty dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249
250.. class:: HTTPPasswordMgr()
251
252 Keep a database of ``(realm, uri) -> (user, password)`` mappings.
253
254
255.. class:: HTTPPasswordMgrWithDefaultRealm()
256
257 Keep a database of ``(realm, uri) -> (user, password)`` mappings. A realm of
258 ``None`` is considered a catch-all realm, which is searched if no other realm
259 fits.
260
261
Georg Brandl7f01a132009-09-16 15:58:14 +0000262.. class:: AbstractBasicAuthHandler(password_mgr=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264 This is a mixin class that helps with HTTP authentication, both to the remote
265 host and to a proxy. *password_mgr*, if given, should be something that is
266 compatible with :class:`HTTPPasswordMgr`; refer to section
267 :ref:`http-password-mgr` for information on the interface that must be
268 supported.
269
270
Georg Brandl7f01a132009-09-16 15:58:14 +0000271.. class:: HTTPBasicAuthHandler(password_mgr=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800273 Handle authentication with the remote host. *password_mgr*, if given, should
274 be something that is compatible with :class:`HTTPPasswordMgr`; refer to
275 section :ref:`http-password-mgr` for information on the interface that must
276 be supported. HTTPBasicAuthHandler will raise a :exc:`ValueError` when
277 presented with a wrong Authentication scheme.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279
Georg Brandl7f01a132009-09-16 15:58:14 +0000280.. class:: ProxyBasicAuthHandler(password_mgr=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282 Handle authentication with the proxy. *password_mgr*, if given, should be
283 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
284 :ref:`http-password-mgr` for information on the interface that must be
285 supported.
286
287
Georg Brandl7f01a132009-09-16 15:58:14 +0000288.. class:: AbstractDigestAuthHandler(password_mgr=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 This is a mixin class that helps with HTTP authentication, both to the remote
291 host and to a proxy. *password_mgr*, if given, should be something that is
292 compatible with :class:`HTTPPasswordMgr`; refer to section
293 :ref:`http-password-mgr` for information on the interface that must be
294 supported.
295
296
Georg Brandl7f01a132009-09-16 15:58:14 +0000297.. class:: HTTPDigestAuthHandler(password_mgr=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800299 Handle authentication with the remote host. *password_mgr*, if given, should
300 be something that is compatible with :class:`HTTPPasswordMgr`; refer to
301 section :ref:`http-password-mgr` for information on the interface that must
302 be supported. When both Digest Authentication Handler and Basic
303 Authentication Handler are both added, Digest Authentication is always tried
304 first. If the Digest Authentication returns a 40x response again, it is sent
305 to Basic Authentication handler to Handle. This Handler method will raise a
306 :exc:`ValueError` when presented with an authentication scheme other than
307 Digest or Basic.
308
Ezio Melottie9c7d6c2011-05-12 01:10:57 +0300309 .. versionchanged:: 3.3
310 Raise :exc:`ValueError` on unsupported Authentication Scheme.
Senthil Kumaran4de00a22011-05-11 21:17:57 +0800311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313
Georg Brandl7f01a132009-09-16 15:58:14 +0000314.. class:: ProxyDigestAuthHandler(password_mgr=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316 Handle authentication with the proxy. *password_mgr*, if given, should be
317 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
318 :ref:`http-password-mgr` for information on the interface that must be
319 supported.
320
321
322.. class:: HTTPHandler()
323
324 A class to handle opening of HTTP URLs.
325
326
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000327.. class:: HTTPSHandler(debuglevel=0, context=None, check_hostname=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000329 A class to handle opening of HTTPS URLs. *context* and *check_hostname*
330 have the same meaning as in :class:`http.client.HTTPSConnection`.
331
332 .. versionchanged:: 3.2
333 *context* and *check_hostname* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335
336.. class:: FileHandler()
337
338 Open local files.
339
340
341.. class:: FTPHandler()
342
343 Open FTP URLs.
344
345
346.. class:: CacheFTPHandler()
347
348 Open FTP URLs, keeping a cache of open FTP connections to minimize delays.
349
350
351.. class:: UnknownHandler()
352
353 A catch-all class to handle unknown URLs.
354
355
Senthil Kumaraned270fa2011-07-18 06:42:46 +0800356.. class:: HTTPErrorProcessor()
357
358 Process HTTP error responses.
359
360
Georg Brandl116aa622007-08-15 14:28:22 +0000361.. _request-objects:
362
363Request Objects
364---------------
365
Jeremy Hyltone2573162009-03-31 14:38:13 +0000366The following methods describe :class:`Request`'s public interface,
367and so all may be overridden in subclasses. It also defines several
368public attributes that can be used by clients to inspect the parsed
369request.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Jeremy Hyltone2573162009-03-31 14:38:13 +0000371.. attribute:: Request.full_url
372
373 The original URL passed to the constructor.
374
375.. attribute:: Request.type
376
377 The URI scheme.
378
379.. attribute:: Request.host
380
381 The URI authority, typically a host, but may also contain a port
382 separated by a colon.
383
384.. attribute:: Request.origin_req_host
385
386 The original host for the request, without port.
387
388.. attribute:: Request.selector
389
390 The URI path. If the :class:`Request` uses a proxy, then selector
391 will be the full url that is passed to the proxy.
392
393.. attribute:: Request.data
394
395 The entity body for the request, or None if not specified.
396
397.. attribute:: Request.unverifiable
398
399 boolean, indicates whether the request is unverifiable as defined
400 by RFC 2965.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
Senthil Kumarande49d642011-10-16 23:54:44 +0800402.. attribute:: Request.method
403
404 The HTTP request method to use. This value is used by
Senthil Kumarana41c9422011-10-20 02:37:08 +0800405 :meth:`~Request.get_method` to override the computed HTTP request
406 method that would otherwise be returned. This attribute is initialized with
407 the value of the *method* argument passed to the constructor.
Senthil Kumarande49d642011-10-16 23:54:44 +0800408
Senthil Kumarana41c9422011-10-20 02:37:08 +0800409 .. versionadded:: 3.3
Senthil Kumarande49d642011-10-16 23:54:44 +0800410
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412.. method:: Request.get_method()
413
Senthil Kumarande49d642011-10-16 23:54:44 +0800414 Return a string indicating the HTTP request method. If
415 :attr:`Request.method` is not ``None``, return its value, otherwise return
416 ``'GET'`` if :attr:`Request.data` is ``None``, or ``'POST'`` if it's not.
417 This is only meaningful for HTTP requests.
418
Florent Xicluna95483b62011-10-19 11:44:51 +0200419 .. versionchanged:: 3.3
Senthil Kumarana41c9422011-10-20 02:37:08 +0800420 get_method now looks at the value of :attr:`Request.method`.
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422
Georg Brandl116aa622007-08-15 14:28:22 +0000423.. method:: Request.add_header(key, val)
424
425 Add another header to the request. Headers are currently ignored by all
426 handlers except HTTP handlers, where they are added to the list of headers sent
427 to the server. Note that there cannot be more than one header with the same
428 name, and later calls will overwrite previous calls in case the *key* collides.
429 Currently, this is no loss of HTTP functionality, since all headers which have
430 meaning when used more than once have a (header-specific) way of gaining the
431 same functionality using only one header.
432
433
434.. method:: Request.add_unredirected_header(key, header)
435
436 Add a header that will not be added to a redirected request.
437
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439.. method:: Request.has_header(header)
440
441 Return whether the instance has the named header (checks both regular and
442 unredirected).
443
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445.. method:: Request.get_full_url()
446
447 Return the URL given in the constructor.
448
449
Georg Brandl116aa622007-08-15 14:28:22 +0000450.. method:: Request.set_proxy(host, type)
451
452 Prepare the request by connecting to a proxy server. The *host* and *type* will
453 replace those of the instance, and the instance's selector will be the original
454 URL given in the constructor.
455
456
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700457.. method:: Request.add_data(data)
458
459 Set the :class:`Request` data to *data*. This is ignored by all handlers except
460 HTTP handlers --- and there it should be a byte string, and will change the
461 request to be ``POST`` rather than ``GET``. Deprecated in 3.3, use
462 :attr:`Request.data`.
463
464 .. deprecated:: 3.3
465
466
467.. method:: Request.has_data()
468
469 Return whether the instance has a non-\ ``None`` data. Deprecated in 3.3,
470 use :attr:`Request.data`.
471
472 .. deprecated:: 3.3
473
474
475.. method:: Request.get_data()
476
477 Return the instance's data. Deprecated in 3.3, use :attr:`Request.data`.
478
479 .. deprecated:: 3.3
480
481
482.. method:: Request.get_type()
483
484 Return the type of the URL --- also known as the scheme. Deprecated in 3.3,
485 use :attr:`Request.type`.
486
487 .. deprecated:: 3.3
488
489
490.. method:: Request.get_host()
491
492 Return the host to which a connection will be made. Deprecated in 3.3, use
493 :attr:`Request.host`.
494
495 .. deprecated:: 3.3
496
497
498.. method:: Request.get_selector()
499
500 Return the selector --- the part of the URL that is sent to the server.
501 Deprecated in 3.3, use :attr:`Request.selector`.
502
503 .. deprecated:: 3.3
504
Senthil Kumaran8dc50042012-04-29 11:50:39 +0800505.. method:: Request.get_header(header_name, default=None)
506
507 Return the value of the given header. If the header is not present, return
508 the default value.
509
510
511.. method:: Request.header_items()
512
513 Return a list of tuples (header_name, header_value) of the Request headers.
514
515
Georg Brandl116aa622007-08-15 14:28:22 +0000516.. method:: Request.set_proxy(host, type)
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700517
Georg Brandl116aa622007-08-15 14:28:22 +0000518.. method:: Request.get_origin_req_host()
519
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700520 Return the request-host of the origin transaction, as defined by
521 :rfc:`2965`. See the documentation for the :class:`Request` constructor.
522 Deprecated in 3.3, use :attr:`Request.origin_req_host`.
523
524 .. deprecated:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526
527.. method:: Request.is_unverifiable()
528
529 Return whether the request is unverifiable, as defined by RFC 2965. See the
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700530 documentation for the :class:`Request` constructor. Deprecated in 3.3, use
531 :attr:`Request.is_unverifiable`.
532
533 .. deprecated:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535
536.. _opener-director-objects:
537
538OpenerDirector Objects
539----------------------
540
541:class:`OpenerDirector` instances have the following methods:
542
543
544.. method:: OpenerDirector.add_handler(handler)
545
546 *handler* should be an instance of :class:`BaseHandler`. The following methods
547 are searched, and added to the possible chains (note that HTTP errors are a
548 special case).
549
550 * :meth:`protocol_open` --- signal that the handler knows how to open *protocol*
551 URLs.
552
553 * :meth:`http_error_type` --- signal that the handler knows how to handle HTTP
554 errors with HTTP error code *type*.
555
556 * :meth:`protocol_error` --- signal that the handler knows how to handle errors
557 from (non-\ ``http``) *protocol*.
558
559 * :meth:`protocol_request` --- signal that the handler knows how to pre-process
560 *protocol* requests.
561
562 * :meth:`protocol_response` --- signal that the handler knows how to
563 post-process *protocol* responses.
564
565
Georg Brandl7f01a132009-09-16 15:58:14 +0000566.. method:: OpenerDirector.open(url, data=None[, timeout])
Georg Brandl116aa622007-08-15 14:28:22 +0000567
568 Open the given *url* (which can be a request object or a string), optionally
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000569 passing the given *data*. Arguments, return values and exceptions raised are
570 the same as those of :func:`urlopen` (which simply calls the :meth:`open`
571 method on the currently installed global :class:`OpenerDirector`). The
572 optional *timeout* parameter specifies a timeout in seconds for blocking
Georg Brandlf78e02b2008-06-10 17:40:04 +0000573 operations like the connection attempt (if not specified, the global default
Georg Brandl325524e2010-05-21 20:57:33 +0000574 timeout setting will be used). The timeout feature actually works only for
Senthil Kumaranc08d9072010-10-05 18:46:56 +0000575 HTTP, HTTPS and FTP connections).
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Georg Brandl116aa622007-08-15 14:28:22 +0000577
Georg Brandl7f01a132009-09-16 15:58:14 +0000578.. method:: OpenerDirector.error(proto, *args)
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580 Handle an error of the given protocol. This will call the registered error
581 handlers for the given protocol with the given arguments (which are protocol
582 specific). The HTTP protocol is a special case which uses the HTTP response
583 code to determine the specific error handler; refer to the :meth:`http_error_\*`
584 methods of the handler classes.
585
586 Return values and exceptions raised are the same as those of :func:`urlopen`.
587
588OpenerDirector objects open URLs in three stages:
589
590The order in which these methods are called within each stage is determined by
591sorting the handler instances.
592
593#. Every handler with a method named like :meth:`protocol_request` has that
594 method called to pre-process the request.
595
596#. Handlers with a method named like :meth:`protocol_open` are called to handle
597 the request. This stage ends when a handler either returns a non-\ :const:`None`
598 value (ie. a response), or raises an exception (usually :exc:`URLError`).
599 Exceptions are allowed to propagate.
600
601 In fact, the above algorithm is first tried for methods named
602 :meth:`default_open`. If all such methods return :const:`None`, the algorithm
603 is repeated for methods named like :meth:`protocol_open`. If all such methods
604 return :const:`None`, the algorithm is repeated for methods named
605 :meth:`unknown_open`.
606
607 Note that the implementation of these methods may involve calls of the parent
Georg Brandla5eacee2010-07-23 16:55:26 +0000608 :class:`OpenerDirector` instance's :meth:`~OpenerDirector.open` and
609 :meth:`~OpenerDirector.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
611#. Every handler with a method named like :meth:`protocol_response` has that
612 method called to post-process the response.
613
614
615.. _base-handler-objects:
616
617BaseHandler Objects
618-------------------
619
620:class:`BaseHandler` objects provide a couple of methods that are directly
621useful, and others that are meant to be used by derived classes. These are
622intended for direct use:
623
624
625.. method:: BaseHandler.add_parent(director)
626
627 Add a director as parent.
628
629
630.. method:: BaseHandler.close()
631
632 Remove any parents.
633
Senthil Kumarana6bac952011-07-04 11:28:30 -0700634The following attribute and methods should only be used by classes derived from
Georg Brandl116aa622007-08-15 14:28:22 +0000635:class:`BaseHandler`.
636
637.. note::
638
639 The convention has been adopted that subclasses defining
640 :meth:`protocol_request` or :meth:`protocol_response` methods are named
641 :class:`\*Processor`; all others are named :class:`\*Handler`.
642
643
644.. attribute:: BaseHandler.parent
645
646 A valid :class:`OpenerDirector`, which can be used to open using a different
647 protocol, or handle errors.
648
649
650.. method:: BaseHandler.default_open(req)
651
652 This method is *not* defined in :class:`BaseHandler`, but subclasses should
653 define it if they want to catch all URLs.
654
655 This method, if implemented, will be called by the parent
656 :class:`OpenerDirector`. It should return a file-like object as described in
657 the return value of the :meth:`open` of :class:`OpenerDirector`, or ``None``.
658 It should raise :exc:`URLError`, unless a truly exceptional thing happens (for
659 example, :exc:`MemoryError` should not be mapped to :exc:`URLError`).
660
661 This method will be called before any protocol-specific open method.
662
663
664.. method:: BaseHandler.protocol_open(req)
665 :noindex:
666
667 This method is *not* defined in :class:`BaseHandler`, but subclasses should
668 define it if they want to handle URLs with the given protocol.
669
670 This method, if defined, will be called by the parent :class:`OpenerDirector`.
671 Return values should be the same as for :meth:`default_open`.
672
673
674.. method:: BaseHandler.unknown_open(req)
675
676 This method is *not* defined in :class:`BaseHandler`, but subclasses should
677 define it if they want to catch all URLs with no specific registered handler to
678 open it.
679
680 This method, if implemented, will be called by the :attr:`parent`
681 :class:`OpenerDirector`. Return values should be the same as for
682 :meth:`default_open`.
683
684
685.. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs)
686
687 This method is *not* defined in :class:`BaseHandler`, but subclasses should
688 override it if they intend to provide a catch-all for otherwise unhandled HTTP
689 errors. It will be called automatically by the :class:`OpenerDirector` getting
690 the error, and should not normally be called in other circumstances.
691
692 *req* will be a :class:`Request` object, *fp* will be a file-like object with
693 the HTTP error body, *code* will be the three-digit code of the error, *msg*
694 will be the user-visible explanation of the code and *hdrs* will be a mapping
695 object with the headers of the error.
696
697 Return values and exceptions raised should be the same as those of
698 :func:`urlopen`.
699
700
701.. method:: BaseHandler.http_error_nnn(req, fp, code, msg, hdrs)
702
703 *nnn* should be a three-digit HTTP error code. This method is also not defined
704 in :class:`BaseHandler`, but will be called, if it exists, on an instance of a
705 subclass, when an HTTP error with code *nnn* occurs.
706
707 Subclasses should override this method to handle specific HTTP errors.
708
709 Arguments, return values and exceptions raised should be the same as for
710 :meth:`http_error_default`.
711
712
713.. method:: BaseHandler.protocol_request(req)
714 :noindex:
715
716 This method is *not* defined in :class:`BaseHandler`, but subclasses should
717 define it if they want to pre-process requests of the given protocol.
718
719 This method, if defined, will be called by the parent :class:`OpenerDirector`.
720 *req* will be a :class:`Request` object. The return value should be a
721 :class:`Request` object.
722
723
724.. method:: BaseHandler.protocol_response(req, response)
725 :noindex:
726
727 This method is *not* defined in :class:`BaseHandler`, but subclasses should
728 define it if they want to post-process responses of the given protocol.
729
730 This method, if defined, will be called by the parent :class:`OpenerDirector`.
731 *req* will be a :class:`Request` object. *response* will be an object
732 implementing the same interface as the return value of :func:`urlopen`. The
733 return value should implement the same interface as the return value of
734 :func:`urlopen`.
735
736
737.. _http-redirect-handler:
738
739HTTPRedirectHandler Objects
740---------------------------
741
742.. note::
743
744 Some HTTP redirections require action from this module's client code. If this
745 is the case, :exc:`HTTPError` is raised. See :rfc:`2616` for details of the
746 precise meanings of the various redirection codes.
747
guido@google.coma119df92011-03-29 11:41:02 -0700748 An :class:`HTTPError` exception raised as a security consideration if the
749 HTTPRedirectHandler is presented with a redirected url which is not an HTTP,
750 HTTPS or FTP url.
751
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Georg Brandl9617a592009-02-13 10:40:43 +0000753.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755 Return a :class:`Request` or ``None`` in response to a redirect. This is called
756 by the default implementations of the :meth:`http_error_30\*` methods when a
757 redirection is received from the server. If a redirection should take place,
758 return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the
Georg Brandl9617a592009-02-13 10:40:43 +0000759 redirect to *newurl*. Otherwise, raise :exc:`HTTPError` if no other handler
760 should try to handle this URL, or return ``None`` if you can't but another
761 handler might.
Georg Brandl116aa622007-08-15 14:28:22 +0000762
763 .. note::
764
765 The default implementation of this method does not strictly follow :rfc:`2616`,
766 which says that 301 and 302 responses to ``POST`` requests must not be
767 automatically redirected without confirmation by the user. In reality, browsers
768 do allow automatic redirection of these responses, changing the POST to a
769 ``GET``, and the default implementation reproduces this behavior.
770
771
772.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)
773
Georg Brandl9617a592009-02-13 10:40:43 +0000774 Redirect to the ``Location:`` or ``URI:`` URL. This method is called by the
775 parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.
Georg Brandl116aa622007-08-15 14:28:22 +0000776
777
778.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)
779
780 The same as :meth:`http_error_301`, but called for the 'found' response.
781
782
783.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)
784
785 The same as :meth:`http_error_301`, but called for the 'see other' response.
786
787
788.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)
789
790 The same as :meth:`http_error_301`, but called for the 'temporary redirect'
791 response.
792
793
794.. _http-cookie-processor:
795
796HTTPCookieProcessor Objects
797---------------------------
798
Georg Brandl116aa622007-08-15 14:28:22 +0000799:class:`HTTPCookieProcessor` instances have one attribute:
800
Georg Brandl116aa622007-08-15 14:28:22 +0000801.. attribute:: HTTPCookieProcessor.cookiejar
802
Georg Brandl24420152008-05-26 16:32:26 +0000803 The :class:`http.cookiejar.CookieJar` in which cookies are stored.
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805
806.. _proxy-handler:
807
808ProxyHandler Objects
809--------------------
810
811
812.. method:: ProxyHandler.protocol_open(request)
813 :noindex:
814
815 The :class:`ProxyHandler` will have a method :meth:`protocol_open` for every
816 *protocol* which has a proxy in the *proxies* dictionary given in the
817 constructor. The method will modify requests to go through the proxy, by
818 calling ``request.set_proxy()``, and call the next handler in the chain to
819 actually execute the protocol.
820
821
822.. _http-password-mgr:
823
824HTTPPasswordMgr Objects
825-----------------------
826
827These methods are available on :class:`HTTPPasswordMgr` and
828:class:`HTTPPasswordMgrWithDefaultRealm` objects.
829
830
831.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd)
832
833 *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and
834 *passwd* must be strings. This causes ``(user, passwd)`` to be used as
835 authentication tokens when authentication for *realm* and a super-URI of any of
836 the given URIs is given.
837
838
839.. method:: HTTPPasswordMgr.find_user_password(realm, authuri)
840
841 Get user/password for given realm and URI, if any. This method will return
842 ``(None, None)`` if there is no matching user/password.
843
844 For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be
845 searched if the given *realm* has no matching user/password.
846
847
848.. _abstract-basic-auth-handler:
849
850AbstractBasicAuthHandler Objects
851--------------------------------
852
853
854.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
855
856 Handle an authentication request by getting a user/password pair, and re-trying
857 the request. *authreq* should be the name of the header where the information
858 about the realm is included in the request, *host* specifies the URL and path to
859 authenticate for, *req* should be the (failed) :class:`Request` object, and
860 *headers* should be the error headers.
861
862 *host* is either an authority (e.g. ``"python.org"``) or a URL containing an
863 authority component (e.g. ``"http://python.org/"``). In either case, the
864 authority must not contain a userinfo component (so, ``"python.org"`` and
865 ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not).
866
867
868.. _http-basic-auth-handler:
869
870HTTPBasicAuthHandler Objects
871----------------------------
872
873
874.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)
875
876 Retry the request with authentication information, if available.
877
878
879.. _proxy-basic-auth-handler:
880
881ProxyBasicAuthHandler Objects
882-----------------------------
883
884
885.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)
886
887 Retry the request with authentication information, if available.
888
889
890.. _abstract-digest-auth-handler:
891
892AbstractDigestAuthHandler Objects
893---------------------------------
894
895
896.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
897
898 *authreq* should be the name of the header where the information about the realm
899 is included in the request, *host* should be the host to authenticate to, *req*
900 should be the (failed) :class:`Request` object, and *headers* should be the
901 error headers.
902
903
904.. _http-digest-auth-handler:
905
906HTTPDigestAuthHandler Objects
907-----------------------------
908
909
910.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)
911
912 Retry the request with authentication information, if available.
913
914
915.. _proxy-digest-auth-handler:
916
917ProxyDigestAuthHandler Objects
918------------------------------
919
920
921.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)
922
923 Retry the request with authentication information, if available.
924
925
926.. _http-handler-objects:
927
928HTTPHandler Objects
929-------------------
930
931
932.. method:: HTTPHandler.http_open(req)
933
934 Send an HTTP request, which can be either GET or POST, depending on
935 ``req.has_data()``.
936
937
938.. _https-handler-objects:
939
940HTTPSHandler Objects
941--------------------
942
943
944.. method:: HTTPSHandler.https_open(req)
945
946 Send an HTTPS request, which can be either GET or POST, depending on
947 ``req.has_data()``.
948
949
950.. _file-handler-objects:
951
952FileHandler Objects
953-------------------
954
955
956.. method:: FileHandler.file_open(req)
957
958 Open the file locally, if there is no host name, or the host name is
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000959 ``'localhost'``.
960
961 This method is applicable only for local hostnames. When a remote hostname
962 is given, an :exc:`URLError` is raised.
963
964.. versionchanged:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966
967.. _ftp-handler-objects:
968
969FTPHandler Objects
970------------------
971
972
973.. method:: FTPHandler.ftp_open(req)
974
975 Open the FTP file indicated by *req*. The login is always done with empty
976 username and password.
977
978
979.. _cacheftp-handler-objects:
980
981CacheFTPHandler Objects
982-----------------------
983
984:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the
985following additional methods:
986
987
988.. method:: CacheFTPHandler.setTimeout(t)
989
990 Set timeout of connections to *t* seconds.
991
992
993.. method:: CacheFTPHandler.setMaxConns(m)
994
995 Set maximum number of cached connections to *m*.
996
997
998.. _unknown-handler-objects:
999
1000UnknownHandler Objects
1001----------------------
1002
1003
1004.. method:: UnknownHandler.unknown_open()
1005
1006 Raise a :exc:`URLError` exception.
1007
1008
1009.. _http-error-processor-objects:
1010
1011HTTPErrorProcessor Objects
1012--------------------------
1013
Senthil Kumaran0215d092011-07-18 07:12:40 +08001014.. method:: HTTPErrorProcessor.http_response()
Georg Brandl116aa622007-08-15 14:28:22 +00001015
1016 Process HTTP error responses.
1017
1018 For 200 error codes, the response object is returned immediately.
1019
1020 For non-200 error codes, this simply passes the job on to the
1021 :meth:`protocol_error_code` handler methods, via :meth:`OpenerDirector.error`.
Georg Brandl0f7ede42008-06-23 11:23:31 +00001022 Eventually, :class:`HTTPDefaultErrorHandler` will raise an
Georg Brandl116aa622007-08-15 14:28:22 +00001023 :exc:`HTTPError` if no other handler handles the error.
1024
Georg Brandl0f7ede42008-06-23 11:23:31 +00001025
Senthil Kumaran0215d092011-07-18 07:12:40 +08001026.. method:: HTTPErrorProcessor.https_response()
1027
Senthil Kumaran3e7f33f2011-07-18 07:17:20 +08001028 Process HTTPS error responses.
1029
Senthil Kumaran0215d092011-07-18 07:12:40 +08001030 The behavior is same as :meth:`http_response`.
1031
1032
Georg Brandl0f7ede42008-06-23 11:23:31 +00001033.. _urllib-request-examples:
Georg Brandl116aa622007-08-15 14:28:22 +00001034
1035Examples
1036--------
1037
Senthil Kumaran0c2d8b82010-04-22 10:53:30 +00001038This example gets the python.org main page and displays the first 300 bytes of
Georg Brandlbdc55ab2010-04-20 18:15:54 +00001039it. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001040
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001041 >>> import urllib.request
1042 >>> f = urllib.request.urlopen('http://www.python.org/')
Senthil Kumaran0c2d8b82010-04-22 10:53:30 +00001043 >>> print(f.read(300))
1044 b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1045 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
1046 xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n
1047 <meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
1048 <title>Python Programming '
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001049
Senthil Kumaran0c2d8b82010-04-22 10:53:30 +00001050Note that urlopen returns a bytes object. This is because there is no way
1051for urlopen to automatically determine the encoding of the byte stream
1052it receives from the http server. In general, a program will decode
1053the returned bytes object to string once it determines or guesses
1054the appropriate encoding.
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001055
Senthil Kumaran0c2d8b82010-04-22 10:53:30 +00001056The following W3C document, http://www.w3.org/International/O-charset , lists
1057the various ways in which a (X)HTML or a XML document could have specified its
1058encoding information.
1059
Senthil Kumaran21c71ba2012-03-13 19:47:51 -07001060As the python.org website uses *utf-8* encoding as specified in it's meta tag, we
1061will use the same for decoding the bytes object. ::
1062
1063 >>> with urllib.request.urlopen('http://www.python.org/') as f:
1064 ... print(f.read(100).decode('utf-8'))
1065 ...
1066 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1067 "http://www.w3.org/TR/xhtml1/DTD/xhtm
1068
1069It is also possible to achieve the same result without using the
1070:term:`context manager` approach. ::
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001071
1072 >>> import urllib.request
1073 >>> f = urllib.request.urlopen('http://www.python.org/')
Georg Brandlfe4fd832010-05-21 21:01:32 +00001074 >>> print(f.read(100).decode('utf-8'))
Senthil Kumaran0c2d8b82010-04-22 10:53:30 +00001075 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1076 "http://www.w3.org/TR/xhtml1/DTD/xhtm
1077
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001078In the following example, we are sending a data-stream to the stdin of a CGI
1079and reading the data it returns to us. Note that this example will only work
1080when the Python installation supports SSL. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001081
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001082 >>> import urllib.request
1083 >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
Senthil Kumaran29333122011-02-11 11:25:47 +00001084 ... data=b'This data is passed to stdin of the CGI')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001085 >>> f = urllib.request.urlopen(req)
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001086 >>> print(f.read().decode('utf-8'))
Georg Brandl116aa622007-08-15 14:28:22 +00001087 Got Data: "This data is passed to stdin of the CGI"
1088
1089The code for the sample CGI used in the above example is::
1090
1091 #!/usr/bin/env python
1092 import sys
1093 data = sys.stdin.read()
Collin Winterc79461b2007-09-01 23:34:30 +00001094 print('Content-type: text-plain\n\nGot Data: "%s"' % data)
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096Use of Basic HTTP Authentication::
1097
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001098 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +00001099 # Create an OpenerDirector with support for Basic HTTP Authentication...
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001100 auth_handler = urllib.request.HTTPBasicAuthHandler()
Georg Brandl116aa622007-08-15 14:28:22 +00001101 auth_handler.add_password(realm='PDQ Application',
1102 uri='https://mahler:8092/site-updates.py',
1103 user='klem',
1104 passwd='kadidd!ehopper')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001105 opener = urllib.request.build_opener(auth_handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001106 # ...and install it globally so it can be used with urlopen.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001107 urllib.request.install_opener(opener)
1108 urllib.request.urlopen('http://www.example.com/login.html')
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110:func:`build_opener` provides many handlers by default, including a
1111:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment
1112variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme
1113involved. For example, the :envvar:`http_proxy` environment variable is read to
1114obtain the HTTP proxy's URL.
1115
1116This example replaces the default :class:`ProxyHandler` with one that uses
Georg Brandl2ee470f2008-07-16 12:55:28 +00001117programmatically-supplied proxy URLs, and adds proxy authorization support with
Georg Brandl116aa622007-08-15 14:28:22 +00001118:class:`ProxyBasicAuthHandler`. ::
1119
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001120 proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
Senthil Kumaran037f8362009-12-24 02:24:37 +00001121 proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
Georg Brandl116aa622007-08-15 14:28:22 +00001122 proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
1123
Senthil Kumaran037f8362009-12-24 02:24:37 +00001124 opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001125 # This time, rather than install the OpenerDirector, we use it directly:
1126 opener.open('http://www.example.com/login.html')
1127
1128Adding HTTP headers:
1129
1130Use the *headers* argument to the :class:`Request` constructor, or::
1131
Georg Brandl029986a2008-06-23 11:44:14 +00001132 import urllib.request
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001133 req = urllib.request.Request('http://www.example.com/')
Georg Brandl116aa622007-08-15 14:28:22 +00001134 req.add_header('Referer', 'http://www.python.org/')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001135 r = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
1138every :class:`Request`. To change this::
1139
Georg Brandl029986a2008-06-23 11:44:14 +00001140 import urllib.request
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001141 opener = urllib.request.build_opener()
Georg Brandl116aa622007-08-15 14:28:22 +00001142 opener.addheaders = [('User-agent', 'Mozilla/5.0')]
1143 opener.open('http://www.example.com/')
1144
1145Also, remember that a few standard headers (:mailheader:`Content-Length`,
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07001146:mailheader:`Content-Type` without charset parameter and :mailheader:`Host`)
1147are added when the :class:`Request` is passed to :func:`urlopen` (or
1148:meth:`OpenerDirector.open`).
Georg Brandl116aa622007-08-15 14:28:22 +00001149
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001150.. _urllib-examples:
1151
1152Here is an example session that uses the ``GET`` method to retrieve a URL
1153containing parameters::
1154
1155 >>> import urllib.request
1156 >>> import urllib.parse
1157 >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
1158 >>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001159 >>> print(f.read().decode('utf-8'))
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001160
Senthil Kumaran29333122011-02-11 11:25:47 +00001161The following example uses the ``POST`` method instead. Note that params output
1162from urlencode is encoded to bytes before it is sent to urlopen as data::
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001163
1164 >>> import urllib.request
1165 >>> import urllib.parse
Senthil Kumaran6b3434a2012-03-15 18:11:16 -07001166 >>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
1167 >>> data = data.encode('utf-8')
1168 >>> request = urllib.request.Request("http://requestb.in/xrbl82xr")
1169 >>> # adding charset parameter to the Content-Type header.
1170 >>> request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
1171 >>> f = urllib.request.urlopen(request, data)
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001172 >>> print(f.read().decode('utf-8'))
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001173
1174The following example uses an explicitly specified HTTP proxy, overriding
1175environment settings::
1176
1177 >>> import urllib.request
1178 >>> proxies = {'http': 'http://proxy.example.com:8080/'}
1179 >>> opener = urllib.request.FancyURLopener(proxies)
1180 >>> f = opener.open("http://www.python.org")
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001181 >>> f.read().decode('utf-8')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001182
1183The following example uses no proxies at all, overriding environment settings::
1184
1185 >>> import urllib.request
1186 >>> opener = urllib.request.FancyURLopener({})
1187 >>> f = opener.open("http://www.python.org/")
Senthil Kumaranb213ee32010-04-15 17:18:22 +00001188 >>> f.read().decode('utf-8')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001189
1190
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001191Legacy interface
1192----------------
1193
1194The following functions and classes are ported from the Python 2 module
1195``urllib`` (as opposed to ``urllib2``). They might become deprecated at
1196some point in the future.
1197
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001198.. function:: urlretrieve(url, filename=None, reporthook=None, data=None)
1199
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001200 Copy a network object denoted by a URL to a local file. If the URL
1201 points to a local file, the object will not be copied unless filename is supplied.
1202 Return a tuple ``(filename, headers)`` where *filename* is the
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001203 local file name under which the object can be found, and *headers* is whatever
1204 the :meth:`info` method of the object returned by :func:`urlopen` returned (for
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001205 a remote object). Exceptions are the same as for :func:`urlopen`.
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001206
1207 The second argument, if present, specifies the file location to copy to (if
1208 absent, the location will be a tempfile with a generated name). The third
1209 argument, if present, is a hook function that will be called once on
1210 establishment of the network connection and once after each block read
1211 thereafter. The hook will be passed three arguments; a count of blocks
1212 transferred so far, a block size in bytes, and the total size of the file. The
1213 third argument may be ``-1`` on older FTP servers which do not return a file
1214 size in response to a retrieval request.
1215
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001216 The following example illustrates the most common usage scenario::
1217
1218 >>> import urllib.request
1219 >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
1220 >>> html = open(local_filename)
1221 >>> html.close()
1222
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001223 If the *url* uses the :file:`http:` scheme identifier, the optional *data*
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001224 argument may be given to specify a ``POST`` request (normally the request
Senthil Kumaran87684e62012-03-14 18:08:13 -07001225 type is ``GET``). The *data* argument must be a bytes object in standard
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001226 :mimetype:`application/x-www-form-urlencoded` format; see the
1227 :func:`urlencode` function below.
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001228
1229 :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that
1230 the amount of data available was less than the expected amount (which is the
1231 size reported by a *Content-Length* header). This can occur, for example, when
1232 the download is interrupted.
1233
1234 The *Content-Length* is treated as a lower bound: if there's more data to read,
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001235 urlretrieve reads more data, but if less data is available, it raises the
1236 exception.
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001237
1238 You can still retrieve the downloaded data in this case, it is stored in the
1239 :attr:`content` attribute of the exception instance.
1240
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001241 If no *Content-Length* header was supplied, urlretrieve can not check the size
1242 of the data it has downloaded, and just returns it. In this case you just have
1243 to assume that the download was successful.
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001244
1245.. function:: urlcleanup()
1246
Senthil Kumarane24f96a2012-03-13 19:29:33 -07001247 Cleans up temporary files that may have been left behind by previous
1248 calls to :func:`urlretrieve`.
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001249
1250.. class:: URLopener(proxies=None, **x509)
1251
1252 Base class for opening and reading URLs. Unless you need to support opening
1253 objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
1254 you probably want to use :class:`FancyURLopener`.
1255
1256 By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header
1257 of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number.
1258 Applications can define their own :mailheader:`User-Agent` header by subclassing
1259 :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute
1260 :attr:`version` to an appropriate string value in the subclass definition.
1261
1262 The optional *proxies* parameter should be a dictionary mapping scheme names to
1263 proxy URLs, where an empty dictionary turns proxies off completely. Its default
1264 value is ``None``, in which case environmental proxy settings will be used if
1265 present, as discussed in the definition of :func:`urlopen`, above.
1266
1267 Additional keyword parameters, collected in *x509*, may be used for
1268 authentication of the client when using the :file:`https:` scheme. The keywords
1269 *key_file* and *cert_file* are supported to provide an SSL key and certificate;
1270 both are needed to support client authentication.
1271
Antoine Pitrou4272d6a2011-10-12 19:10:10 +02001272 :class:`URLopener` objects will raise an :exc:`OSError` exception if the server
Antoine Pitroub8eb9cb2010-12-15 19:07:26 +00001273 returns an error code.
1274
1275 .. method:: open(fullurl, data=None)
1276
1277 Open *fullurl* using the appropriate protocol. This method sets up cache and
1278 proxy information, then calls the appropriate open method with its input
1279 arguments. If the scheme is not recognized, :meth:`open_unknown` is called.
1280 The *data* argument has the same meaning as the *data* argument of
1281 :func:`urlopen`.
1282
1283
1284 .. method:: open_unknown(fullurl, data=None)
1285
1286 Overridable interface to open unknown URL types.
1287
1288
1289 .. method:: retrieve(url, filename=None, reporthook=None, data=None)
1290
1291 Retrieves the contents of *url* and places it in *filename*. The return value
1292 is a tuple consisting of a local filename and either a
1293 :class:`email.message.Message` object containing the response headers (for remote
1294 URLs) or ``None`` (for local URLs). The caller must then open and read the
1295 contents of *filename*. If *filename* is not given and the URL refers to a
1296 local file, the input filename is returned. If the URL is non-local and
1297 *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
1298 with a suffix that matches the suffix of the last path component of the input
1299 URL. If *reporthook* is given, it must be a function accepting three numeric
1300 parameters. It will be called after each chunk of data is read from the
1301 network. *reporthook* is ignored for local URLs.
1302
1303 If the *url* uses the :file:`http:` scheme identifier, the optional *data*
1304 argument may be given to specify a ``POST`` request (normally the request type
1305 is ``GET``). The *data* argument must in standard
1306 :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
1307 function below.
1308
1309
1310 .. attribute:: version
1311
1312 Variable that specifies the user agent of the opener object. To get
1313 :mod:`urllib` to tell servers that it is a particular user agent, set this in a
1314 subclass as a class variable or in the constructor before calling the base
1315 constructor.
1316
1317
1318.. class:: FancyURLopener(...)
1319
1320 :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling
1321 for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x
1322 response codes listed above, the :mailheader:`Location` header is used to fetch
1323 the actual URL. For 401 response codes (authentication required), basic HTTP
1324 authentication is performed. For the 30x response codes, recursion is bounded
1325 by the value of the *maxtries* attribute, which defaults to 10.
1326
1327 For all other response codes, the method :meth:`http_error_default` is called
1328 which you can override in subclasses to handle the error appropriately.
1329
1330 .. note::
1331
1332 According to the letter of :rfc:`2616`, 301 and 302 responses to POST requests
1333 must not be automatically redirected without confirmation by the user. In
1334 reality, browsers do allow automatic redirection of these responses, changing
1335 the POST to a GET, and :mod:`urllib` reproduces this behaviour.
1336
1337 The parameters to the constructor are the same as those for :class:`URLopener`.
1338
1339 .. note::
1340
1341 When performing basic authentication, a :class:`FancyURLopener` instance calls
1342 its :meth:`prompt_user_passwd` method. The default implementation asks the
1343 users for the required information on the controlling terminal. A subclass may
1344 override this method to support more appropriate behavior if needed.
1345
1346 The :class:`FancyURLopener` class offers one additional method that should be
1347 overloaded to provide the appropriate behavior:
1348
1349 .. method:: prompt_user_passwd(host, realm)
1350
1351 Return information needed to authenticate the user at the given host in the
1352 specified security realm. The return value should be a tuple, ``(user,
1353 password)``, which can be used for basic authentication.
1354
1355 The implementation prompts for this information on the terminal; an application
1356 should override this method to use an appropriate interaction model in the local
1357 environment.
1358
1359
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001360:mod:`urllib.request` Restrictions
1361----------------------------------
1362
1363 .. index::
1364 pair: HTTP; protocol
1365 pair: FTP; protocol
1366
Florent Xicluna83386da2011-10-28 22:03:55 +02001367* Currently, only the following protocols are supported: HTTP (versions 0.9 and
1368 1.0), FTP, and local files.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001369
Florent Xicluna305bb662011-10-28 22:14:41 +02001370* The caching feature of :func:`urlretrieve` has been disabled until someone
1371 finds the time to hack proper processing of Expiration time headers.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001372
1373* There should be a function to query whether a particular URL is in the cache.
1374
1375* For backward compatibility, if a URL appears to point to a local file but the
1376 file can't be opened, the URL is re-interpreted using the FTP protocol. This
1377 can sometimes cause confusing error messages.
1378
1379* The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily
1380 long delays while waiting for a network connection to be set up. This means
1381 that it is difficult to build an interactive Web client using these functions
1382 without using threads.
1383
1384 .. index::
1385 single: HTML
1386 pair: HTTP; protocol
1387
1388* The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data
1389 returned by the server. This may be binary data (such as an image), plain text
1390 or (for example) HTML. The HTTP protocol provides type information in the reply
1391 header, which can be inspected by looking at the :mailheader:`Content-Type`
1392 header. If the returned data is HTML, you can use the module
1393 :mod:`html.parser` to parse it.
1394
1395 .. index:: single: FTP
1396
1397* The code handling the FTP protocol cannot differentiate between a file and a
1398 directory. This can lead to unexpected behavior when attempting to read a URL
1399 that points to a file that is not accessible. If the URL ends in a ``/``, it is
1400 assumed to refer to a directory and will be handled accordingly. But if an
1401 attempt to read a file leads to a 550 error (meaning the URL cannot be found or
1402 is not accessible, often for permission reasons), then the path is treated as a
1403 directory in order to handle the case when a directory is specified by a URL but
1404 the trailing ``/`` has been left off. This can cause misleading results when
1405 you try to fetch a file whose read permissions make it inaccessible; the FTP
1406 code will try to read it, fail with a 550 error, and then perform a directory
1407 listing for the unreadable file. If fine-grained control is needed, consider
Éric Araujo09eb9802011-03-20 18:30:37 +01001408 using the :mod:`ftplib` module, subclassing :class:`FancyURLopener`, or changing
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001409 *_urlopener* to meet your needs.
1410
Georg Brandl0f7ede42008-06-23 11:23:31 +00001411
1412
Georg Brandl8175dae2010-11-29 14:53:15 +00001413:mod:`urllib.response` --- Response classes used by urllib
1414==========================================================
Georg Brandl0f7ede42008-06-23 11:23:31 +00001415
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001416.. module:: urllib.response
1417 :synopsis: Response classes used by urllib.
1418
1419The :mod:`urllib.response` module defines functions and classes which define a
Georg Brandl0f7ede42008-06-23 11:23:31 +00001420minimal file like interface, including ``read()`` and ``readline()``. The
Ezio Melottib9701422010-11-18 19:48:27 +00001421typical response object is an addinfourl instance, which defines an ``info()``
Georg Brandl0f7ede42008-06-23 11:23:31 +00001422method and that returns headers and a ``geturl()`` method that returns the url.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001423Functions defined by this module are used internally by the
1424:mod:`urllib.request` module.
1425