Google App Engine

□未翻訳

□翻訳中

□翻訳完了(Omi Chiba)

■レビュー(中垣健志)

Google App Engine

Google App Engine

DALコードなど一部制約を受けますが、Google App Engine(GAE)13でweb2pyを動かすことができます。通常のホスティングに比べてGAEプラットフォームはいくつかよい点があります。

It is possible to run web2py code on Google App Engine (GAE)13 , including DAL code, with some limitations. The GAE platform provides several advantages over normal hosting solutions:

    • での容易さ。Googleは内部の構造を完全に抽象化しています。

    • 拡張性。同時アクセスリクエストの数だけ何度でもあなたのアプリケーションをレプリカします。

    • Big Table。通常のリレーショナルデータベースの代わりに、Googleの有名なデータストアのBigTableに永続的なデータを保存します。

    • Ease of deployment. Google completely abstracts the underlying architecture.

    • Scalability. Google will replicate your app as many times as it takes to serve all concurrent requests.

    • BigTable. On GAE, instead of a normal relational database, you store persistent information in BigTable, the datastore Google is famous for.

制限は(執筆時点):

The limitations are (at the time of writing):

    • ファイルシステムへの読み書きができない。

    • トランザクションがない。

  • 複雑なデータストアクエリがない。具体的には、JOINLIKEDATE/DATETIMEオペレーションがない。

  • ORの重複や同じフィールドを含まない場合のサブクエリができない。

  • Googleの証明書でappspot.comドメインを使用しないとHTTPSが使用できない。

    • No read or write access to the file system.

    • No transactions.

    • No complex datastore queries. In particular there are no JOIN, LIKE, and DATE/DATETIMEoperators.

    • No multiple OR sub-queries unless they involve one and the same field.

    • No HTTPS unless you use the appspot.com domain with a Google certificate.

これはweb2pyがセッション、エラーチケット、キャッシュファイル、アップロードファイルをファイルシステムに保存できないことを意味します;これらはファイルシステムではなくデータベースに保存される必要があります。

This means that web2py cannot store sessions, error tickets, cache files and uploaded files in the filesystem; they must be stored in the datastore and not in the filesystem.

ここではGAEの簡単な解説とweb2py特有の問題を説明しますので、詳細については公式のGAEドキュメントを参考にしてください。

Here we provide a quick overview of GAE and we focus on web2py specific issues, we refer you to the official GAE documentation online for details.

注意:執筆時点ではGAEはPython 2.5しかサポートしていません。それ以外のバージョンでは問題が発生します。そしてweb2pyはバイナリではなくソースディストリビューションで実行する必要があります。

Attention: At the time of writing, GAE supports only Python 2.5. Any other version will cause problems. You also must run the web2py source distribution, not a binary distribution.

設定

Configuration

注意すべき3つの設定ファイルがあります:

There are three configuration files to be aware of:

1.

2.

3.

web2py/app.yaml

web2py/queue.yaml

web2py/index.yaml

app.yamlqueue.yamlはたたき台としてテンプレートファイルapp.example.yamlqueue.example.yamlから作成できます。 index.yamlはGoogleデプロイメントソフトウェアで自動で作成されます。

app.yaml and queue.yaml are most easily created by using the template files app.example.yamland queue.example.yaml as starting points. index.yaml is created automatically by the Google deployment software.

app.yamlは次のような構造です(...で一部省略しています):

app.yaml has the following structure (it has been shortened using ...):

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

application: web2py

version: 1

api_version: 1

runtime: python

handlers:

- url: /_ah/stats.*

...

- url: /(?P<a>.+?)/static/(?P<b>.+)

...

- url: /_ah/admin/.*

...

- url: /_ah/queue/default

...

- url: .*

...

skip_files:

...

app.example.yaml(app.yamlにコピーされた)はweb2pyアプリケーションのデプロイ用に設定できますが、adminやexampleアプリケーション用ではありません。Google App Engineに登録したときに使用したアプリケーションidでweb2pyアプリケーションを置き換える必要があります。

app.example.yaml (when copied to app.yaml) is configured to deploy the web2py welcomeapplication, but not the admin or example applications. You must replace web2py with the application id that you used when registering with Google App Engine.

url: /_ah/stats.*はGAEに"/stats"URLで統計情報とプロファイル情報を公開するよう指示します。

url: /_ah/stats.* instructs GAE to expose the "/stats" URL with statistics and profiling information.

url: /(.+?)/static/(.+)はGAEに対して、処理速度をあげるためweb2pyロジックを使わずにアプリの静的ファイルを直接表示するように指示します。

url: /(.+?)/static/(.+) instructs GAE to serve your app static files directly, without calling web2py logic, for speed.

url: /_ah/admin/.*はGAEに管理画面を公開するように指示します。

url: /_ah/admin/.* instructs GAE to expose the GAE administrative interface.

url: /_ah/queue/defaultはGAEにタスクキューへのインターフェイスを公開するように指示します。これはweb2pyでページを自動でリロードしたり速度をあげるためにページをキャッシュするために使われます。

url: /_ah/queue/default instructs GAE to expose an interface to the task queue. This is used by web2py in order to keep reloading your pages automatically and keep them cached for faster service.

url: .*はそれ以外のリクエストにはgaehandler.pyを使うように指示します。

url:.* instructs web2py to use the gaehandler.py for every other request.

skip_files: セッションはGAEにデプロイする必要がないファイルの正規表現のリストです。具体的な例として:

The skip_files: session is list of regular expressions for files that do not need to deployed on GAE. In particular the lines:

1.

2.

(applications/(admin|examples)/.*)|

((admin|examples|welcome)\.(w2p|tar))|

unpackのwelcome雛形アプリケーションを除いてデフォルトアプリケーションをデプロイしないようにGAEに指示しています。ここに無視されるべきアプリケーションをもっと追加することができます。

tell GAE not to deploy the default applications, except for the unpacked welcome scaffolding application. You can add more applications to be ignored here.

アプリケーションのidとバージョン以外には、welcomeアプリケーションは除く以外は、あまりapp.yamlを編集する必要はないかもしれません。

Except for the application id and version, you probably do not need to edit app.yaml, though you may wish to exclude the welcome application.

ファイルqueue.yamlはGAEタスクキューを設定するのに使用されます。

The file queue.yaml is used to configure GAE task queues.

ファイルindex.yamlはGAEのappserver(Google SDKについてくるwebサーバ)でアプリケーションをローカルで実行する際に自動で作成されます。以下のような中身です:

The file index.yaml is automatically generated when you run your application locally using the GAE appserver (the web server that comes with the Google SDK). It contains something like this:

1.

2.

3.

4.

5.

indexes:

- kind: person

properties:

- name: name

direction: desc

この例ではGAEに"name"フィールドをアルファベットの降順ソートした"person"というテーブルのindexを作成するように指示します。対応するindexが無いとあなたのアプリケーションで検索やソートを行うことができません。

In this example it tells GAE to create an index for table "person" that will be used to sort by "name" in reversed alphabetical order. You will not be able to search and sort records in your app without corresponding indexes.

デプロイメントの前には、常にappserverを使ってあなたのアプリをローカルで動かし全ての機能を確認することが重要です。テストだけではなく、"index.yaml"を自動で作成する目的もあります。時々、このファイルを編集して重複したエントリーなどを削除したりするような掃除をしたほうがいいかもしれません。

It is important to always run your apps locally with the appserver and try every functionality of your app, before deployment. This will be important for testing purposes, but also to automatically generate the "index.yaml" file. Occasionally you may want to edit this file and perform cleanup, such as removing duplicate entries.

実行とデプロイメント

Running and Deployment

GAE SDKをインストール済みであるとします。執筆時にはGAEはPython 2.5.2で動作します。以下のappserverコマンドで、"web2py"フォルダの中からあなたのアプリケーションを実行できます。

Here we assume you have installed the GAE SDK. At the time of writing, GAE runs on Python 2.5.2. You can run your app from inside the "web2py" folder by using the appserver command:

1.

python2.5 dev_appserver.py ../web2py

これでappserverが起動し以下のURLでアプリケーションを実行できます。

This will start the appserver and you can run your application at the URL:

http://127.0.0.1:8080/

GAEにあなたのアプリケーションをアップロードするには、前述したように"app.yaml"を編集し適切なアプリケーションidをセットしたことを確認した上で、以下を実行します:

In order to upload your app on GAE, make sure you have edited the "app.yaml" file as explained before and set the proper application id, then run:

1.

python2.5 appcfg.py update ../web2py

MacやWindowsでは、Google App Engineランチャを使用できます。参照13からダウンロードできます。

On Mac and Windows, you can also use the Google App Engine Launcher. You can download the software from ref.13 .

[File][Add Existing Application]を選択し、web2pyフォルダのトップレベルのパスをパスにセットし、ツールバーにある[Run]ボタンを押します。ローカルで動作確認できたら、ツールバーにある[Deploy]ボタンをクリックするだけでデプロイできます。(アカウントを持っているのが前提です)

Choose [File][Add Existing Application], set the path to the path of the top-level web2py folder, and press the [Run] button in the toolbar. After you have tested that it works locally, you can deploy it on GAE by simply clicking on the [Deploy] button on the toolbar (assuming you have an account).

GAE上で、web2pyのチケット/エラーはログにアクセスし検索できるGAE管理コンソールに同じようにログが出力されます。

On GAE, the web2py tickets/errors are also logged into the GAE administration console where logs can be accessed and searched online.

ハンドラの設定

Configuring the Handler

gaehandler.pyはGAE用に提供されているファイルで、いくつかのオプションがあります。これはデフォルトの値です。

The file gaehandler.py is responsible for serving files on GAE and it has a few options. Here are their default values:

1.

2.

3.

4.

5.

KEEP_CACHED = False

LOG_STATS = False

APPSTATS = True

DEBUG = False

AUTO_RETRY = True

KEEP_CACHEDはGAEにダミーのアクションを実行させ続けることでタスクキューのタスクを保存します、こうすることでGAEにキャッシュを強制します。これであなたのユーザの速度は上がりますが、余分な処理がcycleを消費します。

KEEP_CACHED asks GAE to store tasks in the task queue that keep calling a dummy action, thus forcing GAE to cache your application. This will make GAE serve your users faster but it will consume some extra cycles.

LOG_STATSはページ表示時間をGAE のログに出力します。

LOG_STATS will log the time to serve pages in the GAE logs.

APPSTATSはプロファイリング解析を行うGAE appstatsを有効にします。以下のURLでアクセスできます:

APPSTATS will enable GAE appstats which provides profiling statistics. They will be made available at the URL:

http://localhost:8080/_ah/stats

DEBUGはデバッグモードをセットします。実際には以下のコードで明示的に設定されない限り違いはありません。

DEBUG sets debug mode. It make no difference in practice unless checked explicitly in your code via gluon.settings.web2py_runtime.

AUTO_RETRYは失敗時に再度コミットするよう指示します。

AUTO_RETRY instructs GAE to try commit again in case of failure.

ファイルシステムを回避

Avoid the Filesystem

GAEではファイルシステムにアクセスできません。書き込みのためにファイルを開くこともできません。

On GAE you have no access to the filesystem. You cannot open any file for writing.

このため、GAEでは、"upload"フィールドがuploadfiled属性を持つ持たないにかかわらず、web2pyは自動で全てのアップロードファイルをデータストアに保存します。

For this purpose, on GAE, web2py automatically stores all uploaded files in the datastore, whether or not "upload" Field(s) have a uploadfield attribute.

セッションとチケットもデータベースに保存される必要があり以下のように明示します:

You also should store sessions and tickets in the database and you have to be explicit:

1.

2.

3.

4.

5.

if request.env.web2py_runtime_gae

db = DAL('gae')

session.connect(request,response,db)

else:

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

上記のコードはGAEで動作しているかをチェックし、BigTableに接続し、web2pyにセッションとチケットをそこに保存するように指示します。それ以外の場合はsqliteデータベースに接続します。このコードは雛形アプリケーションの"db.py"に既に存在しています。

The above code checks whether you are running on GAE, connects to BigTable, and instructs web2py to store sessions and tickets in there. It connects to a sqlite database otherwise. This code is already in the scaffolding app in the file "db.py".

Memcache

あなたの好みによって、memcacheにセッションを保存することもできます:

If you prefer, you can store sessions in memcache:

1.

2.

3.

4.

5.

6.

7.

from gluon.contrib.gae_memcache import MemcacheClient

from gluon.contrib.memdb import MEMDB

cache.memcache = MemcacheClient(request)

cache.ram = cache.disk = cache.memcache

db = DAL('gae')

session.connect(request,response,MEMDB(cache.memcache))

GAEではcache.ramとcache.diskは使用されるべきでありません、そこでcache.memcacheを使用している点に注意してください。

Notice that on GAE cache.ram and cache.disk should not be used, so we make them point to cache.memcache.

データベースの問題

Database Issues

マルチエンティティトランザクションが無くリレーショナルデータベースの標準的な関数を使用できない点でGAEは他のホスティング環境と異なります。これは高い拡張性への代償です。これらの制限さえ受けいられればGAEは非常に優れたプラットフォームです。そうでない場合は、代わりにリレーショナルデータベースを使った通常のホスティングプラットフォームを検討したほうが良いでしょう。

The absence of multi-entity transactions and typical functionalities of relational databases are what sets GAE apart from other hosting environment. This is the price to pay for high scalability. GAE is an excellent platform if these limitations are tolerable; if not, then a regular hosting platform with a relational database should be considered instead.

もしGAE上でweb2pyアプリケーションが動作しなかったら、前述した制限の一つが原因です。多くの問題はweb2pyクエリからJOINを削除して非正規化することで解決します。

If a web2py application does not run on GAE, it is because of one of the limitations discussed above. Most issues can be resolved by removing JOINs from web2py queries and de-normalizing the database.

Google App EngineはListPeropertyStringListPropertyといった特別なフィールドタイプをサポートします。以下の古い構文にてweb2pyでこれらのタイプを使用できます。

Google App Engine supports some special field types, such as ListProperty andStringListProperty. You can use these types with web2py using the following old syntax:

1.

2.

3.

4.

from gluon.contrib.gql import gae

db.define_table('product',

Field('name'),

Field('tags', type=gae.StringListProperty())

または同様の新しい構文で:

or the equivalent new syntax:

1.

2.

3.

db.define_table('product',

Field('name'),

Field('tags', 'list:string')

どちらの場合も"tags"フィールドはStringListPropertyタイプで、値はストリングのリストである必要があります(GAEのドキュメントに互換性に関する記載があります)。we2pyがフォームの内容を上手く扱えること、リレーショナルデータベースでも動作すること、これらの理由により二つ目の記述の方が良いです。

In both cases the "tags" field is a StringListProperty therefore its values must be lists of strings, compatibly with the GAE documentation. The second notation is to be preferred because web2py will treat the field in a smarter way in the context of forms and because it will work with relational databases too.

同様にListProperty(int)にマッピングするlist:integerlist:referenceをweb2pyはサポートします。

Similarly, web2py supports list:integer and list:reference which map into aListProperty(int).

listタイプの詳細は6章で説明されています。

list types are discussed in more detail in Chapter 6.

GAEとHTTPS

GAE and HTTPS

あなたのアプリケーションのidが"myapp"の場合は、GAEドメインは

If you application has id "myapp" your GAE domain is

http://myapp.appspot.com/

で、HTTPSでアクセスすることもできます

and it can also be accessed via HTTPS

https://myapp.appspot.com/

この場合、Googleによって提供された"appspot.com"の証明書を使用します。

In this case it will use an "appspot.com" certificate provided by Google.

DNSエントリーを登録してあなたの好きなドメイン名でアプリを使用できますが、HTTPSは使用できません。執筆時点でこれはGAEの制限です。

You can register a DNS entry and use any other domain name you own for your app but you will not be able to use HTTPS on it. At the time of writing, this is a GAE limitation.