如何在Google App Engine上使用任务队列获取返回值(如Ajax)
我可以用任务队列来修改数据库的值,但我该怎么用任务队列获取像Ajax那样的返回值呢?
这是我的代码:
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import os
class Counter(db.Model):
count = db.IntegerProperty(indexed=False)
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_values={}):
values={
}
template_values.update(values)
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.out.write(template.render(path, template_values))
class CounterHandler(BaseRequestHandler):
def get(self):
self.render_template('counters.html',{'counters': Counter.all()})
def post(self):
key = self.request.get('key')
# Add the task to the default queue.
for loop in range(0,1):
a=taskqueue.add(url='/worker', params={'key': key})
#self.redirect('/')
self.response.out.write(a)
class CounterWorker(webapp.RequestHandler):
def post(self): # should run at most 1/s
key = self.request.get('key')
def txn():
counter = Counter.get_by_key_name(key)
if counter is None:
counter = Counter(key_name=key, count=1)
else:
counter.count += 1
counter.put()
db.run_in_transaction(txn)
self.response.out.write('sss')#used for get by task queue
def main():
run_wsgi_app(webapp.WSGIApplication([
('/', CounterHandler),
('/worker', CounterWorker),
]))
if __name__ == '__main__':
main()
我该怎么显示' sss '呢?
1 个回答
2
现在的任务队列API不支持处理返回值或者把结果发送回原来的地方。你的应用程序的运行时间太短,无法使用这种编程方式。
在你的例子中,看起来你想要的流程大概是这样的:
- 创建一个任务
- 返回一段AJAX代码,用来定期检查任务状态
- 任务处理完成后,更新数据存储,并带上返回值
- 任务状态的链接返回更新后的值
另外,如果你不想把' sss '返回给客户端,而是需要它进行进一步处理,你就需要把你的方法拆分成几个部分。第一部分创建任务,然后退出。在任务处理完成后,它会自己添加一个新任务,调用第二部分,并带上返回值。