blob: 6a5b3ceae919d1c379062ed874e3739e3ffac266 [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
Georg Brandl2dd01042009-02-27 16:46:46 +000040 * :meth:`info` --- return the meta-information of the page, such as headers,
41 in the form of an ``http.client.HTTPMessage`` instance (see `Quick
42 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
Georg Brandl2dd01042009-02-27 16:46:46 +000046 Note that ``None`` may be returned if no handler handles the request (though
47 the default installed global :class:`OpenerDirector` uses
48 :class:`UnknownHandler` to ensure this never happens).
49
50 The legacy ``urllib.urlopen`` function from Python 2.6 and earlier has been
51 discontinued; :func:`urlopen` corresponds to the old ``urllib2.urlopen``.
52 Proxy handling, which was done by passing a dictionary parameter to
53 ``urllib.urlopen``, can be obtained by using :class:`ProxyHandler` 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
Georg Brandl9617a592009-02-13 10:40:43 +0000744.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)
Georg Brandl116aa622007-08-15 14:28:22 +0000745
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
Georg Brandl9617a592009-02-13 10:40:43 +0000750 redirect to *newurl*. Otherwise, raise :exc:`HTTPError` if no other handler
751 should try to handle this URL, or return ``None`` if you can't but another
752 handler might.
Georg Brandl116aa622007-08-15 14:28:22 +0000753
754 .. note::
755
756 The default implementation of this method does not strictly follow :rfc:`2616`,
757 which says that 301 and 302 responses to ``POST`` requests must not be
758 automatically redirected without confirmation by the user. In reality, browsers
759 do allow automatic redirection of these responses, changing the POST to a
760 ``GET``, and the default implementation reproduces this behavior.
761
762
763.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)
764
Georg Brandl9617a592009-02-13 10:40:43 +0000765 Redirect to the ``Location:`` or ``URI:`` URL. This method is called by the
766 parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768
769.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)
770
771 The same as :meth:`http_error_301`, but called for the 'found' response.
772
773
774.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)
775
776 The same as :meth:`http_error_301`, but called for the 'see other' response.
777
778
779.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)
780
781 The same as :meth:`http_error_301`, but called for the 'temporary redirect'
782 response.
783
784
785.. _http-cookie-processor:
786
787HTTPCookieProcessor Objects
788---------------------------
789
Georg Brandl116aa622007-08-15 14:28:22 +0000790:class:`HTTPCookieProcessor` instances have one attribute:
791
Georg Brandl116aa622007-08-15 14:28:22 +0000792.. attribute:: HTTPCookieProcessor.cookiejar
793
Georg Brandl24420152008-05-26 16:32:26 +0000794 The :class:`http.cookiejar.CookieJar` in which cookies are stored.
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796
797.. _proxy-handler:
798
799ProxyHandler Objects
800--------------------
801
802
803.. method:: ProxyHandler.protocol_open(request)
804 :noindex:
805
806 The :class:`ProxyHandler` will have a method :meth:`protocol_open` for every
807 *protocol* which has a proxy in the *proxies* dictionary given in the
808 constructor. The method will modify requests to go through the proxy, by
809 calling ``request.set_proxy()``, and call the next handler in the chain to
810 actually execute the protocol.
811
812
813.. _http-password-mgr:
814
815HTTPPasswordMgr Objects
816-----------------------
817
818These methods are available on :class:`HTTPPasswordMgr` and
819:class:`HTTPPasswordMgrWithDefaultRealm` objects.
820
821
822.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd)
823
824 *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and
825 *passwd* must be strings. This causes ``(user, passwd)`` to be used as
826 authentication tokens when authentication for *realm* and a super-URI of any of
827 the given URIs is given.
828
829
830.. method:: HTTPPasswordMgr.find_user_password(realm, authuri)
831
832 Get user/password for given realm and URI, if any. This method will return
833 ``(None, None)`` if there is no matching user/password.
834
835 For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be
836 searched if the given *realm* has no matching user/password.
837
838
839.. _abstract-basic-auth-handler:
840
841AbstractBasicAuthHandler Objects
842--------------------------------
843
844
845.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
846
847 Handle an authentication request by getting a user/password pair, and re-trying
848 the request. *authreq* should be the name of the header where the information
849 about the realm is included in the request, *host* specifies the URL and path to
850 authenticate for, *req* should be the (failed) :class:`Request` object, and
851 *headers* should be the error headers.
852
853 *host* is either an authority (e.g. ``"python.org"``) or a URL containing an
854 authority component (e.g. ``"http://python.org/"``). In either case, the
855 authority must not contain a userinfo component (so, ``"python.org"`` and
856 ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not).
857
858
859.. _http-basic-auth-handler:
860
861HTTPBasicAuthHandler Objects
862----------------------------
863
864
865.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)
866
867 Retry the request with authentication information, if available.
868
869
870.. _proxy-basic-auth-handler:
871
872ProxyBasicAuthHandler Objects
873-----------------------------
874
875
876.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)
877
878 Retry the request with authentication information, if available.
879
880
881.. _abstract-digest-auth-handler:
882
883AbstractDigestAuthHandler Objects
884---------------------------------
885
886
887.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)
888
889 *authreq* should be the name of the header where the information about the realm
890 is included in the request, *host* should be the host to authenticate to, *req*
891 should be the (failed) :class:`Request` object, and *headers* should be the
892 error headers.
893
894
895.. _http-digest-auth-handler:
896
897HTTPDigestAuthHandler Objects
898-----------------------------
899
900
901.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)
902
903 Retry the request with authentication information, if available.
904
905
906.. _proxy-digest-auth-handler:
907
908ProxyDigestAuthHandler Objects
909------------------------------
910
911
912.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)
913
914 Retry the request with authentication information, if available.
915
916
917.. _http-handler-objects:
918
919HTTPHandler Objects
920-------------------
921
922
923.. method:: HTTPHandler.http_open(req)
924
925 Send an HTTP request, which can be either GET or POST, depending on
926 ``req.has_data()``.
927
928
929.. _https-handler-objects:
930
931HTTPSHandler Objects
932--------------------
933
934
935.. method:: HTTPSHandler.https_open(req)
936
937 Send an HTTPS request, which can be either GET or POST, depending on
938 ``req.has_data()``.
939
940
941.. _file-handler-objects:
942
943FileHandler Objects
944-------------------
945
946
947.. method:: FileHandler.file_open(req)
948
949 Open the file locally, if there is no host name, or the host name is
950 ``'localhost'``. Change the protocol to ``ftp`` otherwise, and retry opening it
951 using :attr:`parent`.
952
953
954.. _ftp-handler-objects:
955
956FTPHandler Objects
957------------------
958
959
960.. method:: FTPHandler.ftp_open(req)
961
962 Open the FTP file indicated by *req*. The login is always done with empty
963 username and password.
964
965
966.. _cacheftp-handler-objects:
967
968CacheFTPHandler Objects
969-----------------------
970
971:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the
972following additional methods:
973
974
975.. method:: CacheFTPHandler.setTimeout(t)
976
977 Set timeout of connections to *t* seconds.
978
979
980.. method:: CacheFTPHandler.setMaxConns(m)
981
982 Set maximum number of cached connections to *m*.
983
984
985.. _unknown-handler-objects:
986
987UnknownHandler Objects
988----------------------
989
990
991.. method:: UnknownHandler.unknown_open()
992
993 Raise a :exc:`URLError` exception.
994
995
996.. _http-error-processor-objects:
997
998HTTPErrorProcessor Objects
999--------------------------
1000
Georg Brandl116aa622007-08-15 14:28:22 +00001001.. method:: HTTPErrorProcessor.unknown_open()
1002
1003 Process HTTP error responses.
1004
1005 For 200 error codes, the response object is returned immediately.
1006
1007 For non-200 error codes, this simply passes the job on to the
1008 :meth:`protocol_error_code` handler methods, via :meth:`OpenerDirector.error`.
Georg Brandl0f7ede42008-06-23 11:23:31 +00001009 Eventually, :class:`HTTPDefaultErrorHandler` will raise an
Georg Brandl116aa622007-08-15 14:28:22 +00001010 :exc:`HTTPError` if no other handler handles the error.
1011
Georg Brandl0f7ede42008-06-23 11:23:31 +00001012
1013.. _urllib-request-examples:
Georg Brandl116aa622007-08-15 14:28:22 +00001014
1015Examples
1016--------
1017
1018This example gets the python.org main page and displays the first 100 bytes of
1019it::
1020
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001021 >>> import urllib.request
1022 >>> f = urllib.request.urlopen('http://www.python.org/')
Collin Winterc79461b2007-09-01 23:34:30 +00001023 >>> print(f.read(100))
Georg Brandl116aa622007-08-15 14:28:22 +00001024 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
1025 <?xml-stylesheet href="./css/ht2html
1026
1027Here we are sending a data-stream to the stdin of a CGI and reading the data it
1028returns to us. Note that this example will only work when the Python
1029installation supports SSL. ::
1030
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001031 >>> import urllib.request
1032 >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
Georg Brandl116aa622007-08-15 14:28:22 +00001033 ... data='This data is passed to stdin of the CGI')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001034 >>> f = urllib.request.urlopen(req)
Collin Winterc79461b2007-09-01 23:34:30 +00001035 >>> print(f.read())
Georg Brandl116aa622007-08-15 14:28:22 +00001036 Got Data: "This data is passed to stdin of the CGI"
1037
1038The code for the sample CGI used in the above example is::
1039
1040 #!/usr/bin/env python
1041 import sys
1042 data = sys.stdin.read()
Collin Winterc79461b2007-09-01 23:34:30 +00001043 print('Content-type: text-plain\n\nGot Data: "%s"' % data)
Georg Brandl116aa622007-08-15 14:28:22 +00001044
1045Use of Basic HTTP Authentication::
1046
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001047 import urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +00001048 # Create an OpenerDirector with support for Basic HTTP Authentication...
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001049 auth_handler = urllib.request.HTTPBasicAuthHandler()
Georg Brandl116aa622007-08-15 14:28:22 +00001050 auth_handler.add_password(realm='PDQ Application',
1051 uri='https://mahler:8092/site-updates.py',
1052 user='klem',
1053 passwd='kadidd!ehopper')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001054 opener = urllib.request.build_opener(auth_handler)
Georg Brandl116aa622007-08-15 14:28:22 +00001055 # ...and install it globally so it can be used with urlopen.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001056 urllib.request.install_opener(opener)
1057 urllib.request.urlopen('http://www.example.com/login.html')
Georg Brandl116aa622007-08-15 14:28:22 +00001058
1059:func:`build_opener` provides many handlers by default, including a
1060:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment
1061variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme
1062involved. For example, the :envvar:`http_proxy` environment variable is read to
1063obtain the HTTP proxy's URL.
1064
1065This example replaces the default :class:`ProxyHandler` with one that uses
Georg Brandl2ee470f2008-07-16 12:55:28 +00001066programmatically-supplied proxy URLs, and adds proxy authorization support with
Georg Brandl116aa622007-08-15 14:28:22 +00001067:class:`ProxyBasicAuthHandler`. ::
1068
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001069 proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
1070 proxy_auth_handler = urllib.request.HTTPBasicAuthHandler()
Georg Brandl116aa622007-08-15 14:28:22 +00001071 proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
1072
1073 opener = build_opener(proxy_handler, proxy_auth_handler)
1074 # This time, rather than install the OpenerDirector, we use it directly:
1075 opener.open('http://www.example.com/login.html')
1076
1077Adding HTTP headers:
1078
1079Use the *headers* argument to the :class:`Request` constructor, or::
1080
Georg Brandl029986a2008-06-23 11:44:14 +00001081 import urllib.request
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001082 req = urllib.request.Request('http://www.example.com/')
Georg Brandl116aa622007-08-15 14:28:22 +00001083 req.add_header('Referer', 'http://www.python.org/')
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001084 r = urllib.request.urlopen(req)
Georg Brandl116aa622007-08-15 14:28:22 +00001085
1086:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
1087every :class:`Request`. To change this::
1088
Georg Brandl029986a2008-06-23 11:44:14 +00001089 import urllib.request
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001090 opener = urllib.request.build_opener()
Georg Brandl116aa622007-08-15 14:28:22 +00001091 opener.addheaders = [('User-agent', 'Mozilla/5.0')]
1092 opener.open('http://www.example.com/')
1093
1094Also, remember that a few standard headers (:mailheader:`Content-Length`,
1095:mailheader:`Content-Type` and :mailheader:`Host`) are added when the
1096:class:`Request` is passed to :func:`urlopen` (or :meth:`OpenerDirector.open`).
1097
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001098.. _urllib-examples:
1099
1100Here is an example session that uses the ``GET`` method to retrieve a URL
1101containing parameters::
1102
1103 >>> import urllib.request
1104 >>> import urllib.parse
1105 >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
1106 >>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
1107 >>> print(f.read())
1108
1109The following example uses the ``POST`` method instead::
1110
1111 >>> import urllib.request
1112 >>> import urllib.parse
1113 >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
1114 >>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
1115 >>> print(f.read())
1116
1117The following example uses an explicitly specified HTTP proxy, overriding
1118environment settings::
1119
1120 >>> import urllib.request
1121 >>> proxies = {'http': 'http://proxy.example.com:8080/'}
1122 >>> opener = urllib.request.FancyURLopener(proxies)
1123 >>> f = opener.open("http://www.python.org")
1124 >>> f.read()
1125
1126The following example uses no proxies at all, overriding environment settings::
1127
1128 >>> import urllib.request
1129 >>> opener = urllib.request.FancyURLopener({})
1130 >>> f = opener.open("http://www.python.org/")
1131 >>> f.read()
1132
1133
1134:mod:`urllib.request` Restrictions
1135----------------------------------
1136
1137 .. index::
1138 pair: HTTP; protocol
1139 pair: FTP; protocol
1140
1141* Currently, only the following protocols are supported: HTTP, (versions 0.9 and
1142 1.0), FTP, and local files.
1143
1144* The caching feature of :func:`urlretrieve` has been disabled until I find the
1145 time to hack proper processing of Expiration time headers.
1146
1147* There should be a function to query whether a particular URL is in the cache.
1148
1149* For backward compatibility, if a URL appears to point to a local file but the
1150 file can't be opened, the URL is re-interpreted using the FTP protocol. This
1151 can sometimes cause confusing error messages.
1152
1153* The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily
1154 long delays while waiting for a network connection to be set up. This means
1155 that it is difficult to build an interactive Web client using these functions
1156 without using threads.
1157
1158 .. index::
1159 single: HTML
1160 pair: HTTP; protocol
1161
1162* The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data
1163 returned by the server. This may be binary data (such as an image), plain text
1164 or (for example) HTML. The HTTP protocol provides type information in the reply
1165 header, which can be inspected by looking at the :mailheader:`Content-Type`
1166 header. If the returned data is HTML, you can use the module
1167 :mod:`html.parser` to parse it.
1168
1169 .. index:: single: FTP
1170
1171* The code handling the FTP protocol cannot differentiate between a file and a
1172 directory. This can lead to unexpected behavior when attempting to read a URL
1173 that points to a file that is not accessible. If the URL ends in a ``/``, it is
1174 assumed to refer to a directory and will be handled accordingly. But if an
1175 attempt to read a file leads to a 550 error (meaning the URL cannot be found or
1176 is not accessible, often for permission reasons), then the path is treated as a
1177 directory in order to handle the case when a directory is specified by a URL but
1178 the trailing ``/`` has been left off. This can cause misleading results when
1179 you try to fetch a file whose read permissions make it inaccessible; the FTP
1180 code will try to read it, fail with a 550 error, and then perform a directory
1181 listing for the unreadable file. If fine-grained control is needed, consider
1182 using the :mod:`ftplib` module, subclassing :class:`FancyURLOpener`, or changing
1183 *_urlopener* to meet your needs.
1184
Georg Brandl0f7ede42008-06-23 11:23:31 +00001185
1186
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001187:mod:`urllib.response` --- Response classes used by urllib.
1188===========================================================
Georg Brandl0f7ede42008-06-23 11:23:31 +00001189
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001190.. module:: urllib.response
1191 :synopsis: Response classes used by urllib.
1192
1193The :mod:`urllib.response` module defines functions and classes which define a
Georg Brandl0f7ede42008-06-23 11:23:31 +00001194minimal file like interface, including ``read()`` and ``readline()``. The
1195typical response object is an addinfourl instance, which defines and ``info()``
1196method and that returns headers and a ``geturl()`` method that returns the url.
Senthil Kumaranaca8fd72008-06-23 04:41:59 +00001197Functions defined by this module are used internally by the
1198:mod:`urllib.request` module.
1199