1from threading import local 2 3from django.core.mail import get_connection 4 5from .settings import get_backend 6 7 8# Copied from Django 1.8's django.core.cache.CacheHandler 9class ConnectionHandler: 10 """ 11 A Cache Handler to manage access to Cache instances. 12 13 Ensures only one instance of each alias exists per thread. 14 """ 15 def __init__(self): 16 self._connections = local() 17 18 def __getitem__(self, alias): 19 try: 20 return self._connections.connections[alias] 21 except AttributeError: 22 self._connections.connections = {} 23 except KeyError: 24 pass 25 26 try: 27 backend = get_backend(alias) 28 except KeyError: 29 raise KeyError('%s is not a valid backend alias' % alias) 30 31 connection = get_connection(backend) 32 connection.open() 33 self._connections.connections[alias] = connection 34 return connection 35 36 def all(self): 37 return getattr(self._connections, 'connections', {}).values() 38 39 def close(self): 40 for connection in self.all(): 41 connection.close() 42 43 44connections = ConnectionHandler() 45