Skip to content

Instantly share code, notes, and snippets.

@torufurukawa
Created September 11, 2011 12:41
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 torufurukawa/1209524 to your computer and use it in GitHub Desktop.
Save torufurukawa/1209524 to your computer and use it in GitHub Desktop.
Google App Engin SDK memcache cas test
"""
- /init to initialize service
- /update?uid=XXX to tell service XXX is active
- /count to get how many clients are active within last TIME_LIMIT sec.
"""
KEY = 'users'
TIME_LIMIT = 10
MAX_RETRIES = 3
import time
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import memcache
from django.utils import simplejson as json
class InitalizeHandler(webapp.RedirectHandler):
def get(self):
memcache.set(KEY, "{}")
self.response.out.write("OK")
class UpdateHandler(webapp.RequestHandler):
def get(self):
uid = self.request.get('uid')
client = memcache.Client()
for i in range(MAX_RETRIES):
users = json.loads(client.gets(KEY))
users[uid] = time.time()
if client.cas(KEY, json.dumps(users)):
self.response.out.write('OK')
return
else:
self.response.out.write('FAILED')
class CountHandler(webapp.RequestHandler):
def get(self):
users = json.loads(memcache.get(KEY) or "{}")
count = len([uid for uid,timestamp in users.items()
if time.time() < timestamp + TIME_LIMIT])
self.response.out.write('count: %d' % count)
def main():
application = webapp.WSGIApplication([('/init', InitalizeHandler),
('/update', UpdateHandler),
('/count', CountHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment