2014年5月24日土曜日

はじめてのPython GoogleAppEngineのチュートリアル 1

はじめてのPython フレームワーク

webapp2 は google app engine のフレームワークです。
他にも Django や CherryPy、Pylonsなどが使えますが、webapp2 は Google App Engineの
環境を作成するときにインストールされるので、すぐ使えます。

webapp2
* RequestHandlerクラス:リクエスを処理してレスポンスを生成
* WEGIアプリケーションインスタンス:受信リクエストをURLに基づきハンドラに割り振る

# もっとも単純な例
以下がもっとも単純な例です。

import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello, masahiro\'s World!')
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
RequestHandlerを継承したクラスのgetメソッドを作成すると、self.requestを通してリクエスト情報を取得出来ます。
通常は、self.response にプロパティを設定して終了します。

webapp2.WSGIApplication インスタンスがアプリケーションです。
debug=trueで、ハンドラにエラーが発生したり、キャッチされない例外が発生した場合にブラウザに出力します。

# ユーザ認証

以下の例は、ユーザのログイン認証機能を追加したものです。

#codint: UTF-8
from google.appengine.api import users
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Hello,' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
users.get_current_user() で サインイン済みなら Userオブジェクトが、違う場合は None を得られます。


# フォーム
以下がフォームを使った例です。

#coding: UTF-8
'''
Created on 2014/05/24
@author: masahiro
'''
import cgi
from google.appengine.api import users
import webapp2
MAIN_PAGE_HTML = """\
<html>
<body>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="何か書いてください。"></div>
</form>
</body>
</html>
"""
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(MAIN_PAGE_HTML)
class Guestbook(webapp2.RequestHandler):
def post(self):
self.response.write('<html><body>あたなの文章:<pre>')
self.response.write(cgi.escape(self.request.get('content')))
self.response.write('</pre></body></html>')
application = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Guestbook),
], debug=True)


また、webapp2のimportをyamlファイルに移動しています。

application: guestbook-app
version: 1
runtime: python27
api_version: 1
threadsafe: yes
libraries:
- name: webapp2
version: latest
handlers:
- url: /.*
script: guestbook.application


この例にはハンドラが2つ出てきます。
MainPageとGuestbookです。それぞれURL、/ と /sign に対応しています。
Guestbookではpostのみが定義されています。
cgi.escape()は、HTMLの特殊文字をエスケープします。ユーザに入力された文字が、HTMLとして動作するのを防いでいます。

cgiはPythonの標準ライブラリです。

○cgiドキュメント
https://docs.python.org/release/2.7.2/library/cgi.html


今日はここまで、次はDatastoreにデータを永続化してみます。

0 件のコメント:

コメントを投稿