[Twisted-Python] Deferred problem

Donovan Preston dp at twistedmatrix.com
Tue Oct 28 09:07:06 MST 2003


On Oct 28, 2003, at 9:28 AM, vicky lupien wrote:

>     def getUser(self, username):
>         sql = """SELECT * FROM users WHERE name='%s'""" %username
>         results = self.dbpool.runQuery(sql)   ## the deferred result
>         if results is not None:
>             return results[0], results[1]
>         raise KeyError(username)

The Deferred is a promise that some data will be available eventually. 
You cannot
immediately access the result as you try to do here. What you want to 
do is return the
deferred from here after adding a callback which checks to see if there 
was a match
in the database and returns a Failure (analogous to raising an 
exception) if not. If the
authentication succeeded, the callback should return the id of the 
authenticated user.


def requestAvatarId(self, creds):
	## Start the database query; it will not be done until later.
	theDeferred = self.dbpool.runQuery(
		"select * from users where name='%s'" % username
	)

	## Define a callback which will check the results from the database
	## when they are ready and return either the id of the user who has
	## logged in or a failure indicating login failure.
	def checkAuth(result):
		if result is None:
			return failure.Failure(UnauthorizedLogin(c.username))

		u, p = result
		if components.implements(creds, credentials.IUsernameHashedPassword):
			h = self.hash(creds.username, creds.password, p)
			if h == p:
				return u
		return failure.Failure(UnauthorizedLogin(c.username)

	## Add the callback to the Deferred and return it; when the database
	## result is ready, the callback will fire and provide either a Failure
	## or a logged in user id to the framework code which has called
	## requestAvatarId.
	return theDeferred.addCallback(
		checkAuth
	)





More information about the Twisted-Python mailing list