モデル、ビュー、コントローラ

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(Omi Chiba)

モデル、ビュー、コントローラ

web2pyでは、データ表現(モデル)、データの表示(ビュー)、アプリケーションの作業手順(コントローラ)を分離することを奨励しています。前述の例をもう一度考えて、web2pyのアプリケーションが、この点でどのように構築されるのかを見てみましょう。ここで示すのは、web2pyのMVCを編集するインターフェイスの例です:

web2py encourages the developer to separate data representation (the model), data presentation (the view) and the application workflow (the controller). Let's consider again the previous example and see how to build a web2py application around it. Here is an example of the web2py MVC edit interface:

次図は、web2pyのリクエストに対する典型的な実行順序を示したものです:

The typical workflow of a request in web2py is described in the following diagram:

この図において:

In the diagram:

  • Serverは、web2py内蔵のWebサーバー、もしくは、Apacheなどのサードパーティ製のサーバーにすることができます。Serverはマルチスレッドで処理します。

  • The Server can be the web2py built-in web server or a third-party server, such as Apache. The Server handles multi-threading.

  • "main"は、メインのWSGIアプリケーションです。これは、すべての共通タスクを実行し、ユーザーアプリケーションを制御します。クッキー、セッション、トランザクション、URLのルーティングと逆ルーティング、ディスパッチ処理を扱います。

  • "main" is the main WSGI application. It performs all common tasks and wraps user applications. It deals with cookies, sessions, transactions, URL routing and reverse routing, and dispatching.

Webサーバー側ですでに行われていなくても、静的ファイルを仲介し送信することができます。

It can serve and stream static files if the web server is not doing it already.

  • モデル、ビュー、コントローラのコンポーネントは、ユーザーアプリケーションを構成します。

    • The Models, Views and Controller components make up the user application.

  • 複数のアプリケーションは、同じweb2pyのインスタンスでホストすることができます。

    • Multiple applications can be hosted in the same web2py instance.

  • 破線の矢印は、(単一/複数の)データベースエンジンとの通信を表しています。データベースへの問い合わせは、SQLで直接(非推奨)、もしくは、web2pyのデータベース抽象化レイヤーを利用(推奨)して記述することができます。後者の場合、web2pyのアプリケーションコードは特定のデータベースエンジンに依存しないものとなります。

    • The dashed arrows represent communication with the database engine(s). The database queries can be written in raw SQL (discouraged) or by using the web2py Database Abstraction Layer (recommended), so that web2py application code is not dependent on the specific database engine.

  • ディスパッチャーは、リクエストされたURLをコントローラの関数呼び出しにマッピングします。関数の実行結果は、文字列かまたは複数のシンボルからなる辞書(ハッシュテーブル)として返すことができます。辞書内のデータはビューによって表示されます。HTMLページをリクエストした場合(デフォルトの挙動)、辞書はHTMLページの中でレンダリングされます。同じページをXMLとしてリクエストした場合、web2pyは辞書をXMLとして表示することができるビューを探します。開発者はすでにサポートされるプロトコル(HTML、XML、JSON、RSS、CSV、RTF)や、追加のカスタムプロトコルで、ページを表示するビューを作成することができます。

    • The dispatcher maps the requested URL to a function call in the controller. The output of the function can be a string or a dictionary of symbols (a hash table). The data in the dictionary is rendered by a view. If the visitor requests an HTML page (the default), the dictionary is rendered into an HTML page. If the visitor requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The developer can create views to render pages in any of the already supported protocols (HTML, XML, JSON, RSS, CSV, RTF) or in additional custom protocols.

  • すべての呼び出しはトランザクション内で操作され、キャッチされない例外が発生した場合はどれも、トランザクションがロールバックされます。リクエストが成功した場合は、トランザクションがコミットされます。

    • All calls are wrapped into a transaction, and any uncaught exception causes the transaction to be rolled back. If the request succeeds, the transaction is committed.

  • web2pyはまた、セッションとセッションのクッキーを自動的に処理し、トランザクションがコミットされるときに、特に指定がない場合、セッションも同時に保存されます。

    • web2py also handles sessions and session cookies automatically, and when a transaction is committed, the session is also stored, unless specified otherwise.

  • (cronによる)定期タスクを登録し、予定された時刻に、または/かつ、特定のアクションが完了した後に実行することができます。この方法により、時間のかかるタスクやコンピュータ負荷の高いタスクを、操作性を落とすことなくバックグラウンドで実行することが可能になります。

    • It is possible to register recurrent tasks (via cron) to run at scheduled times and/or after the completion of certain actions. In this way it is possible to run long and compute-intensive tasks in the background without slowing down navigation.

次に示すのは、最小限かつ完結したMVCアプリケーションです。3つのファイルから構成されています:

Here is a minimal and complete MVC application, consisting of three files:

"db.py"はモデルです:

"db.py" is the model:

1.

2.

3.

4.

db = DAL('sqlite://storage.sqlite')

db.define_table('contacts',

Field('name'),

Field('phone'))

ここでは、データベース(この例ではstorage.sqliteファイルに保存されるSQLite)に接続し、contactsというテーブルを定義しています。テーブルが存在しない場合は、web2pyがそれを作成します。そして、透過的に、裏では、利用するデータベースエンジン固有の適切な文法においてSQLコードを生成します。生成されたSQLを見ることできますが、データベースを、デフォルトのSQLiteから、MySQLや、PostgreSQL、MSSQL、Firebird、Oracle、DB2、Informix、Interbase、Ingress、さらに、Google App EngineのGoogle BigTableに置き換えてもコードを変更する必要はありません。

It connects to the database (in this example a SQLite database stored in the storage.sqlitefile) and defines a table called contacts. If the table does not exist, web2py creates it and, transparently and in the background, generates SQL code in the appropriate SQL dialect for the specific database engine used. The developer can see the generated SQL but does not need to change the code if the database back-end, which defaults to SQLite, is replaced with MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres, or Google Big Tables in the Google App Engine.

一旦、テーブルが定義され作成されると、appadmin と呼ばれるデータベースやテーブルにアクセスするために十分な機能を持つWebベースのデータベース管理インターフェイスが利用できます。

Once a table is defined and created, web2py also generates a fully functional web-based database administration interface, called appadmin, to access the database and the tables.

"default.py"はコントローラです:

"default.py" is the controller:

1.

2.

def contacts():

return dict(records=db().select(db.contacts.ALL))

web2pyにおいて、URLはPythonモジュールと関数呼び出しにマッピングされます。この例では、コントローラーがcontactsという単一の関数(または"アクション")を持っています。アクションは文字列(返されるWebページ)かPythonの辞書(key:value ペアの集合)を返すことになります。関数が辞書を返す場合は、コントローラ/関数と同じ名前のビューに渡され、結果的にページがレンダリングされます。この例では、contacts関数は、データベースをselectし、結果のレコードを、辞書のrecordsキーに関連付けられた値として返しています。

In web2py, URLs are mapped to Python modules and function calls. In this case, the controller contains a single function (or "action") called contacts. An action may return a string (the returned web page) or a Python dictionary (a set of key:value pairs). If the function returns a dictionary, it is passed to a view with the same name as the controller/function, which in turn renders the page. In this example, the function contacts performs a database select and returns the resulting records as a value associated with the dictionary key records.

"default/contacts.html"はビューです:

"default/contacts.html" is the view:

1.

2.

3.

4.

5.

{{extend 'layout.html'}}

<h1>Records</h1>

{{for record in records:}}

{{=record.name}}: {{=record.phone}}<br />

{{pass}}

このビューは、関連するコントローラ・関数(アクション)が実行された後に、web2pyによって自動的に呼び出されます。このビューの目的は、records=...として返された辞書内の変数をHTMLにレンダリングすることです。ビューのファイルはHTMLで書かれますが、{{ と }} の特殊文字で区切られたPythonコードを埋め込みます。これは、PHPコードのサンプルとは大きく異なります。なぜなら、HTMLに埋め込まれているコードは"プレゼンテーション層"のコードだけだからです。ビューの先頭で参照されている"layout.html"ファイルは、web2pyによって提供されたもので、すべてのweb2pyアプリケーションのための基本的なレイアウトを定めます。レイアウトファイルは簡単に修正したり置き換えたりすることができます。

This view is called automatically by web2py after the associated controller function (action) is executed. The purpose of this view is to render the variables in the returned dictionaryrecords=... into HTML. The view file is written in HTML, but it embeds Python code delimited by the special {{ and }} delimiters. This is quite different from the PHP code example, because the only code embedded into the HTML is "presentation layer" code. The "layout.html" file referenced at the top of the view is provided by web2py and constitutes the basic layout for all web2py applications. The layout file can easily be modified or replaced.