db.Model
db.Modelを使ったシンプルな例を紹介する。
最もシンプルな例
このプログラムには以下の2つのHandlerからなる。
- MainHandler
ルートディレクトリ(“/”)に対するリクエストを受け付ける。
データストアから、すべてのEntryを取り出し表示する。 - PostHander
“/post/”に対するリクエストを受け付ける。
Entryに1つレコードを追加して、ルートディレクトリにリダイレクトする。
ソースコード
ソースコードは以下の通り。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext import db class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write('<a href="/post">post</a><br>') for entry in Entry.all(): self.response.out.write(entry.message + '<br>') class PostHandler(webapp.RequestHandler): def get(self): entry = Entry(message = "hello") entry.put() self.redirect('/') class Entry(db.Model): message = db.TextProperty() def main(): application = webapp.WSGIApplication( [('/', MainHandler), ('/post', PostHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() |
実行結果
最初はpostと書かれたリンクだけが表示されます。