[Twisted-Python] maybeDeferred capability
mardiros
mardiros at laposte.net
Fri Oct 16 02:01:11 MDT 2009
As I am still a new user of Twisted,
I have decide to use the maybeDeferred capability.
The real aim is to cache sql queries,
but I have written this example from
the twisted mayneDeferred doc.
I am happy with my code, but, I would like
to share it to have some feed back
Here it is:
---
import types
from datetime import datetime, timedelta
from twisted.internet import defer
from twisted.internet import reactor, task
class asyncmemoize:
def __init__(self, function,pool_time=10,cachelifetime=10):
self.function = function
self._cache = {}
self._cachelifetime = timedelta(0,cachelifetime)
self._cleaner = task.LoopingCall(self.cleanCache)
self._cleaner.start(pool_time,now=False)
self._cleanrun = False
def __call__(self, *args, **kwargs):
key = (tuple(args), frozenset(kwargs.items()))
if key not in self._cache:
f = self.function(*args, **kwargs).addCallback(self.callback,key)
self._cache[key]=[datetime.today(), f]
else:
print "from cache"
return self._cache[key][1]
def callback(self,result,key):
print "Put real value in cache"
self._cache[key]=[datetime.today(), self._cachelifetime, result]
return result
def cleanCache(self):
if not self._cleanrun:
self._cleanrun = True
print 'Clean the cache...'
#log.msg('Clean the persistent cache...', logLevel=logging.DEBUG)
expire = datetime.today()
i = 0
for k,v in self._cache.items():
print v[0], "<", expire, "=>", v[0] > expire
if v[0] < expire:
i+=1
del self._cache[k]
print '%i items removed' % i
#log.msg('%i items removed' % i, logLevel=logging.DEBUG)
self._cleanrun = False
def saveInCache(result,key):
print "saving to cache"
cache[key] = result
return result
@asyncmemoize
def asynchronousIsValidUser(user):
print "Loading is authenticating from async"
d = defer.Deferred()
reactor.callLater(2, d.callback, user in ["Alice", "Angus", "Agnes"])
return d
def synchronousIsValidUser(user):
'''
Return true if user is a valid user, false otherwise
'''
return user in ["Alice", "Angus", "Agnes"]
def printResult(result,user):
if result:
print "User", user ,"is authenticated"
else:
print "User", user ,"is not authenticated"
def authenticateUser(isValidUser, user):
print "Authenticating user ", user
d = defer.maybeDeferred(isValidUser, user)
return d.addCallback(printResult,user)
authenticateUser(asynchronousIsValidUser,"Alice")
reactor.callLater(3,authenticateUser,asynchronousIsValidUser,"Alice")
reactor.callLater(5,authenticateUser,asynchronousIsValidUser,"Alice")
reactor.callLater(15,authenticateUser,asynchronousIsValidUser,"Alice")
reactor.callLater(30,authenticateUser,asynchronousIsValidUser,"Alice")
reactor.run()
----------------------------------------------------------------------------
Laposte.net fête ses 10 ans !
Gratuite, garantie à vie et déjà utilisée par des millions d'internautes...
vous aussi, pour votre adresse e-mail, choisissez laposte.net.
Laposte.net, bien + qu'une messagerie
----------------------------------------------------------------------------
More information about the Twisted-Python
mailing list