1
2

More than 3 years have passed since last update.

GAE(Python3) Cloud NDBを使用して登録・更新・取得を行う。

Posted at

今回の目的

GAE(Python3)でCloud NDBを使用してデータの登録更新・取得を可能にします。
基本的にgithubのサンプルを使用します。
今回はpython-docs-samples\appengine\standard_python3\building-an-app\building-an-app-2のモジュールを
ベースに作成しています。

requirements.txtの修正・インストール

プロジェクト直下のrequirements.txtに以下を追記します。

requirements.txt
google-cloud-ndb

追加後、プロジェクト直下のディレクトリで以下コマンドで実行し、google-cloud-ndbをインストールします。

pip install -r requirements.txt

これでCloud NDBのインストールが完了です。

データの登録・更新・取得処理の作成

今回は単純なデータ登録更新取得処理のモジュールを作成します。
以下の内容です。

main.py
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)
datastore/user.py
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():配下で実施します。
今回は単純ですが、データがなければ登録あればログイン日付を更新する処理を記載しています。

templates/index.html
<!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/ を確認します。

2020-09-23_02h38_58.jpg
ログイン日時が確認できました。
データストアを見てみます。
2020-09-23_02h40_00.jpg
データが登録されていました。
2020-09-23_02h41_49.jpg
再度アクセスすると日時が更新されていることを確認できました。

なんだかあまりうまくできなくて時間が結構かかったので、記載しておきます。

今回はここまでです。

ありがとうございました。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2