お気に入り | 日本語 | ログイン

Python での Google App Engine の共通タスク

データストアの情報を更新する

データストア モジュールの put() 操作で、新しいエンティティのデータストアへの追加と、既存データストア エンティティの更新の両方の操作を実行できます。

たとえば、ゲストブックのユーザーに、自分のゲストブックのコメントを更新する機能を持たせたいとします。次のようにして、データストア内の既存のコメントを検索し、既存のテキストを新しいテキストを置換し、変更をデータストアにコミットできます。

# For reference, our comment model might look like this
class Comment(db.Model):
  comment_author = db.UserProperty()
  comment_text = db.TextProperty()


class UpdateComment(BaseRequestHandler):
  def post(self):
    # Assume that receive an HTTP post with the updated comment in the comment field
    updated_comment = self.request.get('comment')
    current_user = users.GetCurrentUser()
    # Form the query to retrieve the comment 
    comment_query = Comment.gql('WHERE comment_author = :1', current_user)
    # Fetch the result from the datastore
    comment_result = comment_query.fetch(1)
    if comment_result:
      comment = comment_result[0]
    else:
      logging.error('Could not find comment')

    # Assign the updated comment to the comment text
    comment.comment_text = db.Text(updated_comment)
    # Put the updated entity in the datastore
    comment.put()

MySQL に類似した一般的なクエリをデータストアで実行できますか

Google の App Engine データストアは、リレーショナルではないオブジェクト モデルを使用して情報を格納しているため、高速でスケーラブルなアプリケーションを作成できます。このようなデータ格納方法は MySQL などのリレーショナル データベースとは異なるため、リレーショナル データベースで使用される機能の一部はシステムでは使用できません。たとえば、Google App Engine データストアにはテーブルの「join」の機能はありません。これはリレーショナル データベースでは利用できる機能です。

すべての CRUD 操作(作成、取得、更新、削除)をサポートし、クエリ言語の GQL を使用してデータストアに対してクエリを実行できます。また、Query クラスを使用することもできます。これによって、データの取得時にフィルタや順序付けを使用でき、エンティティの祖先のクエリも実行できます。

データストア フィルタでは、次の一般的な比較演算子を使用して、データストアから取得したデータを制限できます: < <= = >= >

順序付け演算子で、クエリから返されたデータの順序を指定できます。データストアで使用できる各タイプの順序付け演算子は、こちらで参照できます。

最後に、データをデータストアから取得するときに、返される結果に対して制限とオフセットの両方を指定できます。制限は、クエリで返される結果の最大数です。フェッチ オフセットは、データをデータストアから返すときにスキップする結果の数を指定します。

アプリケーションで使用できるサードパーティ ライブラリ

Google App Engine アプリケーションでは、純粋な Python で作成されたあらゆるサードパーティ ライブラリを使用できます。サードパーティ ライブラリを使用するためには、アプリケーションのディレクトリにファイルを配置するだけです。Google のシステムに展開する際に、アプリケーションとともにアップロードしてください。ファイルは、その他の Python ファイルと同様の方法でアプリケーションにインポートできます。

Django を Google App Engine で使用できますか

はい。Django と Google App Engine の使用の開始方法を紹介した、説明記事を用意してあります。

自分で作成した Google App Engine 付属モジュールをインポートする方法

Google App Engine に付属するモジュールの独自のバージョンをインポートする場合は、正常にインポートするために次の簡単な手順を実行する必要があります。まず、インポートするモジュールのファイルを、アプリケーションのディレクトリに配置します。

アプリケーションのコードのモジュールをインポートする前に、sys.modules 内で既存モジュールへのすべての参照を削除する必要があります。その後、アプリケーションのディレクトリを sys.path の前に移動し、このバージョンがインポートされるようにします。以下では、Google App Engine に付属のものとは異なるバージョンの Django をインポートする方法の例を示します。

# Delete the preloaded copy of Django
for key in [key for key in sys.modules if key.startswith('django')]:
  del sys.modules[key]

アプリケーションのディレクトリを sys.path の前に移動するには:

# Force sys.path to have our own directory first, so we can import from it
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

アプリケーションのパフォーマンスをプロファイリングする方法

アプリケーションのパフォーマンスをプロファイルするには、まずアプリケーションの main() 関数の名前を real_main() に変更します。次に、新しいメイン関数として、以下のような profile_main() をアプリケーションに追加します。

def profile_main():
 # This is the main function for profiling 
 # We've renamed our original main() above to real_main()
 import cProfile, pstats
 prof = cProfile.Profile()
 prof = prof.runctx("real_main()", globals(), locals())
 print "<pre>"
 stats = pstats.Stats(prof)
 stats.sort_stats("time")  # Or cumulative
 stats.print_stats(80)  # 80 = how many to print
 # The rest is optional.
 # stats.print_callees()
 # stats.print_callers()
 print "</pre>"

この関数は、プロファイル出力を HTML 応答に付加します。そうではなく、出力をログに記録したい場合は、プロファイラのメイン関数を次のように修正します。

def profile_main():
 # This is the main function for profiling 
 # We've renamed our original main() above to real_main()
 import cProfile, pstats, StringIO
 prof = cProfile.Profile()
 prof = prof.runctx("real_main()", globals(), locals())
 stream = StringIO.StringIO()
 stats = pstats.Stats(prof, stream=stream)
 stats.sort_stats("time")  # Or cumulative
 stats.print_stats(80)  # 80 = how many to print
 # The rest is optional.
 # stats.print_callees()
 # stats.print_callers()
 logging.info("Profile data:\n%s", stream.getvalue())

より多くの情報が必要な場合は、管理コンソールからログ メッセージを表示してください。ログの詳細については、こちらの記事をご覧ください。

アプリケーションでプロファイリングを有効にするには、main = profile_main を設定します。アプリケーションを通常どおり実行するには、main = real_main を設定します

(cProfile は Python 2.5 で追加されたものです。これは App Engine がアプリケーションの実行に使用するバージョンなので、使用することを推奨します。Python の初期バージョンを使用している場合は、ローカルでプロファイリングを行うことはできません)。

Django を実行すると、ROOT_URLCONF が見つからないというエラーが発生する

Google App Engine の webapp フレームワークは Django テンプレートを使用するため、Django は webapp がロードされたときに一部初期化されています。これにより、残りの Django の設定の初期化がスキップされます。このエラーが発生した場合は、Django による設定のリロードを明示的に強制する必要があります:

from django.conf import settings
settings._target = None

自分のアプリケーションを http://myurl.com(ネイキッド ドメインとも呼ばれる)にマップしたい

この質問は、一般的なよくある質問ページ code.google.com/intl/ja/appengine/kb/general.html#naked_domain に移動しました。