GAEでカウンター
GAEを使い始めたのですが、いわゆるBigTableは未体験だったのでカウンターを試しに作ってみました。
db.Modelを継承した単純なデータモデルを作成し、HTTPのリクエストに対してカウンターの値を返します。データの中には更新時刻も入っていて、更新処理はトランザクションを張っています。
実装自体は短くて、以下の通りです。
counter.py
# -*- coding: utf-8 -*- import datetime from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class Count(db.Model): name = db.StringProperty(required=True) count = db.IntegerProperty(default=0) update_time = db.DateTimeProperty() class count(webapp.RequestHandler): def get(self, name=''): query = Count.gql("Where name = :name", name=name) c = query.get() result = db.run_in_transaction(self._increment, c.key() if c is not None else None, name) self.response.content_type = 'text/plan' self.response.out.write(result) def _increment(self, key, name): if key is None: c = Count(name=name, count=0) else: c = db.get(key) c.count += 1 counter = c.count c.update_time = datetime.datetime.now() c.put() return counter application = webapp.WSGIApplication([ (r'/(.*)', count) ]) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
このファイルに加えて、app.yamlを以下のように記述すればGAE上で動かすことができます。
application: counter version: 1 runtime: python api_version: 1 handlers: - url: /(.*) script: counter.py