urllib2_build_opener.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """PyOpenSSL utilities including HTTPSSocket class which wraps PyOpenSSL
  2. SSL connection into a httplib-like interface suitable for use with urllib2
  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: pyopenssl.py 7929 2011-08-16 16:39:13Z pjkersha $'
  10. import logging
  11. from urllib2 import (OpenerDirector, ProxyHandler, UnknownHandler, HTTPHandler,
  12. HTTPDefaultErrorHandler, HTTPRedirectHandler,
  13. FTPHandler, FileHandler, HTTPErrorProcessor)
  14. from urllib2pyopenssl.https import HTTPSContextHandler
  15. log = logging.getLogger(__name__)
  16. # Copied from urllib2 with modifications for ssl
  17. def urllib2_build_opener(ssl_context=None, *handlers):
  18. """Create an opener object from a list of handlers.
  19. The opener will use several default handlers, including support
  20. for HTTP and FTP.
  21. If any of the handlers passed as arguments are subclasses of the
  22. default handlers, the default handlers will not be used.
  23. """
  24. import types
  25. def isclass(obj):
  26. return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")
  27. opener = OpenerDirector()
  28. default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
  29. HTTPDefaultErrorHandler, HTTPRedirectHandler,
  30. FTPHandler, FileHandler, HTTPErrorProcessor]
  31. check_classes = list(default_classes)
  32. check_classes.append(HTTPSContextHandler)
  33. skip = []
  34. for klass in check_classes:
  35. for check in handlers:
  36. if isclass(check):
  37. if issubclass(check, klass):
  38. skip.append(klass)
  39. elif isinstance(check, klass):
  40. skip.append(klass)
  41. for klass in default_classes:
  42. if klass not in skip:
  43. opener.add_handler(klass())
  44. # Add the HTTPS handler with ssl_context
  45. if HTTPSContextHandler not in skip:
  46. opener.add_handler(HTTPSContextHandler(ssl_context))
  47. for h in handlers:
  48. if isclass(h):
  49. h = h()
  50. opener.add_handler(h)
  51. return opener