Skip to content

Instantly share code, notes, and snippets.

@AngryLoki
Created May 18, 2012 19:45
Show Gist options
  • Save AngryLoki/2727270 to your computer and use it in GitHub Desktop.
Save AngryLoki/2727270 to your computer and use it in GitHub Desktop.
Hit counter with sharding and memcache
application: "true"
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: true.app
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8-80 compliant>
import webapp2
from datetime import datetime
from google.appengine.api import memcache
def counter(self):
"""100% valid html5 hit counter with sharding and memcache"""
mod = datetime.now().minute % 6
exclude = mod + 1 if mod < 5 else 0
keys = map(str, range(0, exclude) + range(exclude + 1, 6))
if memcache.get(str(mod)) is None:
memcache.set(str(mod), 1, 5 * 60)
else:
memcache.incr(str(mod))
cnt = sum(memcache.get_multi(keys).values())
self.response.out.write(
'<!doctype html>\n' +
'<meta charset="utf-8">\n' +
'<title>Memcache-based view counter</title>\n' +
'<h1 style="text-align:center">Counter says %d</h1>' % cnt)
app = webapp2.WSGIApplication([('/', counter)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment