import ssl import socket import time from http.client import HTTPConnection class HTTPSSessionConnection(HTTPConnection): default_port = 443 def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, *, context=None, session=None): super(HTTPSSessionConnection, self).__init__(host, port, timeout, source_address) self._context = context self._session = session def connect(self): super().connect() server_hostname = self.host self.sock = self._context.wrap_socket(self.sock, server_hostname=server_hostname, session=self._session) def connread(context, session=None, host='pypi.python.org'): conn = HTTPSSessionConnection(host, context=context, session=session) try: conn.request("GET", "/pypi") conn.getresponse().read() session = conn.sock.session if session and conn.sock.session_reused: print('session reused {}'.format(session.id)) else: print('no session resumption') return conn.sock.session finally: conn.close() ctx = ssl.create_default_context() session = connread(ctx) start = time.perf_counter() for i in range(10): connread(ctx, session) sesstime = time.perf_counter() - start start = time.perf_counter() for i in range(10): connread(ctx, session=None) nosesstime = time.perf_counter() - start print("""\ session resumption: {:0.3f}sec no session: {:0.3f}sec {:0.1f}%""".format(sesstime, nosesstime, sesstime / nosesstime*100))