【GCP入門編・第6回】これは簡単! Google App Engine での Cloud Datastore の利用方法!

【GCP入門編・第6回】これは簡単! Google App Engine での Cloud Datastore の利用方法!

GCP

投稿日:2017/06/22

前回の記事では hello-world アプリケーションを GAE 上にデプロイしました。この記事では、前回の記事で作成した hello-world アプリケーションを用いて、 Cloud Datastore を利用してみましょう。

この記事の目的

  • 前回の記事で作成した hello-world アプリケーションに手を加え、 Cloud Datastore を使用した簡単なタスク管理アプリケーションを作成しよう。
  • Cloud Datastore の利用について理解できるようになろう。

Cloud Datastore とは

Cloud Datastore は、 MongoDB や RethinkDB のような、ドキュメント志向の NoSQL データベースです。アトミックなトランザクションをサポートし、ドキュメント数のスケールや、高可用性を備えているという特徴があります。また、 Cloud Datastore ではデータは暗号化されて保存されるため、運用側のグーグルでも、その内容がわからないというセキュリティに優れた設計となっています。
Cloud Datastore の公式ドキュメントでは、 Cloud Datastore で使われる概念を、リレーショナルデータベースに対応させた説明が提供されています。
詳細は公式ドキュメントを参照していただくとして、ここでは簡単に記事に登場する概念を説明します。

Entity とは

Cloud Datastore に保存されるドキュメントのことを Entity と呼びます。リレーショナルデータベースの行と同じような概念です。

Kind とは

Object に対してつけられるカテゴリーです。リレーショナルデータベースでは Table に相当します。 Object を登録する際に Kind を指定し、その Kind に対応する Object を全て取得する、といった操作に使われます。

Cloud Datastore を使ってみる

それでは、【GCP入門編・第5回】 Google App Engine (GAE) でのアプリケーション起動方法!で作成した hello-world アプリケーションを用いて、 Cloud Datastore を利用してみましょう。 Cloud Datastore はプロジェクト作成時にデフォルトで利用可能になっていますので、特にコンソール上での準備は必要ありません。
まずは hello-world アプリケーションのフォルダに移動し、 main.py を以下の通り書き換えます。

# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START app]
import logging
from flask import Flask, redirect, request, render_template
from google.appengine.ext import ndb
class Message(ndb.Model):
    body = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add=True)
app = Flask(__name__)
@app.route('/')
def hello():
    # Get message list
    messages = Message.query().fetch()
    return render_template('hello.html', messages=messages)
@app.route('/add', methods=['POST'])
def add_message():
    message_body = request.form.get('message', '')
    message = Message(body=message_body)
    message.put()
    return redirect('/')
@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500
# [END app]

次に、メッセージを入力し、表示する為に HTML テンプレートを追加します。
”templates” ディレクトリを追加し、 ”templates/hello.html” に以下の内容を入力します。

<!doctype html>
<head>
  <title>Message Board</title>
</head>
<body>
  <form action="/add" method="post">
    <textarea name="message" id="message_area"></textarea>
    <input type="submit"></input>
  </form>
  <ul>
    {% for message in messages %}
    <li>{{ message['body'] }} at {{ message['created'] }}</li>
    {% endfor %}
  </ul>
</body>

このテンプレートには、メッセージの入力を行うための input と、 Cloud Datastore から取得したメッセージを表示するためのコードが含まれています。テンプレートの記法に関してはJinja2 のドキュメントを参照ください。
以下のコードで App Engine 上での動作が確認できるかと思います。

$ gcloud app deploy
$ gcloud app browse

以下の画面が表示されていれば成功です。
01.png
テキストエリアに文字を入力し、 [送信] をクリックします。
02.png
画面のように表示されているでしょうか?
入力されたデータは、 GCP のコンソール上から閲覧、削除、アップデートを行うことも可能です。コンソール左側のメニューから Datastore を選択すると、以下の画面のように登録したメッセージ一覧が表示されているかと思います。
03.png

おわりに

いかがでしたでしょうか。今回の記事では、アップデート、削除といった操作や複雑なクエリを発行する方法に関しては説明しませんでしたが、公式ドキュメントに詳細が書かれています。このように、 Google App Engine と Cloud Datastore を使えば、非常に簡単にデータベースを利用したアプリケーションを開発することができますので、是非お試しください。

同じシリーズの記事

GCP のメリットを最大限に活用しよう!

GCP・G Suite のご相談・
お見積り依頼はお気軽に
TEL.03-5840-8815
お問合せフォーム TEL.03-5840-8815