Best way to disconnect from ldap?

J. Cliff Dyer jcd at sdf.lonestar.org
Wed Mar 21 16:21:52 EDT 2012


Write a context manager.  

Then you just do

with MyLDAPWrapper() as ldap
   ldap.this()
   ldap.that()

and when you leave the scope of the with statement, your ldap __exit__
method will get called regardless of how you left.

Cheers,
Cliff


On Wed, 2012-03-21 at 19:30 +0000, John Gordon wrote:
> I'm writing an application that interacts with ldap, and I'm looking
> for advice on how to handle the connection.  Specifically, how to
> close the ldap connection when the application is done.
> 
> I wrote a class to wrap an LDAP connection, similar to this:LDAP
> 
>     import ldap
>     import ConfigParser
> 
>     class MyLDAPWrapper(object):
> 
>         def __init__(self):
> 
>             config = ConfigParser.SafeConfigParser()
>             config.read('sample.conf')
>         
>             uri = config.get('LDAP', 'uri')
>             user = config.get('LDAP', 'user')
>             password = config.get('LDAP', 'password')
> 
>             self.ldapClient = ldap.initialize(uri)
>             self.ldapClient.simple_bind_s(user, password)
> 
> My question is this: what is the best way to ensure the ldap connection
> gets closed when it should?  I could write an explicit close() method,
> but that seems a bit messy; there would end up being lots of calls to
> close() scattered around in my code (primarily inside exception handlers.)
> 
> Or I could write a __del__ method:
> 
>         def __del__(self):
>             self.ldapClient.unbind_s()
> 
> This seems like a much cleaner solution, as I don't ever have to worry
> about closing the connection; it gets done automatically.
> 
> I haven't ever used __del__ before.  Are there any 'gotchas' I need to
> worry about?
> 
> Thanks!
> 
> -- 
> John Gordon                   A is for Amy, who fell down the stairs
> gordon at panix.com              B is for Basil, assaulted by bears
>                                 -- Edward Gorey, "The Gashlycrumb Tinies"
> 





More information about the Python-list mailing list