Skip to content

Instantly share code, notes, and snippets.

@mhrivnak
Created March 28, 2016 19:28
Show Gist options
  • Save mhrivnak/e3a76b3ddd4431138125 to your computer and use it in GitHub Desktop.
Save mhrivnak/e3a76b3ddd4431138125 to your computer and use it in GitHub Desktop.
from collections import namedtuple
from threading import Lock
import time
class Session(object):
"""
This should actually be a Session object from the requests library. I'm
just lazy and made a simple stand-in.
"""
pass
# I put very little thought into the actual list of settings here. Really it
# should just be a full list of whatever ssl settings we support.
SSLSettings = namedtuple('SSLSettings', ['ca_cert', 'client_cert', 'client_key', 'verify_remote_ca'])
SessionEntry = namedtuple('SessionEntry', ['last_used', 'session'])
class SessionPool(object):
def __init__(self):
self._sessions = {}
self._lock = Lock()
def get_session(self, ssl_settings):
"""
:type ssl_settings: SSLSettings
:rtype: Session
"""
with self._lock:
if ssl_settings in self._sessions:
entry = self._sessions[ssl_settings]
entry.last_used = time.time()
else:
entry = SessionEntry(time.time(), Session())
self._sessions[ssl_settings] = entry
return entry.session
def evict_old(self):
"""
Something would need to call this periodically.
"""
with self._lock:
oldest_allowed = time.time() - 300
for key, entry in self._sessions.items():
if entry.last_used < oldest_allowed:
del self._sessions[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment