CachedLDAPConnection: Lazy LDAP connections
authorW. Trevor King <wking@tremily.us>
Sun, 20 Jan 2013 17:59:40 +0000 (12:59 -0500)
committerW. Trevor King <wking@tremily.us>
Sun, 20 Jan 2013 18:12:11 +0000 (13:12 -0500)
This is faster, and it allows us to return cached results even when
the LDAP server is not available (e.g. if your network is down).

mutt-ldap.py

index 5894f29acb3c88e608cc1307baa100ee2e15036b..57ede51f67131aac2341e99f7732e76ff5ef61d3 100755 (executable)
@@ -167,12 +167,14 @@ class CachedLDAPConnection (LDAPConnection):
     _cache_version = '{0}.0'.format(__version__)
 
     def connect(self):
+        # delay LDAP connection until we actually need it
         self._load_cache()
-        super(CachedLDAPConnection, self).connect()
 
     def unbind(self):
-        super(CachedLDAPConnection, self).unbind()
-        self._save_cache()
+        if self.connection:
+            super(CachedLDAPConnection, self).unbind()
+        if self._cache:
+            self._save_cache()
 
     def search(self, query):
         cache_hit, entries = self._cache_lookup(query=query)
@@ -182,6 +184,8 @@ class CachedLDAPConnection (LDAPConnection):
             for entry in entries:
                 yield entry
         else:
+            if self.connection is None:
+                super(CachedLDAPConnection, self).connect()
             entries = []
             keys = self.config.get('cache', 'fields').split()
             for entry in super(CachedLDAPConnection, self).search(query=query):