Handling Forms With webapp - Google App Engine - Google Code のサンプルを参考にした。
「遷移元」のページから、フォームの送信で、「遷移先」に遷移する例。
遷移元を表示するのが Apage クラス。遷移先を表示するのが BPage。両方とも webapp.RequestHandler を継承している。遷移元からのリクエストと遷移先のページを対応付けるのが、webapp.WSGIApplication。
WSGI とは、18.4 wsgiref -- WSGI Utilities and Reference Implementation によると、
The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Having a standard interface makes it easy to use an application that supports WSGI with a number of different web servers.
以下にコードを示す。
import cgi
import wsgiref.handlers
from google.appengine.ext import webapp
# 遷移元のページ
class APage(webapp.RequestHandler):
def get(self):
self.response.out.write(u"""
<html>
<head>
<title>A</title>
</head>
<body>
<h1>遷移前</h1>
<form action="/seni">
お名前:
<input type="text" name="name"/>
<input type="submit" value="送信" />
</form>
</body>
</html>
""")
# 遷移先のページ
class BPage(webapp.RequestHandler):
def get(self):
result = u"""
<html>
<head>
<title>B</title>
</head>
<body>
<h1>遷移後</h1>
<p>お名前:
"""
# リクエストから文字列を取り出す
result += cgi.escape(self.request.get("name"))
result += u"""
</p>
</body>
</html>
"""
self.response.out.write(result)
def main():
# 画面遷移の対応付け
application = webapp.WSGIApplication(
[('/', APage),
('/seni', BPage)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == "__main__":
main()
Bpage#get()において、文字列をユニコードとして認識されるようにしておかないと(文字列の先頭の`u')、UnicodeDecodeError が表示される。
0コメント:
コメントを投稿