blob: 0b5f892a8846f5fa2a115f7835c5a77d5b0f811b [file] [log] [blame]
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001:mod:`urllib.request` --- extensible library for opening URLs
2=============================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00004.. module:: urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Next generation URL opening library.
6.. moduleauthor:: Jeremy Hylton <jhylton@users.sourceforge.net>
7.. sectionauthor:: Moshe Zadka <moshez@users.sourceforge.net>
8
9
Georg Brandl0f7ede42008-06-23 11:23:31 +000010The :mod:`urllib.request` module defines functions and classes which help in
11opening URLs (mostly HTTP) in a complex world --- basic and digest
12authentication, redirections, cookies and more.
Georg Brandl116aa622007-08-15 14:28:22 +000013
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000014The :mod:`urllib.request` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +000015
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
Georg Brandl7fe2c4a2008-12-05 07:32:56 +000026 :func:`urllib.parse.urlencode` function takes a mapping or sequence
27 of 2-tuples and returns a string in this format.
Georg Brandl116aa622007-08-15 14:28:22 +000028
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000029 The optional *timeout* parameter specifies a timeout in seconds for blocking
Georg Brandlf78e02b2008-06-10 17:40:04 +000030 operations like the connection attempt (if not specified, the global default
31 timeout setting will be used). This actually only works for HTTP, HTTPS,
32 FTP and FTPS connections.
Georg Brandl116aa622007-08-15 14:28:22 +000033
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000034 This function returns a file-like object with two additional methods from
35 the :mod:`urllib.response` module
Georg Brandl116aa622007-08-15 14:28:22 +000036
Christian Heimes292d3512008-02-03 16:51:08 +000037 * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to
38 determine if a redirect was followed
Georg Brandl116aa622007-08-15 14:28:22 +000039
Christian Heimes292d3512008-02-03 16:51:08 +000040 * :meth:`info` --- return the meta-information of the page, such as headers, in
Georg Brandl24420152008-05-26 16:32:26 +000041 the form of an ``http.client.HTTPMessage`` instance
Christian Heimes292d3512008-02-03 16:51:08 +000042 (see `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_)
Georg Brandl116aa622007-08-15 14:28:22 +000043
44 Raises :exc:`URLError` on errors.
45
46 Note that ``None`` may be returned if no handler handles the request (though the
47 default installed global :class:`OpenerDirector` uses :class:`UnknownHandler` to
48 ensure this never happens).
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000049 The urlopen function from the previous version, Python 2.6 and earlier, of
50 the module urllib has been discontinued as urlopen can return the
51 file-object as the previous. The proxy handling, which in earlier was passed
52 as a dict parameter to urlopen can be availed by the use of `ProxyHandler`
53 objects.
Georg Brandl116aa622007-08-15 14:28:22 +000054
Georg Brandl116aa622007-08-15 14:28:22 +000055
56.. function:: install_opener(opener)
57
58 Install an :class:`OpenerDirector` instance as the default global opener.
59 Installing an opener is only necessary if you want urlopen to use that opener;
60 otherwise, simply call :meth:`OpenerDirector.open` instead of :func:`urlopen`.
61 The code does not check for a real :class:`OpenerDirector`, and any class with
62 the appropriate interface will work.
63
64
65.. function:: build_opener([handler, ...])
66
67 Return an :class:`OpenerDirector` instance, which chains the handlers in the
68 order given. *handler*\s can be either instances of :class:`BaseHandler`, or
69 subclasses of :class:`BaseHandler` (in which case it must be possible to call
70 the constructor without any parameters). Instances of the following classes
71 will be in front of the *handler*\s, unless the *handler*\s contain them,
72 instances of them or subclasses of them: :class:`ProxyHandler`,
73 :class:`UnknownHandler`, :class:`HTTPHandler`, :class:`HTTPDefaultErrorHandler`,
74 :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
75 :class:`HTTPErrorProcessor`.
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077 If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported),
Georg Brandl116aa622007-08-15 14:28:22 +000078 :class:`HTTPSHandler` will also be added.
79
Georg Brandle6bcc912008-05-12 18:05:20 +000080 A :class:`BaseHandler` subclass may also change its :attr:`handler_order`
81 member variable to modify its position in the handlers list.
Georg Brandl116aa622007-08-15 14:28:22 +000082
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000083.. function:: urlretrieve(url[, filename[, reporthook[, data]]])
84
85 Copy a network object denoted by a URL to a local file, if necessary. If the URL
86 points to a local file, or a valid cached copy of the object exists, the object
87 is not copied. Return a tuple ``(filename, headers)`` where *filename* is the
88 local file name under which the object can be found, and *headers* is whatever
89 the :meth:`info` method of the object returned by :func:`urlopen` returned (for
90 a remote object, possibly cached). Exceptions are the same as for
91 :func:`urlopen`.
92
93 The second argument, if present, specifies the file location to copy to (if
94 absent, the location will be a tempfile with a generated name). The third
95 argument, if present, is a hook function that will be called once on
96 establishment of the network connection and once after each block read
97 thereafter. The hook will be passed three arguments; a count of blocks
98 transferred so far, a block size in bytes, and the total size of the file. The
99 third argument may be ``-1`` on older FTP servers which do not return a file
100 size in response to a retrieval request.
101
102 If the *url* uses the :file:`http:` scheme identifier, the optional *data*
103 argument may be given to specify a ``POST`` request (normally the request type
104 is ``GET``). The *data* argument must in standard
105 :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
106 function below.
107
108 :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that
109 the amount of data available was less than the expected amount (which is the
110 size reported by a *Content-Length* header). This can occur, for example, when
111 the download is interrupted.
112
113 The *Content-Length* is treated as a lower bound: if there's more data to read,
114 urlretrieve reads more data, but if less data is available, it raises the
115 exception.
116
117 You can still retrieve the downloaded data in this case, it is stored in the
118 :attr:`content` attribute of the exception instance.
119
120 If no *Content-Length* header was supplied, urlretrieve can not check the size
121 of the data it has downloaded, and just returns it. In this case you just have
122 to assume that the download was successful.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000125.. data:: _urlopener
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000127 The public functions :func:`urlopen` and :func:`urlretrieve` create an instance
128 of the :class:`FancyURLopener` class and use it to perform their requested
129 actions. To override this functionality, programmers can create a subclass of
130 :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that
131 class to the ``urllib._urlopener`` variable before calling the desired function.
132 For example, applications may want to specify a different
133 :mailheader:`User-Agent` header than :class:`URLopener` defines. This can be
134 accomplished with the following code::
Georg Brandl116aa622007-08-15 14:28:22 +0000135
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000136 import urllib.request
Christian Heimes292d3512008-02-03 16:51:08 +0000137
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000138 class AppURLopener(urllib.request.FancyURLopener):
139 version = "App/1.7"
140
141 urllib._urlopener = AppURLopener()
Christian Heimes292d3512008-02-03 16:51:08 +0000142
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000144.. function:: urlcleanup()
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000146 Clear the cache that may have been built up by previous calls to
147 :func:`urlretrieve`.
Christian Heimes292d3512008-02-03 16:51:08 +0000148
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000149.. function:: pathname2url(path)
Christian Heimes292d3512008-02-03 16:51:08 +0000150
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000151 Convert the pathname *path* from the local syntax for a path to the form used in
152 the path component of a URL. This does not produce a complete URL. The return
153 value will already be quoted using the :func:`quote` function.
Christian Heimes292d3512008-02-03 16:51:08 +0000154
155
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000156.. function:: url2pathname(path)
157
158 Convert the path component *path* from an encoded URL to the local syntax for a
159 path. This does not accept a complete URL. This function uses :func:`unquote`
160 to decode *path*.
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162The following classes are provided:
163
Christian Heimes292d3512008-02-03 16:51:08 +0000164.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable])
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166 This class is an abstraction of a URL request.
167
168 *url* should be a string containing a valid URL.
169
170 *data* may be a string specifying additional data to send to the server, or
171 ``None`` if no such data is needed. Currently HTTP requests are the only ones
172 that use *data*; the HTTP request will be a POST instead of a GET when the
173 *data* parameter is provided. *data* should be a buffer in the standard
174 :mimetype:`application/x-www-form-urlencoded` format. The
Georg Brandl7fe2c4a2008-12-05 07:32:56 +0000175 :func:`urllib.parse.urlencode` function takes a mapping or sequence
176 of 2-tuples and returns a string in this format.
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178 *headers* should be a dictionary, and will be treated as if :meth:`add_header`
Christian Heimes292d3512008-02-03 16:51:08 +0000179 was called with each key and value as arguments. This is often used to "spoof"
180 the ``User-Agent`` header, which is used by a browser to identify itself --
181 some HTTP servers only allow requests coming from common browsers as opposed
182 to scripts. For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0
Georg Brandl0f7ede42008-06-23 11:23:31 +0000183 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib`'s
Christian Heimes292d3512008-02-03 16:51:08 +0000184 default user agent string is ``"Python-urllib/2.6"`` (on Python 2.6).
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186 The final two arguments are only of interest for correct handling of third-party
187 HTTP cookies:
188
189 *origin_req_host* should be the request-host of the origin transaction, as
Georg Brandl24420152008-05-26 16:32:26 +0000190 defined by :rfc:`2965`. It defaults to ``http.cookiejar.request_host(self)``.
191 This is the host name or IP address of the original request that was
192 initiated by the user. For example, if the request is for an image in an
193 HTML document, this should be the request-host of the request for the page
194 containing the image.
Georg Brandl116aa622007-08-15 14:28:22 +0000195
196 *unverifiable* should indicate whether the request is unverifiable, as defined
197 by RFC 2965. It defaults to False. An unverifiable request is one whose URL
198 the user did not have the option to approve. For example, if the request is for
199 an image in an HTML document, and the user had no option to approve the
200 automatic fetching of the image, this should be true.
201
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000202.. class:: URLopener([proxies[, **x509]])
203
204 Base class for opening and reading URLs. Unless you need to support opening
205 objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
206 you probably want to use :class:`FancyURLopener`.
207
208 By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header
209 of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number.
210 Applications can define their own :mailheader:`User-Agent` header by subclassing
211 :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute
212 :attr:`version` to an appropriate string value in the subclass definition.
213
214 The optional *proxies* parameter should be a dictionary mapping scheme names to
215 proxy URLs, where an empty dictionary turns proxies off completely. Its default
216 value is ``None``, in which case environmental proxy settings will be used if
217 present, as discussed in the definition of :func:`urlopen`, above.
218
219 Additional keyword parameters, collected in *x509*, may be used for
220 authentication of the client when using the :file:`https:` scheme. The keywords
221 *key_file* and *cert_file* are supported to provide an SSL key and certificate;
222 both are needed to support client authentication.
223
224 :class:`URLopener` objects will raise an :exc:`IOError` exception if the server
225 returns an error code.
226
227 .. method:: open(fullurl[, data])
228
229 Open *fullurl* using the appropriate protocol. This method sets up cache and
230 proxy information, then calls the appropriate open method with its input
231 arguments. If the scheme is not recognized, :meth:`open_unknown` is called.
232 The *data* argument has the same meaning as the *data* argument of
233 :func:`urlopen`.
234
235
236 .. method:: open_unknown(fullurl[, data])
237
238 Overridable interface to open unknown URL types.
239
240
241 .. method:: retrieve(url[, filename[, reporthook[, data]]])
242
243 Retrieves the contents of *url* and places it in *filename*. The return value
244 is a tuple consisting of a local filename and either a
245 :class:`email.message.Message` object containing the response headers (for remote
246 URLs) or ``None`` (for local URLs). The caller must then open and read the
247 contents of *filename*. If *filename* is not given and the URL refers to a
248 local file, the input filename is returned. If the URL is non-local and
249 *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
250 with a suffix that matches the suffix of the last path component of the input
251 URL. If *reporthook* is given, it must be a function accepting three numeric
252 parameters. It will be called after each chunk of data is read from the
253 network. *reporthook* is ignored for local URLs.
254
255 If the *url* uses the :file:`http:` scheme identifier, the optional *data*
256 argument may be given to specify a ``POST`` request (normally the request type
257 is ``GET``). The *data* argument must in standard
258 :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
259 function below.
260
261
262 .. attribute:: version
263
264 Variable that specifies the user agent of the opener object. To get
265 :mod:`urllib` to tell servers that it is a particular user agent, set this in a
266 subclass as a class variable or in the constructor before calling the base
267 constructor.
268
269
270.. class:: FancyURLopener(...)
271
272 :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling
273 for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x
274 response codes listed above, the :mailheader:`Location` header is used to fetch
275 the actual URL. For 401 response codes (authentication required), basic HTTP
276 authentication is performed. For the 30x response codes, recursion is bounded
277 by the value of the *maxtries* attribute, which defaults to 10.
278
279 For all other response codes, the method :meth:`http_error_default` is called
280 which you can override in subclasses to handle the error appropriately.
281
282 .. note::
283
284 According to the letter of :rfc:`2616`, 301 and 302 responses to POST requests
285 must not be automatically redirected without confirmation by the user. In
286 reality, browsers do allow automatic redirection of these responses, changing
287 the POST to a GET, and :mod:`urllib` reproduces this behaviour.
288
289 The parameters to the constructor are the same as those for :class:`URLopener`.
290
291 .. note::
292
293 When performing basic authentication, a :class:`FancyURLopener` instance calls
294 its :meth:`prompt_user_passwd` method. The default implementation asks the
295 users for the required information on the controlling terminal. A subclass may
296 override this method to support more appropriate behavior if needed.
297
298 The :class:`FancyURLopener` class offers one additional method that should be
299 overloaded to provide the appropriate behavior:
300
301 .. method:: prompt_user_passwd(host, realm)
302
303 Return information needed to authenticate the user at the given host in the
304 specified security realm. The return value should be a tuple, ``(user,
305 password)``, which can be used for basic authentication.
306
307 The implementation prompts for this information on the terminal; an application
308 should override this method to use an appropriate interaction model in the local
309 environment.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. class:: OpenerDirector()
312
313 The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained
314 together. It manages the chaining of handlers, and recovery from errors.
315
316
317.. class:: BaseHandler()
318
319 This is the base class for all registered handlers --- and handles only the
320 simple mechanics of registration.
321
322
323.. class:: HTTPDefaultErrorHandler()
324
325 A class which defines a default handler for HTTP error responses; all responses
326 are turned into :exc:`HTTPError` exceptions.
327
328
329.. class:: HTTPRedirectHandler()
330
331 A class to handle redirections.
332
333
334.. class:: HTTPCookieProcessor([cookiejar])
335
336 A class to handle HTTP Cookies.
337
338
339.. class:: ProxyHandler([proxies])
340
341 Cause requests to go through a proxy. If *proxies* is given, it must be a
342 dictionary mapping protocol names to URLs of proxies. The default is to read the
343 list of proxies from the environment variables :envvar:`<protocol>_proxy`.
Christian Heimese25f35e2008-03-20 10:49:03 +0000344 To disable autodetected proxy pass an empty dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346
347.. class:: HTTPPasswordMgr()
348
349 Keep a database of ``(realm, uri) -> (user, password)`` mappings.
350
351
352.. class:: HTTPPasswordMgrWithDefaultRealm()
353
354 Keep a database of ``(realm, uri) -> (user, password)`` mappings. A realm of
355 ``None`` is considered a catch-all realm, which is searched if no other realm
356 fits.
357
358
359.. class:: AbstractBasicAuthHandler([password_mgr])
360
361 This is a mixin class that helps with HTTP authentication, both to the remote
362 host and to a proxy. *password_mgr*, if given, should be something that is
363 compatible with :class:`HTTPPasswordMgr`; refer to section
364 :ref:`http-password-mgr` for information on the interface that must be
365 supported.
366
367
368.. class:: HTTPBasicAuthHandler([password_mgr])
369
370 Handle authentication with the remote host. *password_mgr*, if given, should be
371 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
372 :ref:`http-password-mgr` for information on the interface that must be
373 supported.
374
375
376.. class:: ProxyBasicAuthHandler([password_mgr])
377
378 Handle authentication with the proxy. *password_mgr*, if given, should be
379 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
380 :ref:`http-password-mgr` for information on the interface that must be
381 supported.
382
383
384.. class:: AbstractDigestAuthHandler([password_mgr])
385
386 This is a mixin class that helps with HTTP authentication, both to the remote
387 host and to a proxy. *password_mgr*, if given, should be something that is
388 compatible with :class:`HTTPPasswordMgr`; refer to section
389 :ref:`http-password-mgr` for information on the interface that must be
390 supported.
391
392
393.. class:: HTTPDigestAuthHandler([password_mgr])
394
395 Handle authentication with the remote host. *password_mgr*, if given, should be
396 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
397 :ref:`http-password-mgr` for information on the interface that must be
398 supported.
399
400
401.. class:: ProxyDigestAuthHandler([password_mgr])
402
403 Handle authentication with the proxy. *password_mgr*, if given, should be
404 something that is compatible with :class:`HTTPPasswordMgr`; refer to section
405 :ref:`http-password-mgr` for information on the interface that must be
406 supported.
407
408
409.. class:: HTTPHandler()
410
411 A class to handle opening of HTTP URLs.
412
413
414.. class:: HTTPSHandler()
415
416 A class to handle opening of HTTPS URLs.
417
418
419.. class:: FileHandler()
420
421 Open local files.
422
423
424.. class:: FTPHandler()
425
426 Open FTP URLs.
427
428
429.. class:: CacheFTPHandler()
430
431 Open FTP URLs, keeping a cache of open FTP connections to minimize delays.
432
433
434.. class:: UnknownHandler()
435
436 A catch-all class to handle unknown URLs.
437
438
439.. _request-objects:
440
441Request Objects
442---------------
443
444The following methods describe all of :class:`Request`'s public interface, and
445so all must be overridden in subclasses.
446
447
448.. method:: Request.add_data(data)
449
450 Set the :class:`Request` data to *data*. This is ignored by all handlers except
451 HTTP handlers --- and there it should be a byte string, and will change the
452 request to be ``POST`` rather than ``GET``.
453
454
455.. method:: Request.get_method()
456
457 Return a string indicating the HTTP request method. This is only meaningful for
458 HTTP requests, and currently always returns ``'GET'`` or ``'POST'``.
459
460
461.. method:: Request.has_data()
462
463 Return whether the instance has a non-\ ``None`` data.
464
465
466.. method:: Request.get_data()
467
468 Return the instance's data.
469
470
471.. method:: Request.add_header(key, val)
472
473 Add another header to the request. Headers are currently ignored by all
474 handlers except HTTP handlers, where they are added to the list of headers sent
475 to the server. Note that there cannot be more than one header with the same
476 name, and later calls will overwrite previous calls in case the *key* collides.
477 Currently, this is no loss of HTTP functionality, since all headers which have
478 meaning when used more than once have a (header-specific) way of gaining the
479 same functionality using only one header.
480
481
482.. method:: Request.add_unredirected_header(key, header)
483
484 Add a header that will not be added to a redirected request.
485
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487.. method:: Request.has_header(header)
488
489 Return whether the instance has the named header (checks both regular and
490 unredirected).
491
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493.. method:: Request.get_full_url()
494
495 Return the URL given in the constructor.
496
497
498.. method:: Request.get_type()
499
500 Return the type of the URL --- also known as the scheme.
501
502
503.. method:: Request.get_host()
504
505 Return the host to which a connection will be made.
506
507
508.. method:: Request.get_selector()
509
510 Return the selector --- the part of the URL that is sent to the server.
511
512
513.. method:: Request.set_proxy(host, type)
514
515 Prepare the request by connecting to a proxy server. The *host* and *type* will
516 replace those of the instance, and the instance's selector will be the original
517 URL given in the constructor.
518
519
520.. method:: Request.get_origin_req_host()
521
522 Return the request-host of the origin transaction, as defined by :rfc:`2965`.
523 See the documentation for the :class:`Request` constructor.
524
525
526.. method:: Request.is_unverifiable()
527
528 Return whether the request is unverifiable, as defined by RFC 2965. See the
529 documentation for the :class:`Request` constructor.
530
531
532.. _opener-director-objects:
533
534OpenerDirector Objects
535----------------------
536
537:class:`OpenerDirector` instances have the following methods:
538
539
540.. method:: OpenerDirector.add_handler(handler)
541
542 *handler* should be an instance of :class:`BaseHandler`. The following methods
543 are searched, and added to the possible chains (note that HTTP errors are a
544 special case).
545
546 * :meth:`protocol_open` --- signal that the handler knows how to open *protocol*
547 URLs.
548
549 * :meth:`http_error_type` --- signal that the handler knows how to handle HTTP
550 errors with HTTP error code *type*.
551
552 * :meth:`protocol_error` --- signal that the handler knows how to handle errors
553 from (non-\ ``http``) *protocol*.
554
555 * :meth:`protocol_request` --- signal that the handler knows how to pre-process
556 *protocol* requests.
557
558 * :meth:`protocol_response` --- signal that the handler knows how to
559 post-process *protocol* responses.
560
561
562.. method:: OpenerDirector.open(url[, data][, timeout])
563
564 Open the given *url* (which can be a request object or a string), optionally
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000565 passing the given *data*. Arguments, return values and exceptions raised are
566 the same as those of :func:`urlopen` (which simply calls the :meth:`open`
567 method on the currently installed global :class:`OpenerDirector`). The
568 optional *timeout* parameter specifies a timeout in seconds for blocking
Georg Brandlf78e02b2008-06-10 17:40:04 +0000569 operations like the connection attempt (if not specified, the global default
570 timeout setting will be usedi). The timeout feature actually works only for
571 HTTP, HTTPS, FTP and FTPS connections).
Georg Brandl116aa622007-08-15 14:28:22 +0000572
Georg Brandl116aa622007-08-15 14:28:22 +0000573
574.. method:: OpenerDirector.error(proto[, arg[, ...]])
575
576 Handle an error of the given protocol. This will call the registered error
577 handlers for the given protocol with the given arguments (which are protocol
578 specific). The HTTP protocol is a special case which uses the HTTP response
579 code to determine the specific error handler; refer to the :meth:`http_error_\*`
580 methods of the handler classes.
581
582 Return values and exceptions raised are the same as those of :func:`urlopen`.
583
584OpenerDirector objects open URLs in three stages:
585
586The order in which these methods are called within each stage is determined by
587sorting the handler instances.
588
589#. Every handler with a method named like :meth:`protocol_request` has that
590 method called to pre-process the request.
591
592#. Handlers with a method named like :meth:`protocol_open` are called to handle
593 the request. This stage ends when a handler either returns a non-\ :const:`None`
594 value (ie. a response), or raises an exception (usually :exc:`URLError`).
595 Exceptions are allowed to propagate.
596
597 In fact, the above algorithm is first tried for methods named
598 :meth:`default_open`. If all such methods return :const:`None`, the algorithm
599 is repeated for methods named like :meth:`protocol_open`. If all such methods
600 return :const:`None`, the algorithm is repeated for methods named
601 :meth:`unknown_open`.
602
603 Note that the implementation of these methods may involve calls of the parent
604 :class:`OpenerDirector` instance's :meth:`.open` and :meth:`.error` methods.
605
606#. Every handler with a method named like :meth:`protocol_response` has that
607 method called to post-process the response.
608
609
610.. _base-handler-objects:
611
612BaseHandler Objects
613-------------------
614
615:class:`BaseHandler` objects provide a couple of methods that are directly
616useful, and others that are meant to be used by derived classes. These are
617intended for direct use:
618
619
620.. method:: BaseHandler.add_parent(director)
621
622 Add a director as parent.
623
624
625.. method:: BaseHandler.close()
626
627 Remove any parents.
628
629The following members and methods should only be used by classes derived from
630:class:`BaseHandler`.
631
632.. note::
633
634 The convention has been adopted that subclasses defining
635 :meth:`protocol_request` or :meth:`protocol_response` methods are named
636 :class:`\*Processor`; all others are named :class:`\*Handler`.
637
638
639.. attribute:: BaseHandler.parent
640
641 A valid :class:`OpenerDirector`, which can be used to open using a different
642 protocol, or handle errors.
643
644
645.. method:: BaseHandler.default_open(req)
646
647 This method is *not* defined in :class:`BaseHandler`, but subclasses should
648 define it if they want to catch all URLs.
649
650 This method, if implemented, will be called by the parent
651 :class:`OpenerDirector`. It should return a file-like object as described in
652 the return value of the :meth:`open` of :class:`OpenerDirector`, or ``None``.
653 It should raise :exc:`URLError`, unless a truly exceptional thing happens (for
654 example, :exc:`MemoryError` should not be mapped to :exc:`URLError`).
655
656 This method will be called before any protocol-specific open method.
657
658
659.. method:: BaseHandler.protocol_open(req)
660 :noindex:
661
662 This method is *not* defined in :class:`BaseHandler`, but subclasses should
663 define it if they want to handle URLs with the given protocol.
664
665 This method, if defined, will be called by the parent :class:`OpenerDirector`.
666 Return values should be the same as for :meth:`default_open`.
667
668
669.. method:: BaseHandler.unknown_open(req)
670
671 This method is *not* defined in :class:`BaseHandler`, but subclasses should
672 define it if they want to catch all URLs with no specific registered handler to
673 open it.
674
675 This method, if implemented, will be called by the :attr:`parent`
676 :class:`OpenerDirector`. Return values should be the same as for
677 :meth:`default_open`.
678
679
680.. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs)
681
682 This method is *not* defined in :class:`BaseHandler`, but subclasses should
683 override it if they intend to provide a catch-all for otherwise unhandled HTTP
684 errors. It will be called automatically by the :class:`OpenerDirector` getting
685 the error, and should not normally be called in other circumstances.
686
687 *req* will be a :class:`Request` object, *fp* will be a file-like object with
688 the HTTP error body, *code* will be the three-digit code of the error, *msg*
689 will be the user-visible explanation of the code and *hdrs* will be a mapping
690 object with the headers of the error.
691
692 Return values and exceptions raised should be the same as those of
693 :func:`urlopen`.
694
695
696.. method:: BaseHandler.http_error_nnn(req, fp, code, msg, hdrs)
697
698 *nnn* should be a three-digit HTTP error code. This method is also not defined
699 in :class:`BaseHandler`, but will be called, if it exists, on an instance of a
700 subclass, when an HTTP error with code *nnn* occurs.
701
702 Subclasses should override this method to handle specific HTTP errors.
703
704 Arguments, return values and exceptions raised should be the same as for
705 :meth:`http_error_default`.
706
707
708.. method:: BaseHandler.protocol_request(req)
709 :noindex:
710
711 This method is *not* defined in :class:`BaseHandler`, but subclasses should
712 define it if they want to pre-process requests of the given protocol.
713
714 This method, if defined, will be called by the parent :class:`OpenerDirector`.
715 *req* will be a :class:`Request` object. The return value should be a
716 :class:`Request` object.
717
718
719.. method:: BaseHandler.protocol_response(req, response)
720 :noindex:
721
722 This method is *not* defined in :class:`BaseHandler`, but subclasses should
723 define it if they want to post-process responses of the given protocol.
724
725 This method, if defined, will be called by the parent :class:`OpenerDirector`.
726 *req* will be a :class:`Request` object. *response* will be an object
727 implementing the same interface as the return value of :func:`urlopen`. The
728 return value should implement the same interface as the return value of
729 :func:`urlopen`.
730
731
732.. _http-redirect-handler:
733
734HTTPRedirectHandler Objects
735---------------------------
736
737.. note::
738
739 Some HTTP redirections require action from this module's client code. If this
740 is the case, :exc:`HTTPError` is raised. See :rfc:`2616` for details of the
741 precise meanings of the various redirection codes.
742
743
744.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs)
745
746 Return a :class:`Request` or ``None`` in response to a redirect. This is called
747 by the default implementations of the :meth:`http_error_30\*` methods when a
748 redirection is received from the server. If a redirection should take place,
749 return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the
750 redirect. Otherwise, raise :exc:`HTTPError` if no other handler should try to
751 handle this URL, or return ``None`` if you can't but another handler might.
752
753 .. note::
754
755 The default implementation of this method does not strictly follow :rfc:`2616`,
756 which says that 301 and 302 responses to ``POST`` requests must not be
757 automatically redirected without confirmation by the user. In reality, browsers
758 do allow automatic redirection of these responses, changing the POST to a
759 ``GET``, and the default implementation reproduces this behavior.
760
761
762.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)
763
764 Redirect to the ``Location:`` URL. This method is called by the parent
765 :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.
766
767
768.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)
769
770 The same as :meth:`http_error_301`, but called for the 'found' response.
771
772
773.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)
774
775 The same as :meth:`http_error_301`, but called for the 'see other' response.
776
777
778.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)
779
780 The same as :meth:`http_error_301`, but called for the 'temporary redirect'
781 response.
782
783
784.. _http-cookie-processor:
785
786HTTPCookieProcessor Objects
787---------------------------
788
Georg Brandl116aa622007-08-15 14:28:22 +0000789:class:`HTTPCookieProcessor` instances have one attribute:
790
Georg Brandl116aa622007-08-15 14:28:22 +0000791.. attribute:: HTTPCookieProcessor.cookiejar
792
Georg Brandl24420152008-05-26 16:32:26 +0000793 The :class:`http.cookiejar.CookieJar` in which cookies are stored.
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795
796.. _proxy-handler:
797
798ProxyHandler Objects
799--------------------
800
801
802.. method:: ProxyHandler.protocol_open(request)
803 :noindex:
804
805 The :class:`ProxyHandler` will have a method :meth:`protocol_open` for every
806 *protocol* which has a proxy in the *proxies* dictionary given in the
807 constructor. The method will modify requests to go through the proxy, by
808 calling ``request.set_proxy()``, and call the next handler in the chain to
809 actually execute the protocol.
810
811
812.. _http-password-mgr:
813
814HTTPPasswordMgr Objects
815-----------------------
816
817These methods are available on :class:`HTTPPasswordMgr` and
818:class:`HTTPPasswordMgrWithDefaultRealm` objects.
819
820
821.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd)
822
823 *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and
824 *passwd* must be strings. This causes ``(user, passwd)`` to be used as
825 authentication tokens when authentication for *realm* and a super-URI of any of
826 the given URIs is given.
827
828
829.. method:: HTTPPasswordMgr.find_user_password(realm, authuri)
830
831 Get user/password for given realm and URI, if any. This method will return
832 ``(None, None)`` if there is no matching user/password.
833
834 For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be
835 searched if the given *realm* has no matching user/password.
836
837
838.. _abstract-basic-auth-handler:
839
840AbstractBasicAuthHandler Objects
841--------------------------------
842
843
844.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
845
846 Handle an authentication request by getting a user/password pair, and re-trying
847 the request. *authreq* should be the name of the header where the information
848 about the realm is included in the request, *host* specifies the URL and path to
849 authenticate for, *req* should be the (failed) :class:`Request` object, and
850 *headers* should be the error headers.
851
852 *host* is either an authority (e.g. ``"python.org"``) or a URL containing an
853 authority component (e.g. ``"http://python.org/"``). In either case, the
854 authority must not contain a userinfo component (so, ``"python.org"`` and
855 ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not).
856
857
858.. _http-basic-auth-handler:
859
860HTTPBasicAuthHandler Objects
861----------------------------
862
863
864.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)
865
866 Retry the request with authentication information, if available.
867
868
869.. _proxy-basic-auth-handler:
870
871ProxyBasicAuthHandler Objects
872-----------------------------
873
874
875.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)
876
877 Retry the request with authentication information, if available.
878
879
880.. _abstract-digest-auth-handler:
881
882AbstractDigestAuthHandler Objects
883---------------------------------
884
885
886.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
887
888 *authreq* should be the name of the header where the information about the realm
889 is included in the request, *host* should be the host to authenticate to, *req*
890 should be the (failed) :class:`Request` object, and *headers* should be the
891 error headers.
892
893
894.. _http-digest-auth-handler:
895
896HTTPDigestAuthHandler Objects
897-----------------------------
898
899
900.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)
901
902 Retry the request with authentication information, if available.
903
904
905.. _proxy-digest-auth-handler:
906
907ProxyDigestAuthHandler Objects
908------------------------------
909
910
911.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)
912
913 Retry the request with authentication information, if available.
914
915
916.. _http-handler-objects:
917
918HTTPHandler Objects
919-------------------
920
921
922.. method:: HTTPHandler.http_open(req)
923
924 Send an HTTP request, which can be either GET or POST, depending on
925 ``req.has_data()``.
926
927
928.. _https-handler-objects:
929
930HTTPSHandler Objects
931--------------------
932
933
934.. method:: HTTPSHandler.https_open(req)
935
936 Send an HTTPS request, which can be either GET or POST, depending on
937 ``req.has_data()``.
938
939
940.. _file-handler-objects:
941
942FileHandler Objects
943-------------------
944
945
946.. method:: FileHandler.file_open(req)
947
948 Open the file locally, if there is no host name, or the host name is
949 ``'localhost'``. Change the protocol to ``ftp`` otherwise, and retry opening it
950 using :attr:`parent`.
951
952
953.. _ftp-handler-objects:
954
955FTPHandler Objects
956------------------
957
958
959.. method:: FTPHandler.ftp_open(req)
960
961 Open the FTP file indicated by *req*. The login is always done with empty
962 username and password.
963
964
965.. _cacheftp-handler-objects:
966
967CacheFTPHandler Objects
968-----------------------
969
970:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the
971following additional methods:
972
973
974.. method:: CacheFTPHandler.setTimeout(t)
975
976 Set timeout of connections to *t* seconds.
977
978
979.. method:: CacheFTPHandler.setMaxConns(m)
980
981 Set maximum number of cached connections to *m*.
982
983
984.. _unknown-handler-objects:
985
986UnknownHandler Objects
987----------------------
988
989
990.. method:: UnknownHandler.unknown_open()
991
992 Raise a :exc:`URLError` exception.
993
994
995.. _http-error-processor-objects:
996
997HTTPErrorProcessor Objects
998--------------------------
999
Georg Brandl116aa622007-08-15 14:28:22 +00001000.. method:: HTTPErrorProcessor.unknown_open()
1001
1002 Process HTTP error responses.
1003
1004 For 200 error codes, the response object is returned immediately.
1005
1006 For non-200 error codes, this simply passes the job on to the
1007 :meth:`protocol_error_code` handler methods, via :meth:`OpenerDirector.error`.
Georg Brandl0f7ede42008-06-23 11:23:31 +00001008 Eventually, :class:`HTTPDefaultErrorHandler` will raise an
Georg Brandl116aa622007-08-15 14:28:22 +00001009 :exc:`HTTPError` if no other handler handles the error.
1010
Georg Brandl0f7ede42008-06-23 11:23:31 +00001011
1012.. _urllib-request-examples:
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014Examples
1015--------
1016
1017This example gets the python.org main page and displays the first 100 bytes of
1018it::
1019
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001020 >>> import urllib.request
1021 >>> f = urllib.request.urlopen('http://www.python.org/')
Collin Winterc79461b2007-09-01 23:34:30 +00001022 >>> print(f.read(100))
Georg Brandl116aa622007-08-15 14:28:22 +00001023 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
1024 <?xml-stylesheet href="./css/ht2html
1025
1026Here we are sending a data-stream to the stdin of a CGI and reading the data it
1027returns to us. Note that this example will only work when the Python
1028installation supports SSL. ::
1029
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001030 >>> import urllib.request
1031 >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
Georg Brandl116aa622007-08-15 14:28:22 +00001032 ... data='This data is passed to stdin of the CGI')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001033 >>> f = urllib.request.urlopen(req)
Collin Winterc79461b2007-09-01 23:34:30 +00001034 >>> print(f.read())
Georg Brandl116aa622007-08-15 14:28:22 +00001035 Got Data: "This data is passed to stdin of the CGI"
1036
1037The code for the sample CGI used in the above example is::
1038
1039 #!/usr/bin/env python
1040 import sys
1041 data = sys.stdin.read()
Collin Winterc79461b2007-09-01 23:34:30 +00001042 print('Content-type: text-plain\n\nGot Data: "%s"' % data)
Georg Brandl116aa622007-08-15 14:28:22 +00001043
1044Use of Basic HTTP Authentication::
1045
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001046 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +00001047 # Create an OpenerDirector with support for Basic HTTP Authentication...
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001048 auth_handler = urllib.request.HTTPBasicAuthHandler()
Georg Brandl116aa622007-08-15 14:28:22 +00001049 auth_handler.add_password(realm='PDQ Application',
1050 uri='https://mahler:8092/site-updates.py',
1051 user='klem',
1052 passwd='kadidd!ehopper')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001053 opener = urllib.request.build_opener(auth_handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001054 # ...and install it globally so it can be used with urlopen.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001055 urllib.request.install_opener(opener)
1056 urllib.request.urlopen('http://www.example.com/login.html')
Georg Brandl116aa622007-08-15 14:28:22 +00001057
1058:func:`build_opener` provides many handlers by default, including a
1059:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment
1060variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme
1061involved. For example, the :envvar:`http_proxy` environment variable is read to
1062obtain the HTTP proxy's URL.
1063
1064This example replaces the default :class:`ProxyHandler` with one that uses
Georg Brandl2ee470f2008-07-16 12:55:28 +00001065programmatically-supplied proxy URLs, and adds proxy authorization support with
Georg Brandl116aa622007-08-15 14:28:22 +00001066:class:`ProxyBasicAuthHandler`. ::
1067
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001068 proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
1069 proxy_auth_handler = urllib.request.HTTPBasicAuthHandler()
Georg Brandl116aa622007-08-15 14:28:22 +00001070 proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
1071
1072 opener = build_opener(proxy_handler, proxy_auth_handler)
1073 # This time, rather than install the OpenerDirector, we use it directly:
1074 opener.open('http://www.example.com/login.html')
1075
1076Adding HTTP headers:
1077
1078Use the *headers* argument to the :class:`Request` constructor, or::
1079
Georg Brandl029986a2008-06-23 11:44:14 +00001080 import urllib.request
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001081 req = urllib.request.Request('http://www.example.com/')
Georg Brandl116aa622007-08-15 14:28:22 +00001082 req.add_header('Referer', 'http://www.python.org/')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001083 r = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +00001084
1085:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
1086every :class:`Request`. To change this::
1087
Georg Brandl029986a2008-06-23 11:44:14 +00001088 import urllib.request
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001089 opener = urllib.request.build_opener()
Georg Brandl116aa622007-08-15 14:28:22 +00001090 opener.addheaders = [('User-agent', 'Mozilla/5.0')]
1091 opener.open('http://www.example.com/')
1092
1093Also, remember that a few standard headers (:mailheader:`Content-Length`,
1094:mailheader:`Content-Type` and :mailheader:`Host`) are added when the
1095:class:`Request` is passed to :func:`urlopen` (or :meth:`OpenerDirector.open`).
1096
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001097.. _urllib-examples:
1098
1099Here is an example session that uses the ``GET`` method to retrieve a URL
1100containing parameters::
1101
1102 >>> import urllib.request
1103 >>> import urllib.parse
1104 >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
1105 >>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
1106 >>> print(f.read())
1107
1108The following example uses the ``POST`` method instead::
1109
1110 >>> import urllib.request
1111 >>> import urllib.parse
1112 >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
1113 >>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
1114 >>> print(f.read())
1115
1116The following example uses an explicitly specified HTTP proxy, overriding
1117environment settings::
1118
1119 >>> import urllib.request
1120 >>> proxies = {'http': 'http://proxy.example.com:8080/'}
1121 >>> opener = urllib.request.FancyURLopener(proxies)
1122 >>> f = opener.open("http://www.python.org")
1123 >>> f.read()
1124
1125The following example uses no proxies at all, overriding environment settings::
1126
1127 >>> import urllib.request
1128 >>> opener = urllib.request.FancyURLopener({})
1129 >>> f = opener.open("http://www.python.org/")
1130 >>> f.read()
1131
1132
1133:mod:`urllib.request` Restrictions
1134----------------------------------
1135
1136 .. index::
1137 pair: HTTP; protocol
1138 pair: FTP; protocol
1139
1140* Currently, only the following protocols are supported: HTTP, (versions 0.9 and
1141 1.0), FTP, and local files.
1142
1143* The caching feature of :func:`urlretrieve` has been disabled until I find the
1144 time to hack proper processing of Expiration time headers.
1145
1146* There should be a function to query whether a particular URL is in the cache.
1147
1148* For backward compatibility, if a URL appears to point to a local file but the
1149 file can't be opened, the URL is re-interpreted using the FTP protocol. This
1150 can sometimes cause confusing error messages.
1151
1152* The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily
1153 long delays while waiting for a network connection to be set up. This means
1154 that it is difficult to build an interactive Web client using these functions
1155 without using threads.
1156
1157 .. index::
1158 single: HTML
1159 pair: HTTP; protocol
1160
1161* The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data
1162 returned by the server. This may be binary data (such as an image), plain text
1163 or (for example) HTML. The HTTP protocol provides type information in the reply
1164 header, which can be inspected by looking at the :mailheader:`Content-Type`
1165 header. If the returned data is HTML, you can use the module
1166 :mod:`html.parser` to parse it.
1167
1168 .. index:: single: FTP
1169
1170* The code handling the FTP protocol cannot differentiate between a file and a
1171 directory. This can lead to unexpected behavior when attempting to read a URL
1172 that points to a file that is not accessible. If the URL ends in a ``/``, it is
1173 assumed to refer to a directory and will be handled accordingly. But if an
1174 attempt to read a file leads to a 550 error (meaning the URL cannot be found or
1175 is not accessible, often for permission reasons), then the path is treated as a
1176 directory in order to handle the case when a directory is specified by a URL but
1177 the trailing ``/`` has been left off. This can cause misleading results when
1178 you try to fetch a file whose read permissions make it inaccessible; the FTP
1179 code will try to read it, fail with a 550 error, and then perform a directory
1180 listing for the unreadable file. If fine-grained control is needed, consider
1181 using the :mod:`ftplib` module, subclassing :class:`FancyURLOpener`, or changing
1182 *_urlopener* to meet your needs.
1183
Georg Brandl0f7ede42008-06-23 11:23:31 +00001184
1185
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001186:mod:`urllib.response` --- Response classes used by urllib.
1187===========================================================
Georg Brandl0f7ede42008-06-23 11:23:31 +00001188
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001189.. module:: urllib.response
1190 :synopsis: Response classes used by urllib.
1191
1192The :mod:`urllib.response` module defines functions and classes which define a
Georg Brandl0f7ede42008-06-23 11:23:31 +00001193minimal file like interface, including ``read()`` and ``readline()``. The
1194typical response object is an addinfourl instance, which defines and ``info()``
1195method and that returns headers and a ``geturl()`` method that returns the url.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001196Functions defined by this module are used internally by the
1197:mod:`urllib.request` module.
1198