2018/09/02

GCP: GCP外のサーバーからDatastoreへデータをインポートする(keyを自分で設定する場合)

  • Goal
    タブ区切りのテキストファイルをローカルマシン(OR AWSのEC2でも同じ)GCPのDatastoreにインポートする。pythonのプログラムで実施。
    Keyは自分で設定したい。

    Keyを自分で設定する必要がない場合はこちら
  • Case
    以下のようなテキストファイルを、Datastoreにインポートする。
    想定するのは、DatastoreをGAEのマスタのように利用していて、バッチで更新をするようなケース。id をKeyとして登録したい。
    list.txtの中身(タブ区切り)
    id     shimei   score
    1234   山田      89
    2341   田中      90
    1238   佐藤      81
  • How
    1.GCPのコンソールで、Service Account Keyを作成する
     形式は、JSON
     権限は、DatastoreのOwner(これは、Import&Exportでも良いのかも?)
     作成された、JSONはローカルマシンのどこかに設置する。
    2.Google cloud datastore のクライアントライブラリをインストールする。
     ~$ pip install google-cloud-datastore
    3.pythonのプログラムでインポートする。
      ##utf-8に変換⇒Unicodeに変換して、インポートすること!
       あとで、Pythonから呼び出しをする事を想定している。


    from google.cloud import datastore
    # データファイル
    infile = 'list.txt'
    # 認証情報 サービスアカウントキーのJsonを指定する
    datastore_client = datastore.Client.from_service_account_json('gcp_ds.json')
    # datastore のkind名
    kind = 'testscore'
    # ここからメインパート
    with open(infile, 'r') as inputfile:
    inputfile.readline() # 1行目読み飛ばし、項目名なので
    for line in inputfile.readlines():
    i = line.split('\t') # タブ区切り
    id = i[0] # datastore上のKeyとなる
    shimei = i[1].decode('utf-8')
    score = i[2].decode('utf-8')
    item_key = datastore_client.key(kind, id)
    item = datastore.Entity(key=item_key) # Keyとして設定
    item['shimei'] = unicode(shimei)
    item['score'] = unicode(score)
    datastore_client.put(item) # 書き込み
  • Result

0 件のコメント:

コメントを投稿