tipfy - Sessions チュートリアル
Google App Engine で書くときに標準で無いのかぁと思う機能の一つにセッション管理があります。自分で実装するのもそんなに手間ではないのですが、用意されてると楽ですよね。tipfy には DataStore ベースと Cookie ベースのセッション機能が用意されてます。
ということで Sessions Tutorial を見ながらやってみます。
Configuration
セッション管理を有効にするには、config.py の extensions リストに session モジュールを追加する必要があります。
tipfy.ext.session.datastore を追加するとセッション情報は DataStore に保存され、tipfy.ext.session.securecookie を追加すると Cookie に保存されます。そんでもってセッション ID とデータの HMAC を作る際の secret_key を設定しておきます。
ちなみに DataStore を使う場合ですが、セッション情報の読み込みは memcache を使ってキャッシングされ、なるべく DataStore へのアクセスが発生しないようにしているそうです。
config.py 既存のファイルを修正
1 config = {}
2
3 config['tipfy'] = {
4 'extensions': [
5 'tipfy.ext.debugger',
6 'tipfy.ext.i18n',
7 'tipfy.ext.user',
8 # ↓↓↓ 追加する ↓↓↓
9 'tipfy.ext.session.securecookie',
10 ],
11 }
12
13 # ↓↓↓ 追加する ↓↓↓
14 config['tipfy.ext.session'] = {
15 # ↓↓↓ my_secret_key を自分のアプリ用に変更して下さい↓↓↓
16 'secret_key': 'my_secret_key',
17 }
Session を使う
すると、全てのリクエストでセッションが有効になります。実際に RequestHandler でセッションを使う場合は、
session_test.py ファイルを新しく追加
1 from tipfy import RequestHandler, request, response
2 from tipfy.ext.session import session
3
4 class MyHandler(RequestHandler):
5 def get(self, **kwargs):
6 # session にキーがセットされているか確認
7 if session.get('foo'):
8 # 動作確認用にセッションの値を response に追加
9 response.data = session.get('foo')
10 else:
11 response.data = 'Session was not set!'
12
13 # session に値をセット
14 session['foo'] = 'bar'
15
16 return response
urls.py 既存のファイルに Rule を追加
1 # -*- coding: utf-8 -*-
2 """
3 urls
4 ~~~~
5
6 URL definitions.
7
8 :copyright: 2009 by tipfy.org.
9 :license: BSD, see LICENSE.txt for more details.
10 """
11 from tipfy import get_config, import_string, Rule
12
13 def get_rules():
14 rules = [
15 ### ↓↓↓ 追加します ↓↓↓
16 Rule('/session-test', endpoint='session', handler='session_test:MyHandler'),
17 ]
18
19 for app_module in get_config('tipfy', 'apps_installed'):
20 try:
21 # Load the urls module from the app and extend our rules.
22 app_urls = import_string('%s.urls' % app_module)
23 rules.extend(app_urls.get_rules())
24 except ImportError:
25 pass
26
27 return rules
tipfy - small Python framework for App Engine