数えよう

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(中垣健志)

数えよう

今度は、同じ訪問者がこのページを何回表示したかを数えるカウンタを追加しましょう。

Let's now add a counter to this page that will count how many times the same visitor displays the page.

web2pyは、セッションとクッキーを使って自動的かつ透過的に訪問者を追跡します。新しい訪問者が来るたびに、セッションが作成されユニークな"session_id"が割り当てます。セッションはサーバ側に保存されている変数のためのコンテナです。一意のIDは、クッキーを介してブラウザに送信されます。訪問者が同じアプリケーションから別のページをリクエストするとき、ブラウザはクッキーを送り戻し、そのクッキーはweb2pyによって取得され、対応するセッションが復元されます。

web2py automatically and transparently tracks visitors using sessions and cookies. For each new visitor, it creates a session and assigns a unique "session_id". The session is a container for variables that are stored server-side. The unique id is sent to the browser via a cookie. When the visitor requests another page from the same application, the browser sends the cookie back, it is retrieved by web2py, and the corresponding session is restored.

セッションを使用するには、デフォルトのコントローラを次のように変更します:

To use the session, modify the default controller:

1.

2.

3.

4.

5.

6.

def index():

if not session.counter:

session.counter = 1

else:

session.counter += 1

return dict(message="Hello from MyApp", counter=session.counter)

counterはweb2pyのキーワードではないですが、sessionに保存される変数であることに注意してください。ここでは、sessionの中にcounter変数が存在するかチェックするようにweb2pyに求めます。存在しない場合は、それを作成し、1に設定します。存在すれば、counterを1増加させるようにweb2pyに求めます。最後に、ビューにcounterの値を渡します。

Notice that counter is not a web2py keyword but session is. We are asking web2py to check whether there is a counter variable in the session and, if not, to create one and set it to 1. If the counter is there, we ask web2py to increase the counter by 1. Finally we pass the value of the counter to the view.

同じ機能をコードするためのよりコンパクトな方法を以下に示します:

A more compact way to code the same function is this:

1.

2.

3.

def index():

session.counter = (session.counter or 0) + 1

return dict(message="Hello from MyApp", counter=session.counter)

そして、ビューを変更し、counterの値を表示するための行を追加します:

Now modify the view to add a line that displays the value of the counter:

1.

2.

3.

4.

5.

6.

7.

<html>

<head></head>

<body>

<h1>{{=message}}</h1>

<h2>Number of visits: {{=counter}}</h2>

</body>

</html>

このページを再び(そして何回も)訪れると、次のようなHTMLのページが表示されます。

When you visit the index page again (and again) you should get the following HTML page:

このcounterは各訪問者と関連づけられ、訪問者がこのページをリロードするたびに増えていきます。異なる訪問者は異なるカウンタを見ることになります。

The counter is associated with each visitor, and is incremented each time the visitor reloads the page. Different visitors see different counters.