Skip to content

Instantly share code, notes, and snippets.

@code
Created August 17, 2009 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code/168961 to your computer and use it in GitHub Desktop.
Save code/168961 to your computer and use it in GitHub Desktop.
if __name__ == '__main__':
from doctest import gae
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api.labs import taskqueue
import time
def task(f, classtask=False, modeltask=False):
def g(*args, **kwargs):
__async__ = kwargs.get('__async__', False)
if not __async__:
return f(*args, **kwargs)
del kwargs['__async__']
cls = None
model = None
if classtask:
cls = args[0]
args = args[1:]
if modeltask or (len(args) > 0 and isinstance(args[0],db.Model)):
model = args[0]
if not model.is_saved():
raise db.NotSavedError(model)
model = model.key()
args = args[1:]
key = repr(time.time())
data = {
'module':f.__module__,
'f':f.__name__,
'args': args,
'kwargs': kwargs
}
if cls:
data['cls'] = cls.__name__
if model:
data['model'] = str(model)
memcache.set(key, data)
taskqueue.add(url='/worker', params={'key': key})
return key
return g
def classtask(f):
return task(f, classtask=True)
def modeltask(f):
return task(f, modeltask=True)
def run(key):
data = memcache.get(key)
if data is None:
return
args = data.get('args')
kwargs = data.get('kwargs')
module = data.get('module')
f = data.get('f')
cls = data.get('cls', None)
model = data.get('model', None)
scope = __import__(module)
if cls:
scope = getattr(scope, cls)
if model:
scope = db.get(db.Key(model))
f = getattr(scope, f)
memcache.get(key)
return f(*args, **kwargs)
if __name__ == '__main__':
class Blah(db.Model):
name = db.StringProperty()
@classmethod
@classtask
def foolsgold(cls, a, b, **kwargs):
print a
print b
print repr(kwargs)
@task
def wiggle(self, boom):
print str(self.key())
print self.name
print boom
Blah.foolsgold('1','2')
key = Blah.foolsgold('1','2',spam='blah',__async__=True)
run(key)
@task
def testing123(foo,bar):
print foo
print 'ha'
print bar
key = testing123('luke','hubbard',__async__=True)
run(key)
blah = Blah(name='jeff')
blah.put()
key = blah.wiggle('wobble',__async__=True)
run(key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment