Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`urllib2` --- extensible library for opening URLs |
| 2 | ====================================================== |
| 3 | |
| 4 | .. module:: urllib2 |
| 5 | :synopsis: Next generation URL opening library. |
| 6 | .. moduleauthor:: Jeremy Hylton <jhylton@users.sourceforge.net> |
| 7 | .. sectionauthor:: Moshe Zadka <moshez@users.sourceforge.net> |
| 8 | |
| 9 | |
| 10 | The :mod:`urllib2` module defines functions and classes which help in opening |
| 11 | URLs (mostly HTTP) in a complex world --- basic and digest authentication, |
| 12 | redirections, cookies and more. |
| 13 | |
| 14 | The :mod:`urllib2` module defines the following functions: |
| 15 | |
| 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 |
| 26 | :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and |
| 27 | returns a string in this format. |
| 28 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 29 | The optional *timeout* parameter specifies a timeout in seconds for blocking |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame^] | 30 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 33 | |
| 34 | This function returns a file-like object with two additional methods: |
| 35 | |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 36 | * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to |
| 37 | determine if a redirect was followed |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 38 | |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 39 | * :meth:`info` --- return the meta-information of the page, such as headers, in |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 40 | the form of an ``http.client.HTTPMessage`` instance |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 41 | (see `Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 | |
| 43 | Raises :exc:`URLError` on errors. |
| 44 | |
| 45 | Note that ``None`` may be returned if no handler handles the request (though the |
| 46 | default installed global :class:`OpenerDirector` uses :class:`UnknownHandler` to |
| 47 | ensure this never happens). |
| 48 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | |
| 50 | .. function:: install_opener(opener) |
| 51 | |
| 52 | Install an :class:`OpenerDirector` instance as the default global opener. |
| 53 | Installing an opener is only necessary if you want urlopen to use that opener; |
| 54 | otherwise, simply call :meth:`OpenerDirector.open` instead of :func:`urlopen`. |
| 55 | The code does not check for a real :class:`OpenerDirector`, and any class with |
| 56 | the appropriate interface will work. |
| 57 | |
| 58 | |
| 59 | .. function:: build_opener([handler, ...]) |
| 60 | |
| 61 | Return an :class:`OpenerDirector` instance, which chains the handlers in the |
| 62 | order given. *handler*\s can be either instances of :class:`BaseHandler`, or |
| 63 | subclasses of :class:`BaseHandler` (in which case it must be possible to call |
| 64 | the constructor without any parameters). Instances of the following classes |
| 65 | will be in front of the *handler*\s, unless the *handler*\s contain them, |
| 66 | instances of them or subclasses of them: :class:`ProxyHandler`, |
| 67 | :class:`UnknownHandler`, :class:`HTTPHandler`, :class:`HTTPDefaultErrorHandler`, |
| 68 | :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`, |
| 69 | :class:`HTTPErrorProcessor`. |
| 70 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 71 | If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported), |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 72 | :class:`HTTPSHandler` will also be added. |
| 73 | |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 74 | A :class:`BaseHandler` subclass may also change its :attr:`handler_order` |
| 75 | member variable to modify its position in the handlers list. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 76 | |
| 77 | The following exceptions are raised as appropriate: |
| 78 | |
| 79 | |
| 80 | .. exception:: URLError |
| 81 | |
| 82 | The handlers raise this exception (or derived exceptions) when they run into a |
| 83 | problem. It is a subclass of :exc:`IOError`. |
| 84 | |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 85 | .. attribute:: reason |
| 86 | |
| 87 | The reason for this error. It can be a message string or another exception |
| 88 | instance (:exc:`socket.error` for remote URLs, :exc:`OSError` for local |
| 89 | URLs). |
| 90 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 91 | |
| 92 | .. exception:: HTTPError |
| 93 | |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 94 | Though being an exception (a subclass of :exc:`URLError`), an :exc:`HTTPError` |
| 95 | can also function as a non-exceptional file-like return value (the same thing |
| 96 | that :func:`urlopen` returns). This is useful when handling exotic HTTP |
| 97 | errors, such as requests for authentication. |
| 98 | |
| 99 | .. attribute:: code |
| 100 | |
| 101 | An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_. |
| 102 | This numeric value corresponds to a value found in the dictionary of |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 103 | codes as found in :attr:`http.server.BaseHTTPRequestHandler.responses`. |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 104 | |
| 105 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 106 | |
| 107 | The following classes are provided: |
| 108 | |
| 109 | |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 110 | .. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 111 | |
| 112 | This class is an abstraction of a URL request. |
| 113 | |
| 114 | *url* should be a string containing a valid URL. |
| 115 | |
| 116 | *data* may be a string specifying additional data to send to the server, or |
| 117 | ``None`` if no such data is needed. Currently HTTP requests are the only ones |
| 118 | that use *data*; the HTTP request will be a POST instead of a GET when the |
| 119 | *data* parameter is provided. *data* should be a buffer in the standard |
| 120 | :mimetype:`application/x-www-form-urlencoded` format. The |
| 121 | :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and |
| 122 | returns a string in this format. |
| 123 | |
| 124 | *headers* should be a dictionary, and will be treated as if :meth:`add_header` |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 125 | was called with each key and value as arguments. This is often used to "spoof" |
| 126 | the ``User-Agent`` header, which is used by a browser to identify itself -- |
| 127 | some HTTP servers only allow requests coming from common browsers as opposed |
| 128 | to scripts. For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0 |
| 129 | (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib2`'s |
| 130 | default user agent string is ``"Python-urllib/2.6"`` (on Python 2.6). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 131 | |
| 132 | The final two arguments are only of interest for correct handling of third-party |
| 133 | HTTP cookies: |
| 134 | |
| 135 | *origin_req_host* should be the request-host of the origin transaction, as |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 136 | defined by :rfc:`2965`. It defaults to ``http.cookiejar.request_host(self)``. |
| 137 | This is the host name or IP address of the original request that was |
| 138 | initiated by the user. For example, if the request is for an image in an |
| 139 | HTML document, this should be the request-host of the request for the page |
| 140 | containing the image. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 141 | |
| 142 | *unverifiable* should indicate whether the request is unverifiable, as defined |
| 143 | by RFC 2965. It defaults to False. An unverifiable request is one whose URL |
| 144 | the user did not have the option to approve. For example, if the request is for |
| 145 | an image in an HTML document, and the user had no option to approve the |
| 146 | automatic fetching of the image, this should be true. |
| 147 | |
| 148 | |
| 149 | .. class:: OpenerDirector() |
| 150 | |
| 151 | The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained |
| 152 | together. It manages the chaining of handlers, and recovery from errors. |
| 153 | |
| 154 | |
| 155 | .. class:: BaseHandler() |
| 156 | |
| 157 | This is the base class for all registered handlers --- and handles only the |
| 158 | simple mechanics of registration. |
| 159 | |
| 160 | |
| 161 | .. class:: HTTPDefaultErrorHandler() |
| 162 | |
| 163 | A class which defines a default handler for HTTP error responses; all responses |
| 164 | are turned into :exc:`HTTPError` exceptions. |
| 165 | |
| 166 | |
| 167 | .. class:: HTTPRedirectHandler() |
| 168 | |
| 169 | A class to handle redirections. |
| 170 | |
| 171 | |
| 172 | .. class:: HTTPCookieProcessor([cookiejar]) |
| 173 | |
| 174 | A class to handle HTTP Cookies. |
| 175 | |
| 176 | |
| 177 | .. class:: ProxyHandler([proxies]) |
| 178 | |
| 179 | Cause requests to go through a proxy. If *proxies* is given, it must be a |
| 180 | dictionary mapping protocol names to URLs of proxies. The default is to read the |
| 181 | list of proxies from the environment variables :envvar:`<protocol>_proxy`. |
Christian Heimes | e25f35e | 2008-03-20 10:49:03 +0000 | [diff] [blame] | 182 | To disable autodetected proxy pass an empty dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 183 | |
| 184 | |
| 185 | .. class:: HTTPPasswordMgr() |
| 186 | |
| 187 | Keep a database of ``(realm, uri) -> (user, password)`` mappings. |
| 188 | |
| 189 | |
| 190 | .. class:: HTTPPasswordMgrWithDefaultRealm() |
| 191 | |
| 192 | Keep a database of ``(realm, uri) -> (user, password)`` mappings. A realm of |
| 193 | ``None`` is considered a catch-all realm, which is searched if no other realm |
| 194 | fits. |
| 195 | |
| 196 | |
| 197 | .. class:: AbstractBasicAuthHandler([password_mgr]) |
| 198 | |
| 199 | This is a mixin class that helps with HTTP authentication, both to the remote |
| 200 | host and to a proxy. *password_mgr*, if given, should be something that is |
| 201 | compatible with :class:`HTTPPasswordMgr`; refer to section |
| 202 | :ref:`http-password-mgr` for information on the interface that must be |
| 203 | supported. |
| 204 | |
| 205 | |
| 206 | .. class:: HTTPBasicAuthHandler([password_mgr]) |
| 207 | |
| 208 | Handle authentication with the remote host. *password_mgr*, if given, should be |
| 209 | something that is compatible with :class:`HTTPPasswordMgr`; refer to section |
| 210 | :ref:`http-password-mgr` for information on the interface that must be |
| 211 | supported. |
| 212 | |
| 213 | |
| 214 | .. class:: ProxyBasicAuthHandler([password_mgr]) |
| 215 | |
| 216 | Handle authentication with the proxy. *password_mgr*, if given, should be |
| 217 | something that is compatible with :class:`HTTPPasswordMgr`; refer to section |
| 218 | :ref:`http-password-mgr` for information on the interface that must be |
| 219 | supported. |
| 220 | |
| 221 | |
| 222 | .. class:: AbstractDigestAuthHandler([password_mgr]) |
| 223 | |
| 224 | This is a mixin class that helps with HTTP authentication, both to the remote |
| 225 | host and to a proxy. *password_mgr*, if given, should be something that is |
| 226 | compatible with :class:`HTTPPasswordMgr`; refer to section |
| 227 | :ref:`http-password-mgr` for information on the interface that must be |
| 228 | supported. |
| 229 | |
| 230 | |
| 231 | .. class:: HTTPDigestAuthHandler([password_mgr]) |
| 232 | |
| 233 | Handle authentication with the remote host. *password_mgr*, if given, should be |
| 234 | something that is compatible with :class:`HTTPPasswordMgr`; refer to section |
| 235 | :ref:`http-password-mgr` for information on the interface that must be |
| 236 | supported. |
| 237 | |
| 238 | |
| 239 | .. class:: ProxyDigestAuthHandler([password_mgr]) |
| 240 | |
| 241 | Handle authentication with the proxy. *password_mgr*, if given, should be |
| 242 | something that is compatible with :class:`HTTPPasswordMgr`; refer to section |
| 243 | :ref:`http-password-mgr` for information on the interface that must be |
| 244 | supported. |
| 245 | |
| 246 | |
| 247 | .. class:: HTTPHandler() |
| 248 | |
| 249 | A class to handle opening of HTTP URLs. |
| 250 | |
| 251 | |
| 252 | .. class:: HTTPSHandler() |
| 253 | |
| 254 | A class to handle opening of HTTPS URLs. |
| 255 | |
| 256 | |
| 257 | .. class:: FileHandler() |
| 258 | |
| 259 | Open local files. |
| 260 | |
| 261 | |
| 262 | .. class:: FTPHandler() |
| 263 | |
| 264 | Open FTP URLs. |
| 265 | |
| 266 | |
| 267 | .. class:: CacheFTPHandler() |
| 268 | |
| 269 | Open FTP URLs, keeping a cache of open FTP connections to minimize delays. |
| 270 | |
| 271 | |
| 272 | .. class:: UnknownHandler() |
| 273 | |
| 274 | A catch-all class to handle unknown URLs. |
| 275 | |
| 276 | |
| 277 | .. _request-objects: |
| 278 | |
| 279 | Request Objects |
| 280 | --------------- |
| 281 | |
| 282 | The following methods describe all of :class:`Request`'s public interface, and |
| 283 | so all must be overridden in subclasses. |
| 284 | |
| 285 | |
| 286 | .. method:: Request.add_data(data) |
| 287 | |
| 288 | Set the :class:`Request` data to *data*. This is ignored by all handlers except |
| 289 | HTTP handlers --- and there it should be a byte string, and will change the |
| 290 | request to be ``POST`` rather than ``GET``. |
| 291 | |
| 292 | |
| 293 | .. method:: Request.get_method() |
| 294 | |
| 295 | Return a string indicating the HTTP request method. This is only meaningful for |
| 296 | HTTP requests, and currently always returns ``'GET'`` or ``'POST'``. |
| 297 | |
| 298 | |
| 299 | .. method:: Request.has_data() |
| 300 | |
| 301 | Return whether the instance has a non-\ ``None`` data. |
| 302 | |
| 303 | |
| 304 | .. method:: Request.get_data() |
| 305 | |
| 306 | Return the instance's data. |
| 307 | |
| 308 | |
| 309 | .. method:: Request.add_header(key, val) |
| 310 | |
| 311 | Add another header to the request. Headers are currently ignored by all |
| 312 | handlers except HTTP handlers, where they are added to the list of headers sent |
| 313 | to the server. Note that there cannot be more than one header with the same |
| 314 | name, and later calls will overwrite previous calls in case the *key* collides. |
| 315 | Currently, this is no loss of HTTP functionality, since all headers which have |
| 316 | meaning when used more than once have a (header-specific) way of gaining the |
| 317 | same functionality using only one header. |
| 318 | |
| 319 | |
| 320 | .. method:: Request.add_unredirected_header(key, header) |
| 321 | |
| 322 | Add a header that will not be added to a redirected request. |
| 323 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 324 | |
| 325 | .. method:: Request.has_header(header) |
| 326 | |
| 327 | Return whether the instance has the named header (checks both regular and |
| 328 | unredirected). |
| 329 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 330 | |
| 331 | .. method:: Request.get_full_url() |
| 332 | |
| 333 | Return the URL given in the constructor. |
| 334 | |
| 335 | |
| 336 | .. method:: Request.get_type() |
| 337 | |
| 338 | Return the type of the URL --- also known as the scheme. |
| 339 | |
| 340 | |
| 341 | .. method:: Request.get_host() |
| 342 | |
| 343 | Return the host to which a connection will be made. |
| 344 | |
| 345 | |
| 346 | .. method:: Request.get_selector() |
| 347 | |
| 348 | Return the selector --- the part of the URL that is sent to the server. |
| 349 | |
| 350 | |
| 351 | .. method:: Request.set_proxy(host, type) |
| 352 | |
| 353 | Prepare the request by connecting to a proxy server. The *host* and *type* will |
| 354 | replace those of the instance, and the instance's selector will be the original |
| 355 | URL given in the constructor. |
| 356 | |
| 357 | |
| 358 | .. method:: Request.get_origin_req_host() |
| 359 | |
| 360 | Return the request-host of the origin transaction, as defined by :rfc:`2965`. |
| 361 | See the documentation for the :class:`Request` constructor. |
| 362 | |
| 363 | |
| 364 | .. method:: Request.is_unverifiable() |
| 365 | |
| 366 | Return whether the request is unverifiable, as defined by RFC 2965. See the |
| 367 | documentation for the :class:`Request` constructor. |
| 368 | |
| 369 | |
| 370 | .. _opener-director-objects: |
| 371 | |
| 372 | OpenerDirector Objects |
| 373 | ---------------------- |
| 374 | |
| 375 | :class:`OpenerDirector` instances have the following methods: |
| 376 | |
| 377 | |
| 378 | .. method:: OpenerDirector.add_handler(handler) |
| 379 | |
| 380 | *handler* should be an instance of :class:`BaseHandler`. The following methods |
| 381 | are searched, and added to the possible chains (note that HTTP errors are a |
| 382 | special case). |
| 383 | |
| 384 | * :meth:`protocol_open` --- signal that the handler knows how to open *protocol* |
| 385 | URLs. |
| 386 | |
| 387 | * :meth:`http_error_type` --- signal that the handler knows how to handle HTTP |
| 388 | errors with HTTP error code *type*. |
| 389 | |
| 390 | * :meth:`protocol_error` --- signal that the handler knows how to handle errors |
| 391 | from (non-\ ``http``) *protocol*. |
| 392 | |
| 393 | * :meth:`protocol_request` --- signal that the handler knows how to pre-process |
| 394 | *protocol* requests. |
| 395 | |
| 396 | * :meth:`protocol_response` --- signal that the handler knows how to |
| 397 | post-process *protocol* responses. |
| 398 | |
| 399 | |
| 400 | .. method:: OpenerDirector.open(url[, data][, timeout]) |
| 401 | |
| 402 | Open the given *url* (which can be a request object or a string), optionally |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 403 | passing the given *data*. Arguments, return values and exceptions raised are |
| 404 | the same as those of :func:`urlopen` (which simply calls the :meth:`open` |
| 405 | method on the currently installed global :class:`OpenerDirector`). The |
| 406 | optional *timeout* parameter specifies a timeout in seconds for blocking |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame^] | 407 | operations like the connection attempt (if not specified, the global default |
| 408 | timeout setting will be usedi). The timeout feature actually works only for |
| 409 | HTTP, HTTPS, FTP and FTPS connections). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 410 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 411 | |
| 412 | .. method:: OpenerDirector.error(proto[, arg[, ...]]) |
| 413 | |
| 414 | Handle an error of the given protocol. This will call the registered error |
| 415 | handlers for the given protocol with the given arguments (which are protocol |
| 416 | specific). The HTTP protocol is a special case which uses the HTTP response |
| 417 | code to determine the specific error handler; refer to the :meth:`http_error_\*` |
| 418 | methods of the handler classes. |
| 419 | |
| 420 | Return values and exceptions raised are the same as those of :func:`urlopen`. |
| 421 | |
| 422 | OpenerDirector objects open URLs in three stages: |
| 423 | |
| 424 | The order in which these methods are called within each stage is determined by |
| 425 | sorting the handler instances. |
| 426 | |
| 427 | #. Every handler with a method named like :meth:`protocol_request` has that |
| 428 | method called to pre-process the request. |
| 429 | |
| 430 | #. Handlers with a method named like :meth:`protocol_open` are called to handle |
| 431 | the request. This stage ends when a handler either returns a non-\ :const:`None` |
| 432 | value (ie. a response), or raises an exception (usually :exc:`URLError`). |
| 433 | Exceptions are allowed to propagate. |
| 434 | |
| 435 | In fact, the above algorithm is first tried for methods named |
| 436 | :meth:`default_open`. If all such methods return :const:`None`, the algorithm |
| 437 | is repeated for methods named like :meth:`protocol_open`. If all such methods |
| 438 | return :const:`None`, the algorithm is repeated for methods named |
| 439 | :meth:`unknown_open`. |
| 440 | |
| 441 | Note that the implementation of these methods may involve calls of the parent |
| 442 | :class:`OpenerDirector` instance's :meth:`.open` and :meth:`.error` methods. |
| 443 | |
| 444 | #. Every handler with a method named like :meth:`protocol_response` has that |
| 445 | method called to post-process the response. |
| 446 | |
| 447 | |
| 448 | .. _base-handler-objects: |
| 449 | |
| 450 | BaseHandler Objects |
| 451 | ------------------- |
| 452 | |
| 453 | :class:`BaseHandler` objects provide a couple of methods that are directly |
| 454 | useful, and others that are meant to be used by derived classes. These are |
| 455 | intended for direct use: |
| 456 | |
| 457 | |
| 458 | .. method:: BaseHandler.add_parent(director) |
| 459 | |
| 460 | Add a director as parent. |
| 461 | |
| 462 | |
| 463 | .. method:: BaseHandler.close() |
| 464 | |
| 465 | Remove any parents. |
| 466 | |
| 467 | The following members and methods should only be used by classes derived from |
| 468 | :class:`BaseHandler`. |
| 469 | |
| 470 | .. note:: |
| 471 | |
| 472 | The convention has been adopted that subclasses defining |
| 473 | :meth:`protocol_request` or :meth:`protocol_response` methods are named |
| 474 | :class:`\*Processor`; all others are named :class:`\*Handler`. |
| 475 | |
| 476 | |
| 477 | .. attribute:: BaseHandler.parent |
| 478 | |
| 479 | A valid :class:`OpenerDirector`, which can be used to open using a different |
| 480 | protocol, or handle errors. |
| 481 | |
| 482 | |
| 483 | .. method:: BaseHandler.default_open(req) |
| 484 | |
| 485 | This method is *not* defined in :class:`BaseHandler`, but subclasses should |
| 486 | define it if they want to catch all URLs. |
| 487 | |
| 488 | This method, if implemented, will be called by the parent |
| 489 | :class:`OpenerDirector`. It should return a file-like object as described in |
| 490 | the return value of the :meth:`open` of :class:`OpenerDirector`, or ``None``. |
| 491 | It should raise :exc:`URLError`, unless a truly exceptional thing happens (for |
| 492 | example, :exc:`MemoryError` should not be mapped to :exc:`URLError`). |
| 493 | |
| 494 | This method will be called before any protocol-specific open method. |
| 495 | |
| 496 | |
| 497 | .. method:: BaseHandler.protocol_open(req) |
| 498 | :noindex: |
| 499 | |
| 500 | This method is *not* defined in :class:`BaseHandler`, but subclasses should |
| 501 | define it if they want to handle URLs with the given protocol. |
| 502 | |
| 503 | This method, if defined, will be called by the parent :class:`OpenerDirector`. |
| 504 | Return values should be the same as for :meth:`default_open`. |
| 505 | |
| 506 | |
| 507 | .. method:: BaseHandler.unknown_open(req) |
| 508 | |
| 509 | This method is *not* defined in :class:`BaseHandler`, but subclasses should |
| 510 | define it if they want to catch all URLs with no specific registered handler to |
| 511 | open it. |
| 512 | |
| 513 | This method, if implemented, will be called by the :attr:`parent` |
| 514 | :class:`OpenerDirector`. Return values should be the same as for |
| 515 | :meth:`default_open`. |
| 516 | |
| 517 | |
| 518 | .. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs) |
| 519 | |
| 520 | This method is *not* defined in :class:`BaseHandler`, but subclasses should |
| 521 | override it if they intend to provide a catch-all for otherwise unhandled HTTP |
| 522 | errors. It will be called automatically by the :class:`OpenerDirector` getting |
| 523 | the error, and should not normally be called in other circumstances. |
| 524 | |
| 525 | *req* will be a :class:`Request` object, *fp* will be a file-like object with |
| 526 | the HTTP error body, *code* will be the three-digit code of the error, *msg* |
| 527 | will be the user-visible explanation of the code and *hdrs* will be a mapping |
| 528 | object with the headers of the error. |
| 529 | |
| 530 | Return values and exceptions raised should be the same as those of |
| 531 | :func:`urlopen`. |
| 532 | |
| 533 | |
| 534 | .. method:: BaseHandler.http_error_nnn(req, fp, code, msg, hdrs) |
| 535 | |
| 536 | *nnn* should be a three-digit HTTP error code. This method is also not defined |
| 537 | in :class:`BaseHandler`, but will be called, if it exists, on an instance of a |
| 538 | subclass, when an HTTP error with code *nnn* occurs. |
| 539 | |
| 540 | Subclasses should override this method to handle specific HTTP errors. |
| 541 | |
| 542 | Arguments, return values and exceptions raised should be the same as for |
| 543 | :meth:`http_error_default`. |
| 544 | |
| 545 | |
| 546 | .. method:: BaseHandler.protocol_request(req) |
| 547 | :noindex: |
| 548 | |
| 549 | This method is *not* defined in :class:`BaseHandler`, but subclasses should |
| 550 | define it if they want to pre-process requests of the given protocol. |
| 551 | |
| 552 | This method, if defined, will be called by the parent :class:`OpenerDirector`. |
| 553 | *req* will be a :class:`Request` object. The return value should be a |
| 554 | :class:`Request` object. |
| 555 | |
| 556 | |
| 557 | .. method:: BaseHandler.protocol_response(req, response) |
| 558 | :noindex: |
| 559 | |
| 560 | This method is *not* defined in :class:`BaseHandler`, but subclasses should |
| 561 | define it if they want to post-process responses of the given protocol. |
| 562 | |
| 563 | This method, if defined, will be called by the parent :class:`OpenerDirector`. |
| 564 | *req* will be a :class:`Request` object. *response* will be an object |
| 565 | implementing the same interface as the return value of :func:`urlopen`. The |
| 566 | return value should implement the same interface as the return value of |
| 567 | :func:`urlopen`. |
| 568 | |
| 569 | |
| 570 | .. _http-redirect-handler: |
| 571 | |
| 572 | HTTPRedirectHandler Objects |
| 573 | --------------------------- |
| 574 | |
| 575 | .. note:: |
| 576 | |
| 577 | Some HTTP redirections require action from this module's client code. If this |
| 578 | is the case, :exc:`HTTPError` is raised. See :rfc:`2616` for details of the |
| 579 | precise meanings of the various redirection codes. |
| 580 | |
| 581 | |
| 582 | .. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs) |
| 583 | |
| 584 | Return a :class:`Request` or ``None`` in response to a redirect. This is called |
| 585 | by the default implementations of the :meth:`http_error_30\*` methods when a |
| 586 | redirection is received from the server. If a redirection should take place, |
| 587 | return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the |
| 588 | redirect. Otherwise, raise :exc:`HTTPError` if no other handler should try to |
| 589 | handle this URL, or return ``None`` if you can't but another handler might. |
| 590 | |
| 591 | .. note:: |
| 592 | |
| 593 | The default implementation of this method does not strictly follow :rfc:`2616`, |
| 594 | which says that 301 and 302 responses to ``POST`` requests must not be |
| 595 | automatically redirected without confirmation by the user. In reality, browsers |
| 596 | do allow automatic redirection of these responses, changing the POST to a |
| 597 | ``GET``, and the default implementation reproduces this behavior. |
| 598 | |
| 599 | |
| 600 | .. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs) |
| 601 | |
| 602 | Redirect to the ``Location:`` URL. This method is called by the parent |
| 603 | :class:`OpenerDirector` when getting an HTTP 'moved permanently' response. |
| 604 | |
| 605 | |
| 606 | .. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs) |
| 607 | |
| 608 | The same as :meth:`http_error_301`, but called for the 'found' response. |
| 609 | |
| 610 | |
| 611 | .. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs) |
| 612 | |
| 613 | The same as :meth:`http_error_301`, but called for the 'see other' response. |
| 614 | |
| 615 | |
| 616 | .. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs) |
| 617 | |
| 618 | The same as :meth:`http_error_301`, but called for the 'temporary redirect' |
| 619 | response. |
| 620 | |
| 621 | |
| 622 | .. _http-cookie-processor: |
| 623 | |
| 624 | HTTPCookieProcessor Objects |
| 625 | --------------------------- |
| 626 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 627 | :class:`HTTPCookieProcessor` instances have one attribute: |
| 628 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 629 | .. attribute:: HTTPCookieProcessor.cookiejar |
| 630 | |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 631 | The :class:`http.cookiejar.CookieJar` in which cookies are stored. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 632 | |
| 633 | |
| 634 | .. _proxy-handler: |
| 635 | |
| 636 | ProxyHandler Objects |
| 637 | -------------------- |
| 638 | |
| 639 | |
| 640 | .. method:: ProxyHandler.protocol_open(request) |
| 641 | :noindex: |
| 642 | |
| 643 | The :class:`ProxyHandler` will have a method :meth:`protocol_open` for every |
| 644 | *protocol* which has a proxy in the *proxies* dictionary given in the |
| 645 | constructor. The method will modify requests to go through the proxy, by |
| 646 | calling ``request.set_proxy()``, and call the next handler in the chain to |
| 647 | actually execute the protocol. |
| 648 | |
| 649 | |
| 650 | .. _http-password-mgr: |
| 651 | |
| 652 | HTTPPasswordMgr Objects |
| 653 | ----------------------- |
| 654 | |
| 655 | These methods are available on :class:`HTTPPasswordMgr` and |
| 656 | :class:`HTTPPasswordMgrWithDefaultRealm` objects. |
| 657 | |
| 658 | |
| 659 | .. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd) |
| 660 | |
| 661 | *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and |
| 662 | *passwd* must be strings. This causes ``(user, passwd)`` to be used as |
| 663 | authentication tokens when authentication for *realm* and a super-URI of any of |
| 664 | the given URIs is given. |
| 665 | |
| 666 | |
| 667 | .. method:: HTTPPasswordMgr.find_user_password(realm, authuri) |
| 668 | |
| 669 | Get user/password for given realm and URI, if any. This method will return |
| 670 | ``(None, None)`` if there is no matching user/password. |
| 671 | |
| 672 | For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be |
| 673 | searched if the given *realm* has no matching user/password. |
| 674 | |
| 675 | |
| 676 | .. _abstract-basic-auth-handler: |
| 677 | |
| 678 | AbstractBasicAuthHandler Objects |
| 679 | -------------------------------- |
| 680 | |
| 681 | |
| 682 | .. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers) |
| 683 | |
| 684 | Handle an authentication request by getting a user/password pair, and re-trying |
| 685 | the request. *authreq* should be the name of the header where the information |
| 686 | about the realm is included in the request, *host* specifies the URL and path to |
| 687 | authenticate for, *req* should be the (failed) :class:`Request` object, and |
| 688 | *headers* should be the error headers. |
| 689 | |
| 690 | *host* is either an authority (e.g. ``"python.org"``) or a URL containing an |
| 691 | authority component (e.g. ``"http://python.org/"``). In either case, the |
| 692 | authority must not contain a userinfo component (so, ``"python.org"`` and |
| 693 | ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not). |
| 694 | |
| 695 | |
| 696 | .. _http-basic-auth-handler: |
| 697 | |
| 698 | HTTPBasicAuthHandler Objects |
| 699 | ---------------------------- |
| 700 | |
| 701 | |
| 702 | .. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs) |
| 703 | |
| 704 | Retry the request with authentication information, if available. |
| 705 | |
| 706 | |
| 707 | .. _proxy-basic-auth-handler: |
| 708 | |
| 709 | ProxyBasicAuthHandler Objects |
| 710 | ----------------------------- |
| 711 | |
| 712 | |
| 713 | .. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs) |
| 714 | |
| 715 | Retry the request with authentication information, if available. |
| 716 | |
| 717 | |
| 718 | .. _abstract-digest-auth-handler: |
| 719 | |
| 720 | AbstractDigestAuthHandler Objects |
| 721 | --------------------------------- |
| 722 | |
| 723 | |
| 724 | .. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers) |
| 725 | |
| 726 | *authreq* should be the name of the header where the information about the realm |
| 727 | is included in the request, *host* should be the host to authenticate to, *req* |
| 728 | should be the (failed) :class:`Request` object, and *headers* should be the |
| 729 | error headers. |
| 730 | |
| 731 | |
| 732 | .. _http-digest-auth-handler: |
| 733 | |
| 734 | HTTPDigestAuthHandler Objects |
| 735 | ----------------------------- |
| 736 | |
| 737 | |
| 738 | .. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs) |
| 739 | |
| 740 | Retry the request with authentication information, if available. |
| 741 | |
| 742 | |
| 743 | .. _proxy-digest-auth-handler: |
| 744 | |
| 745 | ProxyDigestAuthHandler Objects |
| 746 | ------------------------------ |
| 747 | |
| 748 | |
| 749 | .. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs) |
| 750 | |
| 751 | Retry the request with authentication information, if available. |
| 752 | |
| 753 | |
| 754 | .. _http-handler-objects: |
| 755 | |
| 756 | HTTPHandler Objects |
| 757 | ------------------- |
| 758 | |
| 759 | |
| 760 | .. method:: HTTPHandler.http_open(req) |
| 761 | |
| 762 | Send an HTTP request, which can be either GET or POST, depending on |
| 763 | ``req.has_data()``. |
| 764 | |
| 765 | |
| 766 | .. _https-handler-objects: |
| 767 | |
| 768 | HTTPSHandler Objects |
| 769 | -------------------- |
| 770 | |
| 771 | |
| 772 | .. method:: HTTPSHandler.https_open(req) |
| 773 | |
| 774 | Send an HTTPS request, which can be either GET or POST, depending on |
| 775 | ``req.has_data()``. |
| 776 | |
| 777 | |
| 778 | .. _file-handler-objects: |
| 779 | |
| 780 | FileHandler Objects |
| 781 | ------------------- |
| 782 | |
| 783 | |
| 784 | .. method:: FileHandler.file_open(req) |
| 785 | |
| 786 | Open the file locally, if there is no host name, or the host name is |
| 787 | ``'localhost'``. Change the protocol to ``ftp`` otherwise, and retry opening it |
| 788 | using :attr:`parent`. |
| 789 | |
| 790 | |
| 791 | .. _ftp-handler-objects: |
| 792 | |
| 793 | FTPHandler Objects |
| 794 | ------------------ |
| 795 | |
| 796 | |
| 797 | .. method:: FTPHandler.ftp_open(req) |
| 798 | |
| 799 | Open the FTP file indicated by *req*. The login is always done with empty |
| 800 | username and password. |
| 801 | |
| 802 | |
| 803 | .. _cacheftp-handler-objects: |
| 804 | |
| 805 | CacheFTPHandler Objects |
| 806 | ----------------------- |
| 807 | |
| 808 | :class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the |
| 809 | following additional methods: |
| 810 | |
| 811 | |
| 812 | .. method:: CacheFTPHandler.setTimeout(t) |
| 813 | |
| 814 | Set timeout of connections to *t* seconds. |
| 815 | |
| 816 | |
| 817 | .. method:: CacheFTPHandler.setMaxConns(m) |
| 818 | |
| 819 | Set maximum number of cached connections to *m*. |
| 820 | |
| 821 | |
| 822 | .. _unknown-handler-objects: |
| 823 | |
| 824 | UnknownHandler Objects |
| 825 | ---------------------- |
| 826 | |
| 827 | |
| 828 | .. method:: UnknownHandler.unknown_open() |
| 829 | |
| 830 | Raise a :exc:`URLError` exception. |
| 831 | |
| 832 | |
| 833 | .. _http-error-processor-objects: |
| 834 | |
| 835 | HTTPErrorProcessor Objects |
| 836 | -------------------------- |
| 837 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 838 | .. method:: HTTPErrorProcessor.unknown_open() |
| 839 | |
| 840 | Process HTTP error responses. |
| 841 | |
| 842 | For 200 error codes, the response object is returned immediately. |
| 843 | |
| 844 | For non-200 error codes, this simply passes the job on to the |
| 845 | :meth:`protocol_error_code` handler methods, via :meth:`OpenerDirector.error`. |
| 846 | Eventually, :class:`urllib2.HTTPDefaultErrorHandler` will raise an |
| 847 | :exc:`HTTPError` if no other handler handles the error. |
| 848 | |
| 849 | |
| 850 | .. _urllib2-examples: |
| 851 | |
| 852 | Examples |
| 853 | -------- |
| 854 | |
| 855 | This example gets the python.org main page and displays the first 100 bytes of |
| 856 | it:: |
| 857 | |
| 858 | >>> import urllib2 |
| 859 | >>> f = urllib2.urlopen('http://www.python.org/') |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 860 | >>> print(f.read(100)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 861 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> |
| 862 | <?xml-stylesheet href="./css/ht2html |
| 863 | |
| 864 | Here we are sending a data-stream to the stdin of a CGI and reading the data it |
| 865 | returns to us. Note that this example will only work when the Python |
| 866 | installation supports SSL. :: |
| 867 | |
| 868 | >>> import urllib2 |
| 869 | >>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi', |
| 870 | ... data='This data is passed to stdin of the CGI') |
| 871 | >>> f = urllib2.urlopen(req) |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 872 | >>> print(f.read()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 873 | Got Data: "This data is passed to stdin of the CGI" |
| 874 | |
| 875 | The code for the sample CGI used in the above example is:: |
| 876 | |
| 877 | #!/usr/bin/env python |
| 878 | import sys |
| 879 | data = sys.stdin.read() |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 880 | print('Content-type: text-plain\n\nGot Data: "%s"' % data) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 881 | |
| 882 | Use of Basic HTTP Authentication:: |
| 883 | |
| 884 | import urllib2 |
| 885 | # Create an OpenerDirector with support for Basic HTTP Authentication... |
| 886 | auth_handler = urllib2.HTTPBasicAuthHandler() |
| 887 | auth_handler.add_password(realm='PDQ Application', |
| 888 | uri='https://mahler:8092/site-updates.py', |
| 889 | user='klem', |
| 890 | passwd='kadidd!ehopper') |
| 891 | opener = urllib2.build_opener(auth_handler) |
| 892 | # ...and install it globally so it can be used with urlopen. |
| 893 | urllib2.install_opener(opener) |
| 894 | urllib2.urlopen('http://www.example.com/login.html') |
| 895 | |
| 896 | :func:`build_opener` provides many handlers by default, including a |
| 897 | :class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment |
| 898 | variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme |
| 899 | involved. For example, the :envvar:`http_proxy` environment variable is read to |
| 900 | obtain the HTTP proxy's URL. |
| 901 | |
| 902 | This example replaces the default :class:`ProxyHandler` with one that uses |
| 903 | programatically-supplied proxy URLs, and adds proxy authorization support with |
| 904 | :class:`ProxyBasicAuthHandler`. :: |
| 905 | |
| 906 | proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'}) |
| 907 | proxy_auth_handler = urllib2.HTTPBasicAuthHandler() |
| 908 | proxy_auth_handler.add_password('realm', 'host', 'username', 'password') |
| 909 | |
| 910 | opener = build_opener(proxy_handler, proxy_auth_handler) |
| 911 | # This time, rather than install the OpenerDirector, we use it directly: |
| 912 | opener.open('http://www.example.com/login.html') |
| 913 | |
| 914 | Adding HTTP headers: |
| 915 | |
| 916 | Use the *headers* argument to the :class:`Request` constructor, or:: |
| 917 | |
| 918 | import urllib2 |
| 919 | req = urllib2.Request('http://www.example.com/') |
| 920 | req.add_header('Referer', 'http://www.python.org/') |
| 921 | r = urllib2.urlopen(req) |
| 922 | |
| 923 | :class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to |
| 924 | every :class:`Request`. To change this:: |
| 925 | |
| 926 | import urllib2 |
| 927 | opener = urllib2.build_opener() |
| 928 | opener.addheaders = [('User-agent', 'Mozilla/5.0')] |
| 929 | opener.open('http://www.example.com/') |
| 930 | |
| 931 | Also, remember that a few standard headers (:mailheader:`Content-Length`, |
| 932 | :mailheader:`Content-Type` and :mailheader:`Host`) are added when the |
| 933 | :class:`Request` is passed to :func:`urlopen` (or :meth:`OpenerDirector.open`). |
| 934 | |