Skip to content

Instantly share code, notes, and snippets.

@ego008
Created May 7, 2011 07:49
Show Gist options
  • Save ego008/960297 to your computer and use it in GitHub Desktop.
Save ego008/960297 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from google.appengine.api import taskqueue
from google.appengine.ext import db
#modle
class Counter(db.Model):
"""Model for containing a count."""
count = db.IntegerProperty()
#some def run_in_transaction
def update_counter(name):
"""Increment the named counter by 1."""
def _update_counter(name):
counter = Counter.get_by_key_name(name)
if counter is None:
counter = Counter(key_name=name);
counter.count = 1
else:
counter.count = counter.count + 1
counter.put()
# Update counter in a transaction.
db.run_in_transaction(_update_counter, name)
#TaskQueueHandler Get data from post data
class TaskQueueHandler(webapp.RequestHandler):
# TaskQueueHandler is mapped to '/_ah/counter'
"""Task queue handler for update_counter."""
def post(self):
name = self.request.get('counter_name')
update_counter(name)
##views mothod
class SomeRequestViaTaskQueue(webapp.RequestHandler):
"""Perform asynchronous requests to update counter."""
def get(self):
# Asynchronously updates counter.
taskqueue.add(url='/_ah/counter',
params={'counter_name':
'SomeRequestViaTaskQueue'})
# try/finally pattern to temporarily set the namespace.
# Save the current namespace.
namespace = namespace_manager.get_namespace()
try:
# Asynchronously updates counter.
namespace_manager.set_namespace('-global-')
taskqueue.add(url='/_ah/counter',
params={'counter_name',
'SomeRequestViaTaskQueue'})
finally:
# Restore the saved namespace.
namespace_manager.set_namespace(namespace)
self.response.out.write('<html><body><p>')
self.response.out.write('Counters will be updated')
self.response.out.write('</p></body></html>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment