开发者

How to get the return value (like Ajax) using task queue on Google App Engine

开发者 https://www.devze.com 2023-01-23 01:10 出处:网络
I can use a task queue to change the database value, but how can I get the return value like Ajax using task queue?

I can use a task queue to change the database value, but how can I get the return value like Ajax using task queue?

This is my code:

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()

How can I show the 'sss'?


The current Task Queue API doesn't support processing return values or sending them back to the point of origin. Your appengine process isn't long-lived enough for that programming paradigm to work.

In your example, it looks like what you want is something like this:

  1. Create task
  2. Return AJAX code that will poll a task-status handler
  3. Task processes, updates datastore with a return value
  4. Task-status url returns updated value

Alternatively, if you don't want to return the 'sss' to the client but instead need it for further processing, you'll need to split your method into multiple parts. The first part creates the task and then exits. At the end of the task's process, it adds a new task itself to call back into the second part with the return value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号