[Twisted-Python] newbie -- trying to do async ldap operations

Allan Streib astreib at indiana.edu
Wed Apr 23 16:00:52 MDT 2003


On Tue, 22 Apr 2003, Jp Calderone wrote:

>   Here's something that might help (note that I am not familiar with the
> python-ldap API, so I'm just guessing at how it is laidd out):

Your example works nicely with only minor changes.  Here's what I wrote
just to verify it works.  Many thanks!

Allan


from twisted.internet import reactor, defer
import ldap

class LDAPQueryTracker:
    def __init__(self):
        self._ids = {}
        self.ldapCon = ldap.initialize('ldap://localhost/')
        self.ldapCon.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        self.ldapCon.simple_bind_s('cn=Manager,dc=iu,dc=edu', 'xxxxxx')

    def search(self, searchargs):
        id = self.ldapCon.search(searchargs['base'],
                                 ldap.SCOPE_SUBTREE,
                                 searchargs['filter'])
        self._ids[id] = defer.Deferred()
        reactor.callLater(0, self.checkResults)
        return self._ids[id]

    def checkResults(self):
        for (id, deferedResult) in self._ids.items():
            resultType, resultData = self.ldapCon.result(msgid=id,
                                                         all=1,
                                                         timeout=0)
            if resultType is not None:
                del self._ids[id]
                deferedResult.callback(resultData)

            if self._ids:
                reactor.callLater(0, self.checkResults)



#A simple callback
def printResults(results):
    for result in results:
        print result

def printFailure(failure):
    print "LDAP Operation failed"
    failure.printTraceback()


qt = LDAPQueryTracker()
deferedResult = qt.search({'base': 'ou=people,dc=iu,dc=edu',
                           'filter': '(uid=astreib)'})
deferedResult.addCallbacks(printResults, printFailure)

reactor.run()





More information about the Twisted-Python mailing list