Debian Codegraph @

mechanize/_useragent.py

raw symbols SCIP
1 """Convenient HTTP UserAgent class.
2
3 This is a subclass of urllib2.OpenerDirector.
4
5
6 Copyright 2003-2006 John J. Lee <[email protected]>
7
8 This code is free software; you can redistribute it and/or modify it under
9 the terms of the BSD or ZPL 2.1 licenses (see the file LICENSE
10 included with the distribution).
11
12 """
13
14 from __future__ import absolute_import
15
16 import copy
17
18 from . import _auth, _gzip, _opener, _response, _sockettimeout, _urllib2
19 from .polyglot import iteritems, itervalues
20
21
22 class UserAgentBase(_opener.OpenerDirector):
23 """Convenient user-agent class.
24
25 Do not use .add_handler() to add a handler for something already dealt with
26 by this code.
27
28 The only reason at present for the distinction between UserAgent and
29 UserAgentBase is so that classes that depend on .seek()able responses
30 (e.g. mechanize.Browser) can inherit from UserAgentBase. The subclass
31 UserAgent exposes a .set_seekable_responses() method that allows switching
32 off the adding of a .seek() method to responses.
33
34 Public attributes:
35
36 addheaders: list of (name, value) pairs specifying headers to send with
37 every request, unless they are overridden in the Request instance.
38
39 >>> ua = UserAgentBase()
40 >>> ua.addheaders = [
41 ... ("User-agent", "Mozilla/5.0 (compatible)"),
42 ... ("From", "[email protected]")]
43
44 """
45
46 handler_classes = {
47 # scheme handlers
48 "http": _urllib2.HTTPHandler,
49 # CacheFTPHandler is buggy, at least in 2.3, so we don't use it
50 "ftp": _urllib2.FTPHandler,
51 "file": _urllib2.FileHandler,
52
53 # other handlers
54 "_unknown": _urllib2.UnknownHandler,
55 # HTTP{S,}Handler depend on HTTPErrorProcessor too
56 "_http_error": _urllib2.HTTPErrorProcessor,
57 "_http_default_error": _urllib2.HTTPDefaultErrorHandler,
58
59 # feature handlers
60 "_basicauth": _urllib2.HTTPBasicAuthHandler,
61 "_digestauth": _urllib2.HTTPDigestAuthHandler,
62 "_redirect": _urllib2.HTTPRedirectHandler,
63 "_cookies": _urllib2.HTTPCookieProcessor,
64 "_refresh": _urllib2.HTTPRefreshProcessor,
65 "_equiv": _urllib2.HTTPEquivProcessor,
66 "_proxy": _urllib2.ProxyHandler,
67 "_proxy_basicauth": _urllib2.ProxyBasicAuthHandler,
68 "_proxy_digestauth": _urllib2.ProxyDigestAuthHandler,
69 "_robots": _urllib2.HTTPRobotRulesProcessor,
70 "_gzip": _gzip.HTTPGzipProcessor,
71
72 # debug handlers
73 "_debug_redirect": _urllib2.HTTPRedirectDebugProcessor,
74 "_debug_response_body": _urllib2.HTTPResponseDebugProcessor,
75 }
76
77 default_schemes = ["http", "ftp", "file"]
78 default_others = ["_unknown", "_http_error", "_http_default_error"]
79 default_features = [
80 "_gzip",
81 "_redirect",
82 "_cookies",
83 "_refresh",
84 "_equiv",
85 "_basicauth",
86 "_digestauth",
87 "_proxy",
88 "_proxy_basicauth",
89 "_proxy_digestauth",
90 "_robots",
91 ]
92 if hasattr(_urllib2, 'HTTPSHandler'):
93 handler_classes["https"] = _urllib2.HTTPSHandler
94 default_schemes.append("https")
95
96 def __init__(self):
97 _opener.OpenerDirector.__init__(self)
98
99 ua_handlers = self._ua_handlers = {}
100 for scheme in (self.default_schemes + self.default_others +
101 self.default_features):
102 klass = self.handler_classes[scheme]
103 ua_handlers[scheme] = klass()
104 for handler in tuple(itervalues(ua_handlers)):
105 self.add_handler(handler)
106
107 # Yuck.
108 # Ensure correct default constructor args were passed to
109 # HTTPRefreshProcessor and HTTPEquivProcessor.
110 if "_refresh" in ua_handlers:
111 self.set_handle_refresh(True)
112 if "_equiv" in ua_handlers:
113 self.set_handle_equiv(True)
114 # Ensure default password managers are installed.
115 pm = ppm = None
116 if "_basicauth" in ua_handlers or "_digestauth" in ua_handlers:
117 pm = _urllib2.HTTPPasswordMgrWithDefaultRealm()
118 if ("_proxy_basicauth" in ua_handlers or
119 "_proxy_digestauth" in ua_handlers):
120 ppm = _auth.HTTPProxyPasswordMgr()
121 self.set_password_manager(pm)
122 self.set_proxy_password_manager(ppm)
123 # set default certificate manager
124 if "https" in ua_handlers:
125 cm = _urllib2.HTTPSClientCertMgr()
126 self.set_client_cert_manager(cm)
127
128 def close(self):
129 _opener.OpenerDirector.close(self)
130 self._ua_handlers = None
131
132 # XXX
133 # def set_timeout(self, timeout):
134 # self._timeout = timeout
135 # def set_http_connection_cache(self, conn_cache):
136 # self._http_conn_cache = conn_cache
137 # def set_ftp_connection_cache(self, conn_cache):
138 # XXX ATM, FTP has cache as part of handler; should it be separate?
139 # self._ftp_conn_cache = conn_cache
140
141 def set_handled_schemes(self, schemes):
142 """Set sequence of URL scheme (protocol) strings.
143
144 For example: ua.set_handled_schemes(["http", "ftp"])
145
146 If this fails (with ValueError) because you've passed an unknown
147 scheme, the set of handled schemes will not be changed.
148
149 """
150 want = {}
151 for scheme in schemes:
152 if scheme.startswith("_"):
153 raise ValueError("not a scheme '%s'" % scheme)
154 if scheme not in self.handler_classes:
155 raise ValueError("unknown scheme '%s'")
156 want[scheme] = None
157
158 # get rid of scheme handlers we don't want
159 for scheme, oldhandler in tuple(iteritems(self._ua_handlers)):
160 if scheme.startswith("_"):
161 continue # not a scheme handler
162 if scheme not in want:
163 self._replace_handler(scheme, None)
164 else:
165 del want[scheme] # already got it
166 # add the scheme handlers that are missing
167 for scheme in want:
168 self._set_handler(scheme, True)
169
170 def set_cookiejar(self, cookiejar):
171 """Set a mechanize.CookieJar, or None."""
172 self._set_handler("_cookies", obj=cookiejar)
173
174 # XXX could use Greg Stein's httpx for some of this instead?
175 # or httplib2??
176 def set_proxies(self, proxies=None, proxy_bypass=None):
177 """Configure proxy settings.
178
179 :arg proxies: dictionary mapping URL scheme to proxy specification.
180 None means use the default system-specific settings.
181 :arg proxy_bypass: function taking hostname, returning whether proxy
182 should be used. None means use the default system-specific settings.
183
184 The default is to try to obtain proxy settings from the system (see the
185 documentation for urllib.urlopen for information about the
186 system-specific methods used -- note that's urllib, not urllib2).
187
188 To avoid all use of proxies, pass an empty proxies dict.
189
190 >>> ua = UserAgentBase()
191 >>> def proxy_bypass(hostname):
192 ... return hostname == "noproxy.com"
193 >>> ua.set_proxies(
194 ... {"http": "joe:[email protected]:3128",
195 ... "ftp": "proxy.example.com"},
196 ... proxy_bypass)
197
198 """
199 self._set_handler(
200 "_proxy",
201 True,
202 constructor_kwds=dict(proxies=proxies, proxy_bypass=proxy_bypass))
203
204 def add_password(self, url, user, password, realm=None):
205 self._password_manager.add_password(realm, url, user, password)
206
207 def add_proxy_password(self, user, password, hostport=None, realm=None):
208 self._proxy_password_manager.add_password(realm, hostport, user,
209 password)
210
211 def add_client_certificate(self, url, key_file, cert_file):
212 """Add an SSL client certificate, for HTTPS client auth.
213
214 key_file and cert_file must be filenames of the key and certificate
215 files, in PEM format. You can use e.g. OpenSSL to convert a p12 (PKCS
216 12) file to PEM format:
217
218 openssl pkcs12 -clcerts -nokeys -in cert.p12 -out cert.pem
219 openssl pkcs12 -nocerts -in cert.p12 -out key.pem
220
221
222 Note that client certificate password input is very inflexible ATM. At
223 the moment this seems to be console only, which is presumably the
224 default behaviour of libopenssl. In future mechanize may support
225 third-party libraries that (I assume) allow more options here.
226
227 """
228 self._client_cert_manager.add_key_cert(url, key_file, cert_file)
229
230 # the following are rarely useful -- use add_password / add_proxy_password
231 # instead
232 def set_password_manager(self, password_manager):
233 """Set a mechanize.HTTPPasswordMgrWithDefaultRealm, or None."""
234 self._password_manager = password_manager
235 self._set_handler("_basicauth", obj=password_manager)
236 self._set_handler("_digestauth", obj=password_manager)
237
238 def set_proxy_password_manager(self, password_manager):
239 """Set a mechanize.HTTPProxyPasswordMgr, or None."""
240 self._proxy_password_manager = password_manager
241 self._set_handler("_proxy_basicauth", obj=password_manager)
242 self._set_handler("_proxy_digestauth", obj=password_manager)
243
244 def set_client_cert_manager(self, cert_manager):
245 """Set a mechanize.HTTPClientCertMgr, or None."""
246 handler = self._ua_handlers["https"]
247 self._client_cert_manager = handler.client_cert_manager = cert_manager
248
249 def set_ca_data(self, cafile=None, capath=None, cadata=None, context=None):
250 '''
251 Set the SSL Context used for connecting to SSL servers.
252
253 This method accepts the same arguments as the
254 :py:meth:`ssl.SSLContext.load_verify_locations()` method from
255 the Python standard library. You can also pass a pre-built
256 :class:`ssl.SSLContext` via the `context` keyword argument.
257 Note that to use this feature, you must be using Python >=
258 2.7.9.
259
260 '''
261 import ssl
262 if context is None:
263 try:
264 context = ssl.create_default_context(
265 cafile=cafile, capath=capath, cadata=cadata)
266 except AttributeError:
267 raise RuntimeError('python >= 2.7.9 required')
268 handler = self._ua_handlers["https"]
269 handler.ssl_context = context
270
271 # these methods all take a boolean parameter
272 def set_handle_robots(self, handle):
273 """Set whether to observe rules from robots.txt."""
274 self._set_handler("_robots", handle)
275
276 def set_handle_redirect(self, handle):
277 """Set whether to handle HTTP 30x redirections."""
278 self._set_handler("_redirect", handle)
279
280 def set_handle_refresh(self, handle, max_time=None, honor_time=True):
281 """Set whether to handle HTTP Refresh headers."""
282 self._set_handler(
283 "_refresh",
284 handle,
285 constructor_kwds={"max_time": max_time,
286 "honor_time": honor_time})
287
288 def set_handle_equiv(self, handle, head_parser_class=None):
289 """Set whether to treat HTML http-equiv headers like HTTP headers.
290
291 Response objects may be .seek()able if this is set (currently returned
292 responses are, raised HTTPError exception responses are not).
293
294 """
295 if head_parser_class is not None:
296 constructor_kwds = {"head_parser_class": head_parser_class}
297 else:
298 constructor_kwds = {}
299 self._set_handler("_equiv", handle, constructor_kwds=constructor_kwds)
300
301 def set_request_gzip(self, handle):
302 """Add header indicating to server that we handle gzip
303 content encoding. Note that if the server sends gzip'ed content,
304 it is handled automatically in any case, regardless of this setting.
305
306 """
307 self._set_handler(
308 "_gzip", True, constructor_kwds={'request_gzip': bool(handle)})
309 set_handle_gzip = set_request_gzip # legacy
310
311 def set_debug_redirects(self, handle):
312 """
313 Log information about HTTP redirects (including refreshes).
314
315 Logging is performed using module logging. The logger name is
316 `"mechanize.http_redirects"`. To actually print some debug output,
317 eg:
318
319 .. code-block:: python
320
321 import sys, logging
322 logger = logging.getLogger("mechanize.http_redirects")
323 logger.addHandler(logging.StreamHandler(sys.stdout))
324 logger.setLevel(logging.INFO)
325
326 Other logger names relevant to this module:
327
328 * `mechanize.http_responses`
329 * `mechanize.cookies`
330
331 To turn on everything:
332
333 .. code-block:: python
334
335 import sys, logging
336 logger = logging.getLogger("mechanize")
337 logger.addHandler(logging.StreamHandler(sys.stdout))
338 logger.setLevel(logging.INFO)
339
340 """
341 self._set_handler("_debug_redirect", handle)
342
343 def set_debug_responses(self, handle):
344 """Log HTTP response bodies.
345
346 See :meth:`set_debug_redirects()` for details of logging.
347
348 Response objects may be .seek()able if this is set (currently returned
349 responses are, raised HTTPError exception responses are not).
350
351 """
352 self._set_handler("_debug_response_body", handle)
353
354 def set_debug_http(self, handle):
355 """Print HTTP headers to sys.stdout."""
356 level = int(bool(handle))
357 for scheme in "http", "https":
358 h = self._ua_handlers.get(scheme)
359 if h is not None:
360 h.set_http_debuglevel(level)
361
362 def _copy_state(self, other):
363 if self._ua_handlers is None:
364 raise ValueError('Cannot copy state from a closed UserAgentBase')
365 other.addheaders = self.addheaders[:]
366 rmap = {v: k for k, v in iteritems(self._ua_handlers)}
367
368 def clone_handler(h):
369 ans = copy.copy(h)
370 ans.add_parent(other)
371 try:
372 other._ua_handlers[rmap[h]] = ans
373 except KeyError:
374 pass
375 return ans
376
377 other._ua_handlers.clear()
378 other.handlers = [clone_handler(h) for h in self.handlers]
379 other._handler_index_valid = False
380
381 def handlers_by_class(self, cls):
382 for h in self.handlers:
383 if isinstance(h, cls):
384 yield h
385
386 def _set_handler(self,
387 name,
388 handle=None,
389 obj=None,
390 constructor_args=(),
391 constructor_kwds={}):
392 if handle is None:
393 handle = obj is not None
394 if handle:
395 handler_class = self.handler_classes[name]
396 if obj is not None:
397 newhandler = handler_class(obj)
398 else:
399 newhandler = handler_class(*constructor_args,
400 **constructor_kwds)
401 else:
402 newhandler = None
403 self._replace_handler(name, newhandler)
404
405 def _replace_handler(self, name, newhandler=None):
406 # first, if handler was previously added, remove it
407 if name is not None:
408 handler = self._ua_handlers.pop(name, None)
409 if handler is not None:
410 try:
411 self.handlers.remove(handler)
412 except ValueError:
413 pass
414 # then add the replacement, if any
415 if newhandler is not None:
416 self.add_handler(newhandler)
417 self._ua_handlers[name] = newhandler
418
419
420 class UserAgent(UserAgentBase):
421 def __init__(self):
422 UserAgentBase.__init__(self)
423 self._seekable = False
424
425 def set_seekable_responses(self, handle):
426 """Make response objects .seek()able."""
427 self._seekable = bool(handle)
428
429 def open(self,
430 fullurl,
431 data=None,
432 timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
433 if self._seekable:
434
435 def bound_open(fullurl,
436 data=None,
437 timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
438 return UserAgentBase.open(self, fullurl, data, timeout)
439
440 response = _opener.wrapped_open(bound_open,
441 _response.seek_wrapped_response,
442 fullurl, data, timeout)
443 else:
444 response = UserAgentBase.open(self, fullurl, data)
445 return response