blob: 0df73859ba8360a46d48727dd4b22b5a4dfebcdc [file] [log] [blame]
Moshe Zadka8a18e992001-03-01 08:40:42 +00001\section{\module{urllib2} ---
2 extensible library for opening URLs}
3
4\declaremodule{standard}{urllib2}
Moshe Zadka8a18e992001-03-01 08:40:42 +00005\moduleauthor{Jeremy Hylton}{jhylton@users.sourceforge.net}
6\sectionauthor{Moshe Zadka}{moshez@users.sourceforge.net}
7
8\modulesynopsis{An extensible library for opening URLs using a variety of
9 protocols}
10
11The \module{urllib2} module defines functions and classes which help
Fred Drake93c86712001-03-02 20:39:34 +000012in opening URLs (mostly HTTP) in a complex world --- basic and digest
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000013authentication, redirections, cookies and more.
Moshe Zadka8a18e992001-03-01 08:40:42 +000014
15The \module{urllib2} module defines the following functions:
16
17\begin{funcdesc}{urlopen}{url\optional{, data}}
Fred Drake399bc8c2001-11-09 03:49:29 +000018Open the URL \var{url}, which can be either a string or a \class{Request}
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000019object.
Moshe Zadka8a18e992001-03-01 08:40:42 +000020
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000021\var{data} may be a string specifying additional data to send to the
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022server, or \code{None} if no such data is needed.
23Currently HTTP requests are the only ones that use \var{data};
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000024the HTTP request will be a POST instead of a GET when the \var{data}
25parameter is provided. \var{data} should be a buffer in the standard
26\mimetype{application/x-www-form-urlencoded} format. The
27\function{urllib.urlencode()} function takes a mapping or sequence of
282-tuples and returns a string in this format.
Moshe Zadka8a18e992001-03-01 08:40:42 +000029
30This function returns a file-like object with two additional methods:
31
32\begin{itemize}
Fred Drake93c86712001-03-02 20:39:34 +000033 \item \method{geturl()} --- return the URL of the resource retrieved
34 \item \method{info()} --- return the meta-information of the page, as
35 a dictionary-like object
Moshe Zadka8a18e992001-03-01 08:40:42 +000036\end{itemize}
37
38Raises \exception{URLError} on errors.
Kurt B. Kaiser8932b412004-07-11 02:13:17 +000039
40Note that \code{None} may be returned if no handler handles the
41request (though the default installed global \class{OpenerDirector}
42uses \class{UnknownHandler} to ensure this never happens).
Moshe Zadka8a18e992001-03-01 08:40:42 +000043\end{funcdesc}
44
45\begin{funcdesc}{install_opener}{opener}
Kurt B. Kaiser8932b412004-07-11 02:13:17 +000046Install an \class{OpenerDirector} instance as the default global
47opener. Installing an opener is only necessary if you want urlopen to
48use that opener; otherwise, simply call \method{OpenerDirector.open()}
49instead of \function{urlopen()}. The code does not check for a real
50\class{OpenerDirector}, and any class with the appropriate interface
51will work.
Moshe Zadka8a18e992001-03-01 08:40:42 +000052\end{funcdesc}
53
Fred Drake93c86712001-03-02 20:39:34 +000054\begin{funcdesc}{build_opener}{\optional{handler, \moreargs}}
Moshe Zadka8a18e992001-03-01 08:40:42 +000055Return an \class{OpenerDirector} instance, which chains the
56handlers in the order given. \var{handler}s can be either instances
57of \class{BaseHandler}, or subclasses of \class{BaseHandler} (in
58which case it must be possible to call the constructor without
Fred Drake399bc8c2001-11-09 03:49:29 +000059any parameters). Instances of the following classes will be in
60front of the \var{handler}s, unless the \var{handler}s contain
Moshe Zadka8a18e992001-03-01 08:40:42 +000061them, instances of them or subclasses of them:
Fred Draked9cf8e72003-07-14 21:07:05 +000062\class{ProxyHandler}, \class{UnknownHandler}, \class{HTTPHandler},
63\class{HTTPDefaultErrorHandler}, \class{HTTPRedirectHandler},
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000064\class{FTPHandler}, \class{FileHandler}, \class{HTTPErrorProcessor}.
Moshe Zadka8a18e992001-03-01 08:40:42 +000065
Fred Drake93c86712001-03-02 20:39:34 +000066If the Python installation has SSL support (\function{socket.ssl()}
67exists), \class{HTTPSHandler} will also be added.
Gustavo Niemeyer9556fba2003-06-07 17:53:08 +000068
Fred Draked9cf8e72003-07-14 21:07:05 +000069Beginning in Python 2.3, a \class{BaseHandler} subclass may also
70change its \member{handler_order} member variable to modify its
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000071position in the handlers list.
Moshe Zadka8a18e992001-03-01 08:40:42 +000072\end{funcdesc}
73
Fred Drake93c86712001-03-02 20:39:34 +000074
75The following exceptions are raised as appropriate:
76
Moshe Zadka8a18e992001-03-01 08:40:42 +000077\begin{excdesc}{URLError}
Fred Drake399bc8c2001-11-09 03:49:29 +000078The handlers raise this exception (or derived exceptions) when they
79run into a problem. It is a subclass of \exception{IOError}.
Moshe Zadka8a18e992001-03-01 08:40:42 +000080\end{excdesc}
81
82\begin{excdesc}{HTTPError}
83A subclass of \exception{URLError}, it can also function as a
Fred Drake93c86712001-03-02 20:39:34 +000084non-exceptional file-like return value (the same thing that
85\function{urlopen()} returns). This is useful when handling exotic
86HTTP errors, such as requests for authentication.
Moshe Zadka8a18e992001-03-01 08:40:42 +000087\end{excdesc}
88
Fred Drake93c86712001-03-02 20:39:34 +000089
90The following classes are provided:
91
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000092\begin{classdesc}{Request}{url\optional{, data}\optional{, headers}
93 \optional{, origin_req_host}\optional{, unverifiable}}
Moshe Zadka8a18e992001-03-01 08:40:42 +000094This class is an abstraction of a URL request.
95
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096\var{url} should be a string containing a valid URL.
97
98\var{data} may be a string specifying additional data to send to the
99server, or \code{None} if no such data is needed.
100Currently HTTP requests are the only ones that use \var{data};
101the HTTP request will be a POST instead of a GET when the \var{data}
102parameter is provided. \var{data} should be a buffer in the standard
103\mimetype{application/x-www-form-urlencoded} format. The
104\function{urllib.urlencode()} function takes a mapping or sequence of
1052-tuples and returns a string in this format.
106
Moshe Zadka8a18e992001-03-01 08:40:42 +0000107\var{headers} should be a dictionary, and will be treated as if
Fred Drake93c86712001-03-02 20:39:34 +0000108\method{add_header()} was called with each key and value as arguments.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000109
110The final two arguments are only of interest for correct handling of
111third-party HTTP cookies:
112
113\var{origin_req_host} should be the request-host of the origin
114transaction, as defined by \rfc{2965}. It defaults to
115\code{cookielib.request_host(self)}. This is the host name or IP
116address of the original request that was initiated by the user. For
117example, if the request is for an image in an HTML document, this
118should be the request-host of the request for the page containing the
119image.
120
121\var{unverifiable} should indicate whether the request is
122unverifiable, as defined by RFC 2965. It defaults to False. An
123unverifiable request is one whose URL the user did not have the option
124to approve. For example, if the request is for an image in an HTML
125document, and the user had no option to approve the automatic fetching
126of the image, this should be true.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000127\end{classdesc}
128
Fred Drake93c86712001-03-02 20:39:34 +0000129\begin{classdesc}{OpenerDirector}{}
130The \class{OpenerDirector} class opens URLs via \class{BaseHandler}s
131chained together. It manages the chaining of handlers, and recovery
132from errors.
133\end{classdesc}
134
135\begin{classdesc}{BaseHandler}{}
136This is the base class for all registered handlers --- and handles only
137the simple mechanics of registration.
138\end{classdesc}
139
140\begin{classdesc}{HTTPDefaultErrorHandler}{}
141A class which defines a default handler for HTTP error responses; all
142responses are turned into \exception{HTTPError} exceptions.
143\end{classdesc}
144
145\begin{classdesc}{HTTPRedirectHandler}{}
146A class to handle redirections.
147\end{classdesc}
148
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000149\begin{classdesc}{HTTPCookieProcessor}{\optional{cookiejar}}
150A class to handle HTTP Cookies.
151\end{classdesc}
152
Fred Drake93c86712001-03-02 20:39:34 +0000153\begin{classdesc}{ProxyHandler}{\optional{proxies}}
154Cause requests to go through a proxy.
155If \var{proxies} is given, it must be a dictionary mapping
156protocol names to URLs of proxies.
157The default is to read the list of proxies from the environment
Martin v. Löwisbe837372004-08-25 11:24:42 +0000158variables \envvar{<protocol>_proxy}.
Fred Drake93c86712001-03-02 20:39:34 +0000159\end{classdesc}
160
161\begin{classdesc}{HTTPPasswordMgr}{}
162Keep a database of
163\code{(\var{realm}, \var{uri}) -> (\var{user}, \var{password})}
164mappings.
165\end{classdesc}
166
167\begin{classdesc}{HTTPPasswordMgrWithDefaultRealm}{}
168Keep a database of
169\code{(\var{realm}, \var{uri}) -> (\var{user}, \var{password})} mappings.
170A realm of \code{None} is considered a catch-all realm, which is searched
171if no other realm fits.
172\end{classdesc}
173
174\begin{classdesc}{AbstractBasicAuthHandler}{\optional{password_mgr}}
175This is a mixin class that helps with HTTP authentication, both
176to the remote host and to a proxy.
Fred Drake399bc8c2001-11-09 03:49:29 +0000177\var{password_mgr}, if given, should be something that is compatible
178with \class{HTTPPasswordMgr}; refer to section~\ref{http-password-mgr}
179for information on the interface that must be supported.
Fred Drake93c86712001-03-02 20:39:34 +0000180\end{classdesc}
181
182\begin{classdesc}{HTTPBasicAuthHandler}{\optional{password_mgr}}
183Handle authentication with the remote host.
Fred Drake399bc8c2001-11-09 03:49:29 +0000184\var{password_mgr}, if given, should be something that is compatible
185with \class{HTTPPasswordMgr}; refer to section~\ref{http-password-mgr}
186for information on the interface that must be supported.
Fred Drake93c86712001-03-02 20:39:34 +0000187\end{classdesc}
188
189\begin{classdesc}{ProxyBasicAuthHandler}{\optional{password_mgr}}
190Handle authentication with the proxy.
Fred Drake399bc8c2001-11-09 03:49:29 +0000191\var{password_mgr}, if given, should be something that is compatible
192with \class{HTTPPasswordMgr}; refer to section~\ref{http-password-mgr}
193for information on the interface that must be supported.
Fred Drake93c86712001-03-02 20:39:34 +0000194\end{classdesc}
195
196\begin{classdesc}{AbstractDigestAuthHandler}{\optional{password_mgr}}
Fred Drake399bc8c2001-11-09 03:49:29 +0000197This is a mixin class that helps with HTTP authentication, both
Fred Drake93c86712001-03-02 20:39:34 +0000198to the remote host and to a proxy.
Fred Drake399bc8c2001-11-09 03:49:29 +0000199\var{password_mgr}, if given, should be something that is compatible
200with \class{HTTPPasswordMgr}; refer to section~\ref{http-password-mgr}
201for information on the interface that must be supported.
Fred Drake93c86712001-03-02 20:39:34 +0000202\end{classdesc}
203
204\begin{classdesc}{HTTPDigestAuthHandler}{\optional{password_mgr}}
205Handle authentication with the remote host.
Fred Drake399bc8c2001-11-09 03:49:29 +0000206\var{password_mgr}, if given, should be something that is compatible
207with \class{HTTPPasswordMgr}; refer to section~\ref{http-password-mgr}
208for information on the interface that must be supported.
Fred Drake93c86712001-03-02 20:39:34 +0000209\end{classdesc}
210
211\begin{classdesc}{ProxyDigestAuthHandler}{\optional{password_mgr}}
212Handle authentication with the proxy.
Fred Drake399bc8c2001-11-09 03:49:29 +0000213\var{password_mgr}, if given, should be something that is compatible
214with \class{HTTPPasswordMgr}; refer to section~\ref{http-password-mgr}
215for information on the interface that must be supported.
Fred Drake93c86712001-03-02 20:39:34 +0000216\end{classdesc}
217
218\begin{classdesc}{HTTPHandler}{}
219A class to handle opening of HTTP URLs.
220\end{classdesc}
221
222\begin{classdesc}{HTTPSHandler}{}
223A class to handle opening of HTTPS URLs.
224\end{classdesc}
225
226\begin{classdesc}{FileHandler}{}
227Open local files.
228\end{classdesc}
229
230\begin{classdesc}{FTPHandler}{}
231Open FTP URLs.
232\end{classdesc}
233
234\begin{classdesc}{CacheFTPHandler}{}
235Open FTP URLs, keeping a cache of open FTP connections to minimize
236delays.
237\end{classdesc}
238
Fred Drake93c86712001-03-02 20:39:34 +0000239\begin{classdesc}{UnknownHandler}{}
240A catch-all class to handle unknown URLs.
241\end{classdesc}
242
243
244\subsection{Request Objects \label{request-objects}}
245
Moshe Zadka8a18e992001-03-01 08:40:42 +0000246The following methods describe all of \class{Request}'s public interface,
247and so all must be overridden in subclasses.
248
249\begin{methoddesc}[Request]{add_data}{data}
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000250Set the \class{Request} data to \var{data}. This is ignored by all
251handlers except HTTP handlers --- and there it should be a byte
252string, and will change the request to be \code{POST} rather than
253\code{GET}.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000254\end{methoddesc}
255
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000256\begin{methoddesc}[Request]{get_method}{}
257Return a string indicating the HTTP request method. This is only
Fred Drakecc97ebf2005-04-13 01:08:23 +0000258meaningful for HTTP requests, and currently always returns
259\code{'GET'} or \code{'POST'}.
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000260\end{methoddesc}
261
Fred Drake399bc8c2001-11-09 03:49:29 +0000262\begin{methoddesc}[Request]{has_data}{}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000263Return whether the instance has a non-\code{None} data.
264\end{methoddesc}
265
Fred Drake399bc8c2001-11-09 03:49:29 +0000266\begin{methoddesc}[Request]{get_data}{}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000267Return the instance's data.
268\end{methoddesc}
269
270\begin{methoddesc}[Request]{add_header}{key, val}
Fred Drake93c86712001-03-02 20:39:34 +0000271Add another header to the request. Headers are currently ignored by
272all handlers except HTTP handlers, where they are added to the list
Fred Drake399bc8c2001-11-09 03:49:29 +0000273of headers sent to the server. Note that there cannot be more than
Fred Drake93c86712001-03-02 20:39:34 +0000274one header with the same name, and later calls will overwrite
275previous calls in case the \var{key} collides. Currently, this is
276no loss of HTTP functionality, since all headers which have meaning
Fred Drake399bc8c2001-11-09 03:49:29 +0000277when used more than once have a (header-specific) way of gaining the
Moshe Zadka8a18e992001-03-01 08:40:42 +0000278same functionality using only one header.
279\end{methoddesc}
280
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000281\begin{methoddesc}[Request]{add_unredirected_header}{key, header}
282Add a header that will not be added to a redirected request.
Neal Norwitzfb0521f2004-02-28 16:00:23 +0000283\versionadded{2.4}
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000284\end{methoddesc}
285
286\begin{methoddesc}[Request]{has_header}{header}
287Return whether the instance has the named header (checks both regular
288and unredirected).
Neal Norwitzfb0521f2004-02-28 16:00:23 +0000289\versionadded{2.4}
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000290\end{methoddesc}
291
Moshe Zadka8a18e992001-03-01 08:40:42 +0000292\begin{methoddesc}[Request]{get_full_url}{}
293Return the URL given in the constructor.
294\end{methoddesc}
295
296\begin{methoddesc}[Request]{get_type}{}
Fred Drake93c86712001-03-02 20:39:34 +0000297Return the type of the URL --- also known as the scheme.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000298\end{methoddesc}
299
300\begin{methoddesc}[Request]{get_host}{}
Fred Drake399bc8c2001-11-09 03:49:29 +0000301Return the host to which a connection will be made.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000302\end{methoddesc}
303
304\begin{methoddesc}[Request]{get_selector}{}
305Return the selector --- the part of the URL that is sent to
306the server.
307\end{methoddesc}
308
309\begin{methoddesc}[Request]{set_proxy}{host, type}
Fred Drake399bc8c2001-11-09 03:49:29 +0000310Prepare the request by connecting to a proxy server. The \var{host}
311and \var{type} will replace those of the instance, and the instance's
Fred Drake93c86712001-03-02 20:39:34 +0000312selector will be the original URL given in the constructor.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000313\end{methoddesc}
314
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000315\begin{methoddesc}[Request]{get_origin_req_host}{}
316Return the request-host of the origin transaction, as defined by
317\rfc{2965}. See the documentation for the \class{Request}
318constructor.
319\end{methoddesc}
320
321\begin{methoddesc}[Request]{is_unverifiable}{}
322Return whether the request is unverifiable, as defined by RFC 2965.
323See the documentation for the \class{Request} constructor.
324\end{methoddesc}
325
Fred Drake93c86712001-03-02 20:39:34 +0000326
327\subsection{OpenerDirector Objects \label{opener-director-objects}}
328
329\class{OpenerDirector} instances have the following methods:
Moshe Zadka8a18e992001-03-01 08:40:42 +0000330
331\begin{methoddesc}[OpenerDirector]{add_handler}{handler}
Fred Drake93c86712001-03-02 20:39:34 +0000332\var{handler} should be an instance of \class{BaseHandler}. The
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000333following methods are searched, and added to the possible chains (note
334that HTTP errors are a special case).
Moshe Zadka8a18e992001-03-01 08:40:42 +0000335
336\begin{itemize}
Fred Drake93c86712001-03-02 20:39:34 +0000337 \item \method{\var{protocol}_open()} ---
338 signal that the handler knows how to open \var{protocol} URLs.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000339 \item \method{http_error_\var{type}()} ---
340 signal that the handler knows how to handle HTTP errors with HTTP
341 error code \var{type}.
342 \item \method{\var{protocol}_error()} ---
343 signal that the handler knows how to handle errors from
344 (non-\code{http}) \var{protocol}.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000345 \item \method{\var{protocol}_request()} ---
346 signal that the handler knows how to pre-process \var{protocol}
347 requests.
348 \item \method{\var{protocol}_response()} ---
349 signal that the handler knows how to post-process \var{protocol}
350 responses.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000351\end{itemize}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000352\end{methoddesc}
353
Moshe Zadka8a18e992001-03-01 08:40:42 +0000354\begin{methoddesc}[OpenerDirector]{open}{url\optional{, data}}
Fred Drake399bc8c2001-11-09 03:49:29 +0000355Open the given \var{url} (which can be a request object or a string),
Moshe Zadka8a18e992001-03-01 08:40:42 +0000356optionally passing the given \var{data}.
357Arguments, return values and exceptions raised are the same as those
Fred Drake93c86712001-03-02 20:39:34 +0000358of \function{urlopen()} (which simply calls the \method{open()} method
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000359on the currently installed global \class{OpenerDirector}).
Moshe Zadka8a18e992001-03-01 08:40:42 +0000360\end{methoddesc}
361
Fred Drake93c86712001-03-02 20:39:34 +0000362\begin{methoddesc}[OpenerDirector]{error}{proto\optional{,
363 arg\optional{, \moreargs}}}
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000364Handle an error of the given protocol. This will call the registered
Fred Drake399bc8c2001-11-09 03:49:29 +0000365error handlers for the given protocol with the given arguments (which
366are protocol specific). The HTTP protocol is a special case which
367uses the HTTP response code to determine the specific error handler;
368refer to the \method{http_error_*()} methods of the handler classes.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000369
370Return values and exceptions raised are the same as those
Fred Drake93c86712001-03-02 20:39:34 +0000371of \function{urlopen()}.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000372\end{methoddesc}
373
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000374OpenerDirector objects open URLs in three stages:
375
Andrew M. Kuchling300ce192004-07-10 18:28:33 +0000376The order in which these methods are called within each stage is
377determined by sorting the handler instances.
378
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000379\begin{enumerate}
380 \item Every handler with a method named like
381 \method{\var{protocol}_request()} has that method called to
382 pre-process the request.
383
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000384 \item Handlers with a method named like
385 \method{\var{protocol}_open()} are called to handle the request.
386 This stage ends when a handler either returns a
387 non-\constant{None} value (ie. a response), or raises an exception
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000388 (usually \exception{URLError}). Exceptions are allowed to propagate.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000389
390 In fact, the above algorithm is first tried for methods named
391 \method{default_open}. If all such methods return
392 \constant{None}, the algorithm is repeated for methods named like
393 \method{\var{protocol}_open()}. If all such methods return
394 \constant{None}, the algorithm is repeated for methods named
395 \method{unknown_open()}.
396
397 Note that the implementation of these methods may involve calls of
398 the parent \class{OpenerDirector} instance's \method{.open()} and
399 \method{.error()} methods.
400
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000401 \item Every handler with a method named like
402 \method{\var{protocol}_response()} has that method called to
403 post-process the response.
404
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000405\end{enumerate}
Fred Drake93c86712001-03-02 20:39:34 +0000406
407\subsection{BaseHandler Objects \label{base-handler-objects}}
408
409\class{BaseHandler} objects provide a couple of methods that are
410directly useful, and others that are meant to be used by derived
411classes. These are intended for direct use:
Moshe Zadka8a18e992001-03-01 08:40:42 +0000412
413\begin{methoddesc}[BaseHandler]{add_parent}{director}
414Add a director as parent.
415\end{methoddesc}
416
417\begin{methoddesc}[BaseHandler]{close}{}
418Remove any parents.
419\end{methoddesc}
420
Fred Drake399bc8c2001-11-09 03:49:29 +0000421The following members and methods should only be used by classes
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000422derived from \class{BaseHandler}. \note{The convention has been
423adopted that subclasses defining \method{\var{protocol}_request()} or
424\method{\var{protocol}_response()} methods are named
425\class{*Processor}; all others are named \class{*Handler}.}
426
Moshe Zadka8a18e992001-03-01 08:40:42 +0000427
428\begin{memberdesc}[BaseHandler]{parent}
Fred Drake93c86712001-03-02 20:39:34 +0000429A valid \class{OpenerDirector}, which can be used to open using a
430different protocol, or handle errors.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000431\end{memberdesc}
432
433\begin{methoddesc}[BaseHandler]{default_open}{req}
Fred Drake93c86712001-03-02 20:39:34 +0000434This method is \emph{not} defined in \class{BaseHandler}, but
435subclasses should define it if they want to catch all URLs.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000436
Fred Drake399bc8c2001-11-09 03:49:29 +0000437This method, if implemented, will be called by the parent
Fred Drake93c86712001-03-02 20:39:34 +0000438\class{OpenerDirector}. It should return a file-like object as
439described in the return value of the \method{open()} of
Fred Drake399bc8c2001-11-09 03:49:29 +0000440\class{OpenerDirector}, or \code{None}. It should raise
Fred Drake93c86712001-03-02 20:39:34 +0000441\exception{URLError}, unless a truly exceptional thing happens (for
442example, \exception{MemoryError} should not be mapped to
Fred Drake399bc8c2001-11-09 03:49:29 +0000443\exception{URLError}).
Moshe Zadka8a18e992001-03-01 08:40:42 +0000444
445This method will be called before any protocol-specific open method.
446\end{methoddesc}
447
Fred Drake47852462001-05-11 15:46:45 +0000448\begin{methoddescni}[BaseHandler]{\var{protocol}_open}{req}
Fred Drake93c86712001-03-02 20:39:34 +0000449This method is \emph{not} defined in \class{BaseHandler}, but
450subclasses should define it if they want to handle URLs with the given
451protocol.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000452
Fred Drake399bc8c2001-11-09 03:49:29 +0000453This method, if defined, will be called by the parent
Fred Drake93c86712001-03-02 20:39:34 +0000454\class{OpenerDirector}. Return values should be the same as for
455\method{default_open()}.
Fred Drake47852462001-05-11 15:46:45 +0000456\end{methoddescni}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000457
458\begin{methoddesc}[BaseHandler]{unknown_open}{req}
Fred Drake93c86712001-03-02 20:39:34 +0000459This method is \var{not} defined in \class{BaseHandler}, but
460subclasses should define it if they want to catch all URLs with no
Fred Drake399bc8c2001-11-09 03:49:29 +0000461specific registered handler to open it.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000462
Fred Drake399bc8c2001-11-09 03:49:29 +0000463This method, if implemented, will be called by the \member{parent}
Fred Drake93c86712001-03-02 20:39:34 +0000464\class{OpenerDirector}. Return values should be the same as for
465\method{default_open()}.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000466\end{methoddesc}
467
468\begin{methoddesc}[BaseHandler]{http_error_default}{req, fp, code, msg, hdrs}
Fred Drake93c86712001-03-02 20:39:34 +0000469This method is \emph{not} defined in \class{BaseHandler}, but
470subclasses should override it if they intend to provide a catch-all
471for otherwise unhandled HTTP errors. It will be called automatically
472by the \class{OpenerDirector} getting the error, and should not
473normally be called in other circumstances.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000474
Fred Drake93c86712001-03-02 20:39:34 +0000475\var{req} will be a \class{Request} object, \var{fp} will be a
476file-like object with the HTTP error body, \var{code} will be the
477three-digit code of the error, \var{msg} will be the user-visible
478explanation of the code and \var{hdrs} will be a mapping object with
479the headers of the error.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000480
481Return values and exceptions raised should be the same as those
Fred Drake93c86712001-03-02 20:39:34 +0000482of \function{urlopen()}.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000483\end{methoddesc}
484
Fred Drake93c86712001-03-02 20:39:34 +0000485\begin{methoddesc}[BaseHandler]{http_error_\var{nnn}}{req, fp, code, msg, hdrs}
486\var{nnn} should be a three-digit HTTP error code. This method is
487also not defined in \class{BaseHandler}, but will be called, if it
488exists, on an instance of a subclass, when an HTTP error with code
489\var{nnn} occurs.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000490
Fred Drake93c86712001-03-02 20:39:34 +0000491Subclasses should override this method to handle specific HTTP
492errors.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000493
Fred Drake93c86712001-03-02 20:39:34 +0000494Arguments, return values and exceptions raised should be the same as
495for \method{http_error_default()}.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000496\end{methoddesc}
497
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000498\begin{methoddescni}[BaseHandler]{\var{protocol}_request}{req}
499This method is \emph{not} defined in \class{BaseHandler}, but
500subclasses should define it if they want to pre-process requests of
501the given protocol.
502
503This method, if defined, will be called by the parent
504\class{OpenerDirector}. \var{req} will be a \class{Request} object.
505The return value should be a \class{Request} object.
506\end{methoddescni}
507
508\begin{methoddescni}[BaseHandler]{\var{protocol}_response}{req, response}
509This method is \emph{not} defined in \class{BaseHandler}, but
510subclasses should define it if they want to post-process responses of
511the given protocol.
512
513This method, if defined, will be called by the parent
514\class{OpenerDirector}. \var{req} will be a \class{Request} object.
515\var{response} will be an object implementing the same interface as
516the return value of \function{urlopen()}. The return value should
517implement the same interface as the return value of
518\function{urlopen()}.
519\end{methoddescni}
520
Fred Drake93c86712001-03-02 20:39:34 +0000521\subsection{HTTPRedirectHandler Objects \label{http-redirect-handler}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000522
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000523\note{Some HTTP redirections require action from this module's client
524 code. If this is the case, \exception{HTTPError} is raised. See
525 \rfc{2616} for details of the precise meanings of the various
526 redirection codes.}
527
528\begin{methoddesc}[HTTPRedirectHandler]{redirect_request}{req,
529 fp, code, msg, hdrs}
530Return a \class{Request} or \code{None} in response to a redirect.
531This is called by the default implementations of the
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000532\method{http_error_30*()} methods when a redirection is received from
533the server. If a redirection should take place, return a new
Fred Draked9cf8e72003-07-14 21:07:05 +0000534\class{Request} to allow \method{http_error_30*()} to perform the
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000535redirect. Otherwise, raise \exception{HTTPError} if no other handler
536should try to handle this URL, or return \code{None} if you can't but
537another handler might.
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000538
Fred Draked9cf8e72003-07-14 21:07:05 +0000539\begin{notice}
540 The default implementation of this method does not strictly
541 follow \rfc{2616}, which says that 301 and 302 responses to \code{POST}
Martin v. Löwis162f0812003-07-12 07:33:32 +0000542 requests must not be automatically redirected without confirmation by
543 the user. In reality, browsers do allow automatic redirection of
Fred Draked9cf8e72003-07-14 21:07:05 +0000544 these responses, changing the POST to a \code{GET}, and the default
545 implementation reproduces this behavior.
546\end{notice}
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000547\end{methoddesc}
548
Moshe Zadka8a18e992001-03-01 08:40:42 +0000549
Fred Drake93c86712001-03-02 20:39:34 +0000550\begin{methoddesc}[HTTPRedirectHandler]{http_error_301}{req,
551 fp, code, msg, hdrs}
552Redirect to the \code{Location:} URL. This method is called by
553the parent \class{OpenerDirector} when getting an HTTP
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000554`moved permanently' response.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000555\end{methoddesc}
556
Fred Drake93c86712001-03-02 20:39:34 +0000557\begin{methoddesc}[HTTPRedirectHandler]{http_error_302}{req,
558 fp, code, msg, hdrs}
559The same as \method{http_error_301()}, but called for the
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000560`found' response.
Fred Drake93c86712001-03-02 20:39:34 +0000561\end{methoddesc}
562
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000563\begin{methoddesc}[HTTPRedirectHandler]{http_error_303}{req,
564 fp, code, msg, hdrs}
565The same as \method{http_error_301()}, but called for the
Martin v. Löwis162f0812003-07-12 07:33:32 +0000566`see other' response.
Raymond Hettinger024aaa12003-04-24 15:32:12 +0000567\end{methoddesc}
Fred Drake93c86712001-03-02 20:39:34 +0000568
Martin v. Löwis162f0812003-07-12 07:33:32 +0000569\begin{methoddesc}[HTTPRedirectHandler]{http_error_307}{req,
570 fp, code, msg, hdrs}
571The same as \method{http_error_301()}, but called for the
572`temporary redirect' response.
Fred Drake9753ae12003-07-14 20:53:57 +0000573\end{methoddesc}
574
Martin v. Löwis162f0812003-07-12 07:33:32 +0000575
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000576\subsection{HTTPCookieProcessor Objects \label{http-cookie-processor}}
577
Andrew M. Kuchlingd54a0ae2005-12-04 20:25:23 +0000578\versionadded{2.4}
579
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000580\class{HTTPCookieProcessor} instances have one attribute:
581
Guido van Rossumd8faa362007-04-27 19:54:29 +0000582\begin{memberdesc}[HTTPCookieProcessor]{cookiejar}
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000583The \class{cookielib.CookieJar} in which cookies are stored.
584\end{memberdesc}
585
586
Fred Drake93c86712001-03-02 20:39:34 +0000587\subsection{ProxyHandler Objects \label{proxy-handler}}
588
Fred Drake47852462001-05-11 15:46:45 +0000589\begin{methoddescni}[ProxyHandler]{\var{protocol}_open}{request}
Fred Drake93c86712001-03-02 20:39:34 +0000590The \class{ProxyHandler} will have a method
591\method{\var{protocol}_open()} for every \var{protocol} which has a
592proxy in the \var{proxies} dictionary given in the constructor. The
593method will modify requests to go through the proxy, by calling
594\code{request.set_proxy()}, and call the next handler in the chain to
595actually execute the protocol.
Fred Drake47852462001-05-11 15:46:45 +0000596\end{methoddescni}
Fred Drake93c86712001-03-02 20:39:34 +0000597
598
599\subsection{HTTPPasswordMgr Objects \label{http-password-mgr}}
600
601These methods are available on \class{HTTPPasswordMgr} and
602\class{HTTPPasswordMgrWithDefaultRealm} objects.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000603
604\begin{methoddesc}[HTTPPasswordMgr]{add_password}{realm, uri, user, passwd}
Fred Drakebb066cf2004-05-12 03:07:27 +0000605\var{uri} can be either a single URI, or a sequence of URIs. \var{realm},
Moshe Zadka8a18e992001-03-01 08:40:42 +0000606\var{user} and \var{passwd} must be strings. This causes
Fred Drake93c86712001-03-02 20:39:34 +0000607\code{(\var{user}, \var{passwd})} to be used as authentication tokens
Moshe Zadka8a18e992001-03-01 08:40:42 +0000608when authentication for \var{realm} and a super-URI of any of the
609given URIs is given.
610\end{methoddesc}
611
612\begin{methoddesc}[HTTPPasswordMgr]{find_user_password}{realm, authuri}
Fred Drake93c86712001-03-02 20:39:34 +0000613Get user/password for given realm and URI, if any. This method will
614return \code{(None, None)} if there is no matching user/password.
615
616For \class{HTTPPasswordMgrWithDefaultRealm} objects, the realm
617\code{None} will be searched if the given \var{realm} has no matching
618user/password.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000619\end{methoddesc}
620
Moshe Zadka8a18e992001-03-01 08:40:42 +0000621
Fred Drake93c86712001-03-02 20:39:34 +0000622\subsection{AbstractBasicAuthHandler Objects
623 \label{abstract-basic-auth-handler}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000624
Thomas Wouters477c8d52006-05-27 19:21:47 +0000625\begin{methoddesc}[AbstractBasicAuthHandler]{http_error_auth_reqed}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000626 {authreq, host, req, headers}
Fred Drake399bc8c2001-11-09 03:49:29 +0000627Handle an authentication request by getting a user/password pair, and
628re-trying the request. \var{authreq} should be the name of the header
629where the information about the realm is included in the request,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000630\var{host} specifies the URL and path to authenticate for, \var{req}
631should be the (failed) \class{Request} object, and \var{headers}
632should be the error headers.
633
634\var{host} is either an authority (e.g. \code{"python.org"}) or a URL
635containing an authority component (e.g. \code{"http://python.org/"}).
636In either case, the authority must not contain a userinfo component
637(so, \code{"python.org"} and \code{"python.org:80"} are fine,
638\code{"joe:password@python.org"} is not).
Moshe Zadka8a18e992001-03-01 08:40:42 +0000639\end{methoddesc}
640
Fred Drake93c86712001-03-02 20:39:34 +0000641
642\subsection{HTTPBasicAuthHandler Objects
643 \label{http-basic-auth-handler}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000644
645\begin{methoddesc}[HTTPBasicAuthHandler]{http_error_401}{req, fp, code,
646 msg, hdrs}
Fred Drake399bc8c2001-11-09 03:49:29 +0000647Retry the request with authentication information, if available.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000648\end{methoddesc}
649
Fred Drake93c86712001-03-02 20:39:34 +0000650
651\subsection{ProxyBasicAuthHandler Objects
652 \label{proxy-basic-auth-handler}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000653
654\begin{methoddesc}[ProxyBasicAuthHandler]{http_error_407}{req, fp, code,
655 msg, hdrs}
Fred Drake399bc8c2001-11-09 03:49:29 +0000656Retry the request with authentication information, if available.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000657\end{methoddesc}
658
Moshe Zadka8a18e992001-03-01 08:40:42 +0000659
Fred Drake93c86712001-03-02 20:39:34 +0000660\subsection{AbstractDigestAuthHandler Objects
661 \label{abstract-digest-auth-handler}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000662
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663\begin{methoddesc}[AbstractDigestAuthHandler]{http_error_auth_reqed}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000664 {authreq, host, req, headers}
665\var{authreq} should be the name of the header where the information about
Fred Drake399bc8c2001-11-09 03:49:29 +0000666the realm is included in the request, \var{host} should be the host to
667authenticate to, \var{req} should be the (failed) \class{Request}
668object, and \var{headers} should be the error headers.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000669\end{methoddesc}
670
Fred Drake93c86712001-03-02 20:39:34 +0000671
672\subsection{HTTPDigestAuthHandler Objects
673 \label{http-digest-auth-handler}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000674
675\begin{methoddesc}[HTTPDigestAuthHandler]{http_error_401}{req, fp, code,
676 msg, hdrs}
Fred Drake399bc8c2001-11-09 03:49:29 +0000677Retry the request with authentication information, if available.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000678\end{methoddesc}
679
Fred Drake93c86712001-03-02 20:39:34 +0000680
681\subsection{ProxyDigestAuthHandler Objects
682 \label{proxy-digest-auth-handler}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000683
684\begin{methoddesc}[ProxyDigestAuthHandler]{http_error_407}{req, fp, code,
685 msg, hdrs}
Fred Drake93c86712001-03-02 20:39:34 +0000686Retry the request with authentication information, if available.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000687\end{methoddesc}
688
Fred Drake93c86712001-03-02 20:39:34 +0000689
690\subsection{HTTPHandler Objects \label{http-handler-objects}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000691
692\begin{methoddesc}[HTTPHandler]{http_open}{req}
Fred Drake399bc8c2001-11-09 03:49:29 +0000693Send an HTTP request, which can be either GET or POST, depending on
Fred Drake93c86712001-03-02 20:39:34 +0000694\code{\var{req}.has_data()}.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000695\end{methoddesc}
696
Fred Drake93c86712001-03-02 20:39:34 +0000697
698\subsection{HTTPSHandler Objects \label{https-handler-objects}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000699
700\begin{methoddesc}[HTTPSHandler]{https_open}{req}
Fred Drake93c86712001-03-02 20:39:34 +0000701Send an HTTPS request, which can be either GET or POST, depending on
702\code{\var{req}.has_data()}.
Moshe Zadka8a18e992001-03-01 08:40:42 +0000703\end{methoddesc}
704
Moshe Zadka8a18e992001-03-01 08:40:42 +0000705
Fred Drake93c86712001-03-02 20:39:34 +0000706\subsection{FileHandler Objects \label{file-handler-objects}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000707
708\begin{methoddesc}[FileHandler]{file_open}{req}
709Open the file locally, if there is no host name, or
Fred Drake93c86712001-03-02 20:39:34 +0000710the host name is \code{'localhost'}. Change the
Moshe Zadka8a18e992001-03-01 08:40:42 +0000711protocol to \code{ftp} otherwise, and retry opening
712it using \member{parent}.
713\end{methoddesc}
714
Fred Drake93c86712001-03-02 20:39:34 +0000715
716\subsection{FTPHandler Objects \label{ftp-handler-objects}}
Moshe Zadka8a18e992001-03-01 08:40:42 +0000717
718\begin{methoddesc}[FTPHandler]{ftp_open}{req}
719Open the FTP file indicated by \var{req}.
720The login is always done with empty username and password.
721\end{methoddesc}
722
Moshe Zadka8a18e992001-03-01 08:40:42 +0000723
Fred Drake93c86712001-03-02 20:39:34 +0000724\subsection{CacheFTPHandler Objects \label{cacheftp-handler-objects}}
725
726\class{CacheFTPHandler} objects are \class{FTPHandler} objects with
727the following additional methods:
Moshe Zadka8a18e992001-03-01 08:40:42 +0000728
729\begin{methoddesc}[CacheFTPHandler]{setTimeout}{t}
730Set timeout of connections to \var{t} seconds.
731\end{methoddesc}
732
733\begin{methoddesc}[CacheFTPHandler]{setMaxConns}{m}
734Set maximum number of cached connections to \var{m}.
735\end{methoddesc}
736
Fred Drake93c86712001-03-02 20:39:34 +0000737
Fred Drake93c86712001-03-02 20:39:34 +0000738\subsection{UnknownHandler Objects \label{unknown-handler-objects}}
739
Fred Drakea9399112001-07-05 21:14:03 +0000740\begin{methoddesc}[UnknownHandler]{unknown_open}{}
Fred Drake93c86712001-03-02 20:39:34 +0000741Raise a \exception{URLError} exception.
742\end{methoddesc}
Fred Drake53e5b712003-04-25 15:27:33 +0000743
744
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000745\subsection{HTTPErrorProcessor Objects \label{http-error-processor-objects}}
746
Neal Norwitzfb0521f2004-02-28 16:00:23 +0000747\versionadded{2.4}
748
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000749\begin{methoddesc}[HTTPErrorProcessor]{unknown_open}{}
750Process HTTP error responses.
751
752For 200 error codes, the response object is returned immediately.
753
754For non-200 error codes, this simply passes the job on to the
755\method{\var{protocol}_error_\var{code}()} handler methods, via
756\method{OpenerDirector.error()}. Eventually,
757\class{urllib2.HTTPDefaultErrorHandler} will raise an
758\exception{HTTPError} if no other handler handles the error.
759\end{methoddesc}
760
761
Fred Drake53e5b712003-04-25 15:27:33 +0000762\subsection{Examples \label{urllib2-examples}}
763
764This example gets the python.org main page and displays the first 100
765bytes of it:
766
767\begin{verbatim}
768>>> import urllib2
769>>> f = urllib2.urlopen('http://www.python.org/')
770>>> print f.read(100)
771<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
772<?xml-stylesheet href="./css/ht2html
773\end{verbatim}
774
775Here we are sending a data-stream to the stdin of a CGI and reading
Georg Brandla2764ad2005-12-26 23:36:32 +0000776the data it returns to us. Note that this example will only work when the
777Python installation supports SSL.
Fred Drake53e5b712003-04-25 15:27:33 +0000778
779\begin{verbatim}
780>>> import urllib2
781>>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',
782... data='This data is passed to stdin of the CGI')
783>>> f = urllib2.urlopen(req)
784>>> print f.read()
785Got Data: "This data is passed to stdin of the CGI"
786\end{verbatim}
787
788The code for the sample CGI used in the above example is:
789
790\begin{verbatim}
791#!/usr/bin/env python
792import sys
793data = sys.stdin.read()
Raymond Hettinger5de33782004-02-08 20:25:01 +0000794print 'Content-type: text-plain\n\nGot Data: "%s"' % data
Fred Drake53e5b712003-04-25 15:27:33 +0000795\end{verbatim}
Martin v. Löwisbe837372004-08-25 11:24:42 +0000796
797
798Use of Basic HTTP Authentication:
799
800\begin{verbatim}
801import urllib2
802# Create an OpenerDirector with support for Basic HTTP Authentication...
803auth_handler = urllib2.HTTPBasicAuthHandler()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000804auth_handler.add_password(realm='PDQ Application',
805 uri='https://mahler:8092/site-updates.py',
806 user='klem',
807 passwd='kadidd!ehopper')
Martin v. Löwisbe837372004-08-25 11:24:42 +0000808opener = urllib2.build_opener(auth_handler)
809# ...and install it globally so it can be used with urlopen.
810urllib2.install_opener(opener)
811urllib2.urlopen('http://www.example.com/login.html')
812\end{verbatim}
813
814\function{build_opener()} provides many handlers by default, including a
815\class{ProxyHandler}. By default, \class{ProxyHandler} uses the
816environment variables named \code{<scheme>_proxy}, where \code{<scheme>}
817is the URL scheme involved. For example, the \envvar{http_proxy}
818environment variable is read to obtain the HTTP proxy's URL.
819
820This example replaces the default \class{ProxyHandler} with one that uses
821programatically-supplied proxy URLs, and adds proxy authorization support
822with \class{ProxyBasicAuthHandler}.
823
824\begin{verbatim}
825proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
826proxy_auth_handler = urllib2.HTTPBasicAuthHandler()
827proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
828
829opener = build_opener(proxy_handler, proxy_auth_handler)
830# This time, rather than install the OpenerDirector, we use it directly:
831opener.open('http://www.example.com/login.html')
832\end{verbatim}
833
834
835Adding HTTP headers:
836
837Use the \var{headers} argument to the \class{Request} constructor, or:
838
839\begin{verbatim}
840import urllib2
841req = urllib2.Request('http://www.example.com/')
842req.add_header('Referer', 'http://www.python.org/')
843r = urllib2.urlopen(req)
844\end{verbatim}
845
846\class{OpenerDirector} automatically adds a \mailheader{User-Agent}
847header to every \class{Request}. To change this:
848
849\begin{verbatim}
850import urllib2
851opener = urllib2.build_opener()
852opener.addheaders = [('User-agent', 'Mozilla/5.0')]
853opener.open('http://www.example.com/')
854\end{verbatim}
855
856Also, remember that a few standard headers
857(\mailheader{Content-Length}, \mailheader{Content-Type} and
858\mailheader{Host}) are added when the \class{Request} is passed to
859\function{urlopen()} (or \method{OpenerDirector.open()}).