session

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(中垣健志)

session

sessionは、もう1つのStorageインスタンスです。sessionに対して次のように格納したものは何でも:

session is another instance of the Storage class. Whatever is stored into session for example:

1.

session.myvariable = "hello"

後で読み出すことができます。

can be retrieved at a later time:

1.

a = session.myvariable

同じユーザである限り、同じセッションの元でコードが実行されます(ユーザがセッションクッキーを削除せず、セッションが無効になってない限りです)。sessionはStorageオブジェクトであるので、存在しない属性/キーの組み合わせでアクセスしても例外は発生しません。代わりにNoneが返されます。

as long as the code is executed within the same session by the same user (provided the user has not deleted session cookies and the session did not expire). Because session is a Storageobject, trying to access an attribute/key that has not been set does not raise an exception; it returns None instead.

セッションオブジェクトには、2つの重要なメソッドがあります。1つはforgetです:

The session object has two important methods. One is forget:

1.

これは、web2pyにセッションを保存しないよう指示します。アクションが頻繁に呼ばれ、かつ、ユーザの活動を追跡する必要がないコントローラにおいて使用されます。

It tells web2py not to save the session. This should be used in those controllers whose actions are called often and do not need to track user activity. session.forget() prevents the session file from being written, regardless of whether it has been modified.session.forget(response) additionally unlocks and closes the session file.

もう1つのメソッドは、connectです:

The other method is connect:

1.

session.connect(request, response, db, masterapp=None)

ここで、dbは(DALによって返される)開いているデータベース接続の名前です。これは、web2pyに、ファイルシステムではなくデータベースにセッションを保存するよう指示します。 web2pyは次のようにテーブルを作成し:

where db is the name of an open database connection (as returned by the DAL). It tells web2py that you want to store the sessions in the database and not on the filesystem. web2py creates a table:

1.

2.

3.

4.

5.

6.

7.

db.define_table('web2py_session',

Field('locked', 'boolean', default=False),

Field('client_ip'),

Field('created_datetime', 'datetime', default=now),

Field('modified_datetime', 'datetime'),

Field('unique_key'),

Field('session_data', 'text'))

cPickledされたセッションをsession_dataフィールドに保存します。

and stores cPickled sessions in the session_data field.

masterapp=Noneというオプションは、デフォルトでは、動作中のアプリケーションの、つまり、request.applicationの名前のアプリケーションに対する既存のセッションを取得するようにします。

The option masterapp=None, by default, tells web2py to try to retrieve an existing session for the application with name in request.application, in the running application.

複数のアプリケーションでセッションを共有したい場合は、masterappにマスタとなるアプリケーションの名前を設定します。

If you want two or more applications to share sessions, set masterapp to the name of the master application.

アプリケーションの状態は、request、session、responseのシステム変数を表示することで、いつでもチェックすることができます。その1つの方法は次のような専用のアクションを用意することです:

You can check the state of your application at any time by printing the request, session andresponse system variables. One way to do it is to create a dedicated action:

1.

2.

def status():

return dict(request=request, session=session, response=response)