Google App Engine Python: memcache と template でコンテンツを変化させる。

前3回に渡って「スケジュール、キャッシュ、テンプレートによる効率的更新」という記事を掲載した。それは、cron によって定期的にコンテンツを更新しようというものだった。

ニーズがあるかはわからないが、決められたコンテンツの中から選んで表示する場合には、cron を使うまでもない。

memcache に保存できるのは、文字列だけではない。基本的には、すべてのオブジェクトを格納できる。

今回は、memcache にリストを保存するサンプルとして、アクセスの度に表示されるコンテンツが変化するページを作成してみよう。

from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os
from google.appengine.api import memcache

class MainPage(webapp.RequestHandler):
  def get(self):
    lis    = ["A","B","C","D","E"]
    pubword= memcache.get('pubword')
    if pubword :
       for i in lis :
           if i in pubword :
              continue
           else :
              pubword.append(i)
              break
       if i==lis[-1] :
              pubword=[i]
    else :
       i = lis[0]
       pubword=[i]
      
    memcache.set('pubword',pubword)
    frg='<h2>'+i+'</h2>'
 
    path = os.path.join(os.path.dirname(__file__), 'main.tpl')
    self.response.out.write(template.render(path, {
         'frg':frg
    }))


application = webapp.WSGIApplication([('/', MainPage)],debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()      

もっとよいロジックがあるかもしれないが、サンプルなので許して欲しい。
アクセスがある度に、"A","B","C","D","E"を順番にテンプレートに埋め込むというものである。

表示した文字は、"pubword"という名のリストに追加していく。そして、そのリストを memcache に保存する。ページにアクセスがあると、"pubword"に保存されている文字以外の文字を1つ表示する。最後の文字"E"を表示したら、リスト"pubword"の内容は、その最後の文字"E"だけにする。

こうすることで、"A","B","C","D","E"が順番に表示されるという仕掛けだ。

テンプレートは、文字を埋め込む場所にテンプレート変数 {{ frg }} をおけばよい。

<html>
<head>
<title>changing words</title>
</head>
<body>
<h1>changing words</h1>
{{ frg }}
</body>
</html>