1 """urllib2 style build opener integrates with HTTPSConnection class from this
2 package.
3 """
4 __author__ = "P J Kershaw"
5 __date__ = "21/12/10"
6 __copyright__ = "(C) 2011 Science and Technology Facilities Council"
7 __license__ = "BSD - see LICENSE file in top-level directory"
8 __contact__ = "Philip.Kershaw@stfc.ac.uk"
9 __revision__ = '$Id$'
10 import logging
11 from urllib2 import (ProxyHandler, UnknownHandler, HTTPDefaultErrorHandler,
12 FTPHandler, FileHandler, HTTPErrorProcessor, HTTPHandler,
13 OpenerDirector, HTTPRedirectHandler)
14
15 from ndg.httpsclient.https import HTTPSContextHandler
16
17 log = logging.getLogger(__name__)
18
19
20
22 """Create an opener object from a list of handlers.
23
24 The opener will use several default handlers, including support
25 for HTTP and FTP.
26
27 If any of the handlers passed as arguments are subclasses of the
28 default handlers, the default handlers will not be used.
29 """
30 import types
31 def isclass(obj):
32 return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")
33
34 opener = OpenerDirector()
35 default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
36 HTTPDefaultErrorHandler, HTTPRedirectHandler,
37 FTPHandler, FileHandler, HTTPErrorProcessor]
38 check_classes = list(default_classes)
39 check_classes.append(HTTPSContextHandler)
40 skip = []
41 for klass in check_classes:
42 for check in handlers:
43 if isclass(check):
44 if issubclass(check, klass):
45 skip.append(klass)
46 elif isinstance(check, klass):
47 skip.append(klass)
48
49 for klass in default_classes:
50 if klass not in skip:
51 opener.add_handler(klass())
52
53
54 ssl_context = kw.get('ssl_context')
55
56
57 if HTTPSContextHandler not in skip:
58 opener.add_handler(HTTPSContextHandler(ssl_context))
59
60 for h in handlers:
61 if isclass(h):
62 h = h()
63 opener.add_handler(h)
64
65 return opener
66