blob: 77dfb8fac8ec5c48dd02ca615b8d360530294284 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{urllib} ---
Fred Drakedfca4dc2000-08-25 05:13:42 +00002 Open arbitrary resources by URL}
Fred Drakeb91e9341998-07-23 17:59:49 +00003
Fred Drake38e5d272000-04-03 20:13:55 +00004\declaremodule{standard}{urllib}
5\modulesynopsis{Open an arbitrary network resource by URL (requires sockets).}
Fred Drakeb91e9341998-07-23 17:59:49 +00006
Guido van Rossuma8db1df1995-02-16 16:29:46 +00007\index{WWW}
Fred Drake8ee679f2001-07-14 02:50:55 +00008\index{World Wide Web}
Guido van Rossum61d34f41995-02-27 17:51:51 +00009\index{URL}
Guido van Rossuma8db1df1995-02-16 16:29:46 +000010
Guido van Rossum86751151995-02-28 17:14:32 +000011
Guido van Rossuma8db1df1995-02-16 16:29:46 +000012This module provides a high-level interface for fetching data across
Fred Drake8ee679f2001-07-14 02:50:55 +000013the World Wide Web. In particular, the \function{urlopen()} function
Fred Drake6ef871c1998-03-12 06:52:05 +000014is similar to the built-in function \function{open()}, but accepts
15Universal Resource Locators (URLs) instead of filenames. Some
16restrictions apply --- it can only open URLs for reading, and no seek
17operations are available.
Guido van Rossuma8db1df1995-02-16 16:29:46 +000018
Fred Drakef5eaa2e1997-12-15 22:13:50 +000019It defines the following public functions:
Guido van Rossuma8db1df1995-02-16 16:29:46 +000020
Fred Drake5ca3a082002-04-04 20:34:36 +000021\begin{funcdesc}{urlopen}{url\optional{, data\optional{, proxies}}}
Guido van Rossuma8db1df1995-02-16 16:29:46 +000022Open a network object denoted by a URL for reading. If the URL does
Fred Drake6ef871c1998-03-12 06:52:05 +000023not have a scheme identifier, or if it has \file{file:} as its scheme
Brett Cannona2f87372003-04-29 04:11:12 +000024identifier, this opens a local file (without universal newlines);
25otherwise it opens a socket to a server somewhere on the network. If
Georg Brandl124a4e52006-02-20 21:26:18 +000026the connection cannot be made
Brett Cannona2f87372003-04-29 04:11:12 +000027the \exception{IOError} exception is raised. If all went well, a
28file-like object is returned. This supports the following methods:
29\method{read()}, \method{readline()}, \method{readlines()}, \method{fileno()},
30\method{close()}, \method{info()} and \method{geturl()}. It also has
31proper support for the iterator protocol.
Fred Drake504ca682004-03-25 16:51:12 +000032One caveat: the \method{read()} method, if the size argument is
33omitted or negative, may not read until the end of the data stream;
34there is no good way to determine that the entire stream from a socket
35has been read in the general case.
Guido van Rossum0af2f631998-07-22 21:34:21 +000036
Fred Drake1ec71cb1999-02-22 22:42:14 +000037Except for the \method{info()} and \method{geturl()} methods,
Guido van Rossum0af2f631998-07-22 21:34:21 +000038these methods have the same interface as for
Fred Drake6ef871c1998-03-12 06:52:05 +000039file objects --- see section \ref{bltin-file-objects} in this
40manual. (It is not a built-in file object, however, so it can't be
Guido van Rossum470be141995-03-17 16:07:09 +000041used at those few places where a true built-in file object is
42required.)
Guido van Rossuma8db1df1995-02-16 16:29:46 +000043
Fred Drake6ef871c1998-03-12 06:52:05 +000044The \method{info()} method returns an instance of the class
Guido van Rossum954b9ad1998-09-28 14:08:29 +000045\class{mimetools.Message} containing meta-information associated
46with the URL. When the method is HTTP, these headers are those
47returned by the server at the head of the retrieved HTML page
48(including Content-Length and Content-Type). When the method is FTP,
49a Content-Length header will be present if (as is now usual) the
50server passed back a file length in response to the FTP retrieval
Guido van Rossum88e0b5b2001-08-23 13:38:15 +000051request. A Content-Type header will be present if the MIME type can
52be guessed. When the method is local-file, returned headers will include
Guido van Rossum954b9ad1998-09-28 14:08:29 +000053a Date representing the file's last-modified time, a Content-Length
54giving file size, and a Content-Type containing a guess at the file's
55type. See also the description of the
Fred Drake1ec71cb1999-02-22 22:42:14 +000056\refmodule{mimetools}\refstmodindex{mimetools} module.
57
58The \method{geturl()} method returns the real URL of the page. In
59some cases, the HTTP server redirects a client to another URL. The
60\function{urlopen()} function handles this transparently, but in some
61cases the caller needs to know which URL the client was redirected
62to. The \method{geturl()} method can be used to get at this
63redirected URL.
Guido van Rossum0af2f631998-07-22 21:34:21 +000064
65If the \var{url} uses the \file{http:} scheme identifier, the optional
66\var{data} argument may be given to specify a \code{POST} request
67(normally the request type is \code{GET}). The \var{data} argument
Brett Cannon317ad7a2003-04-24 02:31:14 +000068must be in standard \mimetype{application/x-www-form-urlencoded} format;
Guido van Rossum0af2f631998-07-22 21:34:21 +000069see the \function{urlencode()} function below.
70
Fred Drakeaef0e892000-08-31 17:23:35 +000071The \function{urlopen()} function works transparently with proxies
Fred Drake81c17352000-09-15 04:12:56 +000072which do not require authentication. In a \UNIX{} or Windows
Guido van Rossumd59da4b2007-05-22 18:11:13 +000073environment, set the \envvar{http_proxy}, or \envvar{ftp_proxy}
74environment variables to a URL that identifies
Fred Drakeaef0e892000-08-31 17:23:35 +000075the proxy server before starting the Python interpreter. For example
76(the \character{\%} is the command prompt):
Fred Drake38e5d272000-04-03 20:13:55 +000077
78\begin{verbatim}
79% http_proxy="http://www.someproxy.com:3128"
80% export http_proxy
81% python
82...
83\end{verbatim}
84
Brett Cannon317ad7a2003-04-24 02:31:14 +000085In a Windows environment, if no proxy environment variables are set,
Fred Draked2167032002-04-04 20:09:50 +000086proxy settings are obtained from the registry's Internet Settings
87section.
88
Fred Drake38e5d272000-04-03 20:13:55 +000089In a Macintosh environment, \function{urlopen()} will retrieve proxy
90information from Internet\index{Internet Config} Config.
91
Fred Drake5ca3a082002-04-04 20:34:36 +000092Alternatively, the optional \var{proxies} argument may be used to
93explicitly specify proxies. It must be a dictionary mapping scheme
94names to proxy URLs, where an empty dictionary causes no proxies to be
95used, and \code{None} (the default value) causes environmental proxy
96settings to be used as discussed above. For example:
97
98\begin{verbatim}
99# Use http://www.someproxy.com:3128 for http proxying
Andrew M. Kuchling597bd602005-06-01 15:26:24 +0000100proxies = {'http': 'http://www.someproxy.com:3128'}
Fred Drake5ca3a082002-04-04 20:34:36 +0000101filehandle = urllib.urlopen(some_url, proxies=proxies)
102# Don't use any proxies
103filehandle = urllib.urlopen(some_url, proxies={})
104# Use proxies from environment - both versions are equivalent
105filehandle = urllib.urlopen(some_url, proxies=None)
106filehandle = urllib.urlopen(some_url)
Brett Cannon317ad7a2003-04-24 02:31:14 +0000107\end{verbatim}
Fred Drake5ca3a082002-04-04 20:34:36 +0000108
Fred Draked2167032002-04-04 20:09:50 +0000109The \function{urlopen()} function does not support explicit proxy
110specification. If you need to override environmental proxy settings,
111use \class{URLopener}, or a subclass such as \class{FancyURLopener}.
112
Fred Drakeaef0e892000-08-31 17:23:35 +0000113Proxies which require authentication for use are not currently
114supported; this is considered an implementation limitation.
Fred Drakea2c25952002-04-04 20:58:02 +0000115
116\versionchanged[Added the \var{proxies} support]{2.3}
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000117\end{funcdesc}
118
Fred Drake51001332000-12-15 23:57:51 +0000119\begin{funcdesc}{urlretrieve}{url\optional{, filename\optional{,
120 reporthook\optional{, data}}}}
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000121Copy a network object denoted by a URL to a local file, if necessary.
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000122If the URL points to a local file, or a valid cached copy of the
Fred Drake6ef871c1998-03-12 06:52:05 +0000123object exists, the object is not copied. Return a tuple
124\code{(\var{filename}, \var{headers})} where \var{filename} is the
125local file name under which the object can be found, and \var{headers}
Brett Cannon317ad7a2003-04-24 02:31:14 +0000126is whatever the \method{info()} method of the object returned by
127\function{urlopen()} returned (for a remote object, possibly cached).
128Exceptions are the same as for \function{urlopen()}.
Guido van Rossum954b9ad1998-09-28 14:08:29 +0000129
130The second argument, if present, specifies the file location to copy
131to (if absent, the location will be a tempfile with a generated name).
132The third argument, if present, is a hook function that will be called
133once on establishment of the network connection and once after each
134block read thereafter. The hook will be passed three arguments; a
135count of blocks transferred so far, a block size in bytes, and the
Fred Drake09b29571998-10-01 20:43:13 +0000136total size of the file. The third argument may be \code{-1} on older
Brett Cannon317ad7a2003-04-24 02:31:14 +0000137FTP servers which do not return a file size in response to a retrieval
Guido van Rossum954b9ad1998-09-28 14:08:29 +0000138request.
Fred Drake9fa4d612000-08-24 01:06:40 +0000139
140If the \var{url} uses the \file{http:} scheme identifier, the optional
141\var{data} argument may be given to specify a \code{POST} request
142(normally the request type is \code{GET}). The \var{data} argument
Fred Drake51001332000-12-15 23:57:51 +0000143must in standard \mimetype{application/x-www-form-urlencoded} format;
Fred Drake9fa4d612000-08-24 01:06:40 +0000144see the \function{urlencode()} function below.
Georg Brandlb9256022005-08-24 18:46:39 +0000145
146\versionchanged[
147\function{urlretrieve()} will raise \exception{ContentTooShortError}
148when it detects that the amount of data available
149was less than the expected amount (which is the size reported by a
150\var{Content-Length} header). This can occur, for example, when the
151download is interrupted.
152
153The \var{Content-Length} is treated as a lower bound: if there's more data
154to read, urlretrieve reads more data, but if less data is available,
155it raises the exception.
156
157You can still retrieve the downloaded data in this case, it is stored
158in the \member{content} attribute of the exception instance.
159
160If no \var{Content-Length} header was supplied, urlretrieve can
161not check the size of the data it has downloaded, and just returns it.
162In this case you just have to assume that the download was successful]{2.5}
163
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000164\end{funcdesc}
165
Fred Drake88f015d2002-10-22 21:58:06 +0000166\begin{datadesc}{_urlopener}
167The public functions \function{urlopen()} and
168\function{urlretrieve()} create an instance of the
169\class{FancyURLopener} class and use it to perform their requested
170actions. To override this functionality, programmers can create a
171subclass of \class{URLopener} or \class{FancyURLopener}, then assign
Fred Drake4f4dbef2003-08-27 15:11:40 +0000172an instance of that class to the
Fred Drake88f015d2002-10-22 21:58:06 +0000173\code{urllib._urlopener} variable before calling the desired function.
174For example, applications may want to specify a different
175\mailheader{User-Agent} header than \class{URLopener} defines. This
176can be accomplished with the following code:
177
178\begin{verbatim}
179import urllib
180
181class AppURLopener(urllib.FancyURLopener):
Skip Montanaro8e97fbf2005-03-09 02:57:26 +0000182 version = "App/1.7"
Fred Drake88f015d2002-10-22 21:58:06 +0000183
184urllib._urlopener = AppURLopener()
185\end{verbatim}
186\end{datadesc}
187
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000188\begin{funcdesc}{urlcleanup}{}
189Clear the cache that may have been built up by previous calls to
Fred Drake6ef871c1998-03-12 06:52:05 +0000190\function{urlretrieve()}.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000191\end{funcdesc}
192
Guido van Rossum0af2f631998-07-22 21:34:21 +0000193\begin{funcdesc}{quote}{string\optional{, safe}}
Fred Drake6ef871c1998-03-12 06:52:05 +0000194Replace special characters in \var{string} using the \samp{\%xx} escape.
Brett Cannon317ad7a2003-04-24 02:31:14 +0000195Letters, digits, and the characters \character{_.-} are never quoted.
Guido van Rossum0af2f631998-07-22 21:34:21 +0000196The optional \var{safe} parameter specifies additional characters
Guido van Rossum61d34f41995-02-27 17:51:51 +0000197that should not be quoted --- its default value is \code{'/'}.
198
Fred Drake10853c92000-07-28 13:51:27 +0000199Example: \code{quote('/\~{}connolly/')} yields \code{'/\%7econnolly/'}.
Guido van Rossum8d40c841996-12-13 14:48:47 +0000200\end{funcdesc}
201
Guido van Rossum0af2f631998-07-22 21:34:21 +0000202\begin{funcdesc}{quote_plus}{string\optional{, safe}}
Fred Drake6ef871c1998-03-12 06:52:05 +0000203Like \function{quote()}, but also replaces spaces by plus signs, as
Guido van Rossum0af2f631998-07-22 21:34:21 +0000204required for quoting HTML form values. Plus signs in the original
Brett Cannon317ad7a2003-04-24 02:31:14 +0000205string are escaped unless they are included in \var{safe}. It also
206does not have \var{safe} default to \code{'/'}.
Guido van Rossum61d34f41995-02-27 17:51:51 +0000207\end{funcdesc}
208
209\begin{funcdesc}{unquote}{string}
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000210Replace \samp{\%xx} escapes by their single-character equivalent.
Guido van Rossum61d34f41995-02-27 17:51:51 +0000211
Fred Drake10853c92000-07-28 13:51:27 +0000212Example: \code{unquote('/\%7Econnolly/')} yields \code{'/\~{}connolly/'}.
Guido van Rossum61d34f41995-02-27 17:51:51 +0000213\end{funcdesc}
214
Guido van Rossum8d40c841996-12-13 14:48:47 +0000215\begin{funcdesc}{unquote_plus}{string}
Fred Drake6ef871c1998-03-12 06:52:05 +0000216Like \function{unquote()}, but also replaces plus signs by spaces, as
Guido van Rossum8d40c841996-12-13 14:48:47 +0000217required for unquoting HTML form values.
218\end{funcdesc}
219
Skip Montanaro4fda21b2001-01-28 21:18:16 +0000220\begin{funcdesc}{urlencode}{query\optional{, doseq}}
221Convert a mapping object or a sequence of two-element tuples to a
Brett Cannon317ad7a2003-04-24 02:31:14 +0000222``url-encoded'' string, suitable to pass to
Guido van Rossum0af2f631998-07-22 21:34:21 +0000223\function{urlopen()} above as the optional \var{data} argument. This
224is useful to pass a dictionary of form fields to a \code{POST}
Fred Drake09b29571998-10-01 20:43:13 +0000225request. The resulting string is a series of
226\code{\var{key}=\var{value}} pairs separated by \character{\&}
227characters, where both \var{key} and \var{value} are quoted using
Skip Montanaroeda28442001-01-24 06:36:06 +0000228\function{quote_plus()} above. If the optional parameter \var{doseq} is
229present and evaluates to true, individual \code{\var{key}=\var{value}} pairs
230are generated for each element of the sequence.
Skip Montanaro4fda21b2001-01-28 21:18:16 +0000231When a sequence of two-element tuples is used as the \var{query} argument,
232the first element of each tuple is a key and the second is a value. The
233order of parameters in the encoded string will match the order of parameter
234tuples in the sequence.
Fred Draked859d472003-04-24 16:22:47 +0000235The \refmodule{cgi} module provides the functions
236\function{parse_qs()} and \function{parse_qsl()} which are used to
237parse query strings into Python data structures.
Guido van Rossum0af2f631998-07-22 21:34:21 +0000238\end{funcdesc}
239
Fred Drake88f015d2002-10-22 21:58:06 +0000240\begin{funcdesc}{pathname2url}{path}
241Convert the pathname \var{path} from the local syntax for a path to
242the form used in the path component of a URL. This does not produce a
243complete URL. The return value will already be quoted using the
244\function{quote()} function.
245\end{funcdesc}
Fred Drake38e5d272000-04-03 20:13:55 +0000246
Fred Drake88f015d2002-10-22 21:58:06 +0000247\begin{funcdesc}{url2pathname}{path}
248Convert the path component \var{path} from an encoded URL to the local
249syntax for a path. This does not accept a complete URL. This
250function uses \function{unquote()} to decode \var{path}.
251\end{funcdesc}
Fred Drake38e5d272000-04-03 20:13:55 +0000252
253\begin{classdesc}{URLopener}{\optional{proxies\optional{, **x509}}}
254Base class for opening and reading URLs. Unless you need to support
255opening objects using schemes other than \file{http:}, \file{ftp:},
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000256or \file{file:}, you probably want to use
Fred Drake38e5d272000-04-03 20:13:55 +0000257\class{FancyURLopener}.
258
259By default, the \class{URLopener} class sends a
Fred Draked86038d2001-08-03 18:39:36 +0000260\mailheader{User-Agent} header of \samp{urllib/\var{VVV}}, where
Fred Drake38e5d272000-04-03 20:13:55 +0000261\var{VVV} is the \module{urllib} version number. Applications can
Fred Draked86038d2001-08-03 18:39:36 +0000262define their own \mailheader{User-Agent} header by subclassing
Skip Montanaro8e97fbf2005-03-09 02:57:26 +0000263\class{URLopener} or \class{FancyURLopener} and setting the class
264attribute \member{version} to an appropriate string value in the
265subclass definition.
Fred Drake38e5d272000-04-03 20:13:55 +0000266
Fred Draked2167032002-04-04 20:09:50 +0000267The optional \var{proxies} parameter should be a dictionary mapping
268scheme names to proxy URLs, where an empty dictionary turns proxies
Fred Drake5ca3a082002-04-04 20:34:36 +0000269off completely. Its default value is \code{None}, in which case
Fred Draked2167032002-04-04 20:09:50 +0000270environmental proxy settings will be used if present, as discussed in
271the definition of \function{urlopen()}, above.
272
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000273Additional keyword parameters, collected in \var{x509}, may be used for
274authentication of the client when using the \file{https:} scheme. The keywords
275\var{key_file} and \var{cert_file} are supported to provide an
276SSL key and certificate; both are needed to support client authentication.
Georg Brandl124a4e52006-02-20 21:26:18 +0000277
278\class{URLopener} objects will raise an \exception{IOError} exception
279if the server returns an error code.
Fred Drake38e5d272000-04-03 20:13:55 +0000280\end{classdesc}
281
282\begin{classdesc}{FancyURLopener}{...}
283\class{FancyURLopener} subclasses \class{URLopener} providing default
Martin v. Löwis162f0812003-07-12 07:33:32 +0000284handling for the following HTTP response codes: 301, 302, 303, 307 and
285401. For the 30x response codes listed above, the
286\mailheader{Location} header is used to fetch the actual URL. For 401
287response codes (authentication required), basic HTTP authentication is
288performed. For the 30x response codes, recursion is bounded by the
289value of the \var{maxtries} attribute, which defaults to 10.
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000290
Georg Brandl124a4e52006-02-20 21:26:18 +0000291For all other response codes, the method \method{http_error_default()}
292is called which you can override in subclasses to handle the error
293appropriately.
294
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000295\note{According to the letter of \rfc{2616}, 301 and 302 responses to
296 POST requests must not be automatically redirected without
297 confirmation by the user. In reality, browsers do allow automatic
298 redirection of these responses, changing the POST to a GET, and
299 \module{urllib} reproduces this behaviour.}
Fred Drake38e5d272000-04-03 20:13:55 +0000300
301The parameters to the constructor are the same as those for
302\class{URLopener}.
Fred Drake47f11ce2001-04-12 20:26:49 +0000303
Fred Drake0aa811c2001-10-20 04:24:09 +0000304\note{When performing basic authentication, a
Fred Drake47f11ce2001-04-12 20:26:49 +0000305\class{FancyURLopener} instance calls its
306\method{prompt_user_passwd()} method. The default implementation asks
307the users for the required information on the controlling terminal. A
308subclass may override this method to support more appropriate behavior
Fred Drake0aa811c2001-10-20 04:24:09 +0000309if needed.}
Fred Drake38e5d272000-04-03 20:13:55 +0000310\end{classdesc}
311
Georg Brandlb9256022005-08-24 18:46:39 +0000312\begin{excclassdesc}{ContentTooShortError}{msg\optional{, content}}
313This exception is raised when the \function{urlretrieve()} function
314detects that the amount of the downloaded data is less than the
315expected amount (given by the \var{Content-Length} header). The
316\member{content} attribute stores the downloaded (and supposedly
317truncated) data.
318\versionadded{2.5}
319\end{excclassdesc}
320
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000321Restrictions:
322
323\begin{itemize}
324
325\item
326Currently, only the following protocols are supported: HTTP, (versions
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003270.9 and 1.0), FTP, and local files.
Fred Drake6ef871c1998-03-12 06:52:05 +0000328\indexii{HTTP}{protocol}
Fred Drake6ef871c1998-03-12 06:52:05 +0000329\indexii{FTP}{protocol}
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000330
331\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000332The caching feature of \function{urlretrieve()} has been disabled
333until I find the time to hack proper processing of Expiration time
334headers.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000335
336\item
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000337There should be a function to query whether a particular URL is in
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000338the cache.
339
340\item
341For backward compatibility, if a URL appears to point to a local file
342but the file can't be opened, the URL is re-interpreted using the FTP
343protocol. This can sometimes cause confusing error messages.
344
345\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000346The \function{urlopen()} and \function{urlretrieve()} functions can
347cause arbitrarily long delays while waiting for a network connection
348to be set up. This means that it is difficult to build an interactive
Fred Drake8ee679f2001-07-14 02:50:55 +0000349Web client using these functions without using threads.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000350
351\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000352The data returned by \function{urlopen()} or \function{urlretrieve()}
353is the raw data returned by the server. This may be binary data
Georg Brandlb9256022005-08-24 18:46:39 +0000354(such as an image), plain text or (for example) HTML\index{HTML}. The
Fred Drake1ec71cb1999-02-22 22:42:14 +0000355HTTP\indexii{HTTP}{protocol} protocol provides type information in the
356reply header, which can be inspected by looking at the
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000357\mailheader{Content-Type} header. If the
Fred Draked86038d2001-08-03 18:39:36 +0000358returned data is HTML, you can use the module
359\refmodule{htmllib}\refstmodindex{htmllib} to parse it.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000360
361\item
Andrew M. Kuchling2a510ce2004-07-13 14:03:31 +0000362The code handling the FTP\index{FTP} protocol cannot differentiate
363between a file and a directory. This can lead to unexpected behavior
364when attempting to read a URL that points to a file that is not
365accessible. If the URL ends in a \code{/}, it is assumed to refer to
366a directory and will be handled accordingly. But if an attempt to
367read a file leads to a 550 error (meaning the URL cannot be found or
368is not accessible, often for permission reasons), then the path is
369treated as a directory in order to handle the case when a directory is
370specified by a URL but the trailing \code{/} has been left off. This can
371cause misleading results when you try to fetch a file whose read
372permissions make it inaccessible; the FTP code will try to read it,
373fail with a 550 error, and then perform a directory listing for the
374unreadable file. If fine-grained control is needed, consider using the
375\module{ftplib} module, subclassing \class{FancyURLOpener}, or changing
376\var{_urlopener} to meet your needs.
Brett Cannon71868e72004-07-13 00:48:42 +0000377
378\item
Fred Drake81c17352000-09-15 04:12:56 +0000379This module does not support the use of proxies which require
380authentication. This may be implemented in the future.
381
382\item
Fred Drake6ef871c1998-03-12 06:52:05 +0000383Although the \module{urllib} module contains (undocumented) routines
384to parse and unparse URL strings, the recommended interface for URL
Fred Drake1ec71cb1999-02-22 22:42:14 +0000385manipulation is in module \refmodule{urlparse}\refstmodindex{urlparse}.
Guido van Rossuma8db1df1995-02-16 16:29:46 +0000386
387\end{itemize}
Fred Drake38e5d272000-04-03 20:13:55 +0000388
389
390\subsection{URLopener Objects \label{urlopener-objs}}
391\sectionauthor{Skip Montanaro}{skip@mojam.com}
392
393\class{URLopener} and \class{FancyURLopener} objects have the
Fred Drakedfca4dc2000-08-25 05:13:42 +0000394following attributes.
Fred Drake38e5d272000-04-03 20:13:55 +0000395
Fred Drakedfca4dc2000-08-25 05:13:42 +0000396\begin{methoddesc}[URLopener]{open}{fullurl\optional{, data}}
Brett Cannon317ad7a2003-04-24 02:31:14 +0000397Open \var{fullurl} using the appropriate protocol. This method sets
Fred Drake38e5d272000-04-03 20:13:55 +0000398up cache and proxy information, then calls the appropriate open method with
399its input arguments. If the scheme is not recognized,
Brett Cannon317ad7a2003-04-24 02:31:14 +0000400\method{open_unknown()} is called. The \var{data} argument
Fred Drake38e5d272000-04-03 20:13:55 +0000401has the same meaning as the \var{data} argument of \function{urlopen()}.
402\end{methoddesc}
403
Fred Drakedfca4dc2000-08-25 05:13:42 +0000404\begin{methoddesc}[URLopener]{open_unknown}{fullurl\optional{, data}}
Fred Drake38e5d272000-04-03 20:13:55 +0000405Overridable interface to open unknown URL types.
406\end{methoddesc}
407
Fred Drakedfca4dc2000-08-25 05:13:42 +0000408\begin{methoddesc}[URLopener]{retrieve}{url\optional{,
409 filename\optional{,
410 reporthook\optional{, data}}}}
Fred Drake38e5d272000-04-03 20:13:55 +0000411Retrieves the contents of \var{url} and places it in \var{filename}. The
412return value is a tuple consisting of a local filename and either a
413\class{mimetools.Message} object containing the response headers (for remote
Fred Drake5ca3a082002-04-04 20:34:36 +0000414URLs) or \code{None} (for local URLs). The caller must then open and read the
Fred Drake38e5d272000-04-03 20:13:55 +0000415contents of \var{filename}. If \var{filename} is not given and the URL
416refers to a local file, the input filename is returned. If the URL is
417non-local and \var{filename} is not given, the filename is the output of
418\function{tempfile.mktemp()} with a suffix that matches the suffix of the last
419path component of the input URL. If \var{reporthook} is given, it must be
420a function accepting three numeric parameters. It will be called after each
421chunk of data is read from the network. \var{reporthook} is ignored for
422local URLs.
Fred Drake9fa4d612000-08-24 01:06:40 +0000423
424If the \var{url} uses the \file{http:} scheme identifier, the optional
425\var{data} argument may be given to specify a \code{POST} request
426(normally the request type is \code{GET}). The \var{data} argument
Fred Drake51001332000-12-15 23:57:51 +0000427must in standard \mimetype{application/x-www-form-urlencoded} format;
Fred Drake9fa4d612000-08-24 01:06:40 +0000428see the \function{urlencode()} function below.
Fred Drake38e5d272000-04-03 20:13:55 +0000429\end{methoddesc}
430
Fred Drakedfca4dc2000-08-25 05:13:42 +0000431\begin{memberdesc}[URLopener]{version}
432Variable that specifies the user agent of the opener object. To get
433\refmodule{urllib} to tell servers that it is a particular user agent,
434set this in a subclass as a class variable or in the constructor
435before calling the base constructor.
436\end{memberdesc}
437
Fred Drake47f11ce2001-04-12 20:26:49 +0000438The \class{FancyURLopener} class offers one additional method that
439should be overloaded to provide the appropriate behavior:
440
441\begin{methoddesc}[FancyURLopener]{prompt_user_passwd}{host, realm}
442Return information needed to authenticate the user at the given host
443in the specified security realm. The return value should be a tuple,
444\code{(\var{user}, \var{password})}, which can be used for basic
445authentication.
446
447The implementation prompts for this information on the terminal; an
448application should override this method to use an appropriate
449interaction model in the local environment.
450\end{methoddesc}
451
Fred Drake38e5d272000-04-03 20:13:55 +0000452
453\subsection{Examples}
454\nodename{Urllib Examples}
455
456Here is an example session that uses the \samp{GET} method to retrieve
457a URL containing parameters:
458
459\begin{verbatim}
460>>> import urllib
461>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
462>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
463>>> print f.read()
464\end{verbatim}
465
466The following example uses the \samp{POST} method instead:
467
468\begin{verbatim}
469>>> import urllib
470>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
471>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
472>>> print f.read()
473\end{verbatim}
Fred Draked2167032002-04-04 20:09:50 +0000474
475The following example uses an explicitly specified HTTP proxy,
476overriding environment settings:
477
478\begin{verbatim}
479>>> import urllib
480>>> proxies = {'http': 'http://proxy.example.com:8080/'}
481>>> opener = urllib.FancyURLopener(proxies)
482>>> f = opener.open("http://www.python.org")
483>>> f.read()
484\end{verbatim}
485
486The following example uses no proxies at all, overriding environment
487settings:
488
489\begin{verbatim}
490>>> import urllib
491>>> opener = urllib.FancyURLopener({})
492>>> f = opener.open("http://www.python.org/")
493>>> f.read()
494\end{verbatim}