今回の目的
GAE(Python3)でCloud NDBを使用してデータの登録更新・取得を可能にします。
基本的にgithubのサンプルを使用します。
今回はpython-docs-samples\appengine\standard_python3\building-an-app\building-an-app-2のモジュールを
ベースに作成しています。
requirements.txtの修正・インストール
プロジェクト直下のrequirements.txtに以下を追記します。
google-cloud-ndb
追加後、プロジェクト直下のディレクトリで以下コマンドで実行し、google-cloud-ndbをインストールします。
pip install -r requirements.txt
これでCloud NDBのインストールが完了です。
データの登録・更新・取得処理の作成
今回は単純なデータ登録更新取得処理のモジュールを作成します。
以下の内容です。
import datetime
from flask import Flask, render_template
from datastore import user
app = Flask(__name__)
@app.route('/')
def root():
# テストユーザの登録または更新
user.putData('test')
# テストユーザの取得
selectUsr = user.get('test')
return render_template('index.html', user=selectUsr)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
import datetime
from google.cloud import ndb
#ユーザ情報
class User(ndb.Model):
# 最終ログイン日時
lastLoginDt = ndb.DateTimeProperty()
client = ndb.Client()
#ユーザ登録・更新
def putData(idStr):
with client.context():
user = User(
id=idStr,
lastLoginDt = datetime.datetime.now())
user.put()
#ユーザ取得
def get(idStr):
with client.context():
return ndb.Key(User, idStr).get()
classで項目を設定します。
ユーザ登録・更新、ユーザ取得はwith client.context():配下で実施します。
今回は単純ですが、データがなければ登録あればログイン日付を更新する処理を記載しています。
<!doctype html>
<html>
<head>
<title>Sample</title>
<script src="{{ url_for('static', filename='script.js') }}"></script>
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Sample</h1>
<h2>{{ user.lastLoginDt }}</h2>
</body>
</html>
登録更新したログインユーザのログイン日時が表示されることを確認します。
以下を実行します。
python main.py
http://127.0.0.1:8080/ を確認します。
ログイン日時が確認できました。
データストアを見てみます。
データが登録されていました。
再度アクセスすると日時が更新されていることを確認できました。
なんだかあまりうまくできなくて時間が結構かかったので、記載しておきます。
今回はここまでです。
ありがとうございました。