Python3 で Cloud Firestore のデータを読む (Read)


こちらで作成したデータを読みます。
Python3 で Cloud Firestore のデータを作成 (Create)

firestore_read.py
#! /usr/bin/python
#
import sys
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

# ------------------------------------------------------------------
def data_read_proc(doc):
    results = doc.to_dict()
    str_out = doc.id + '\t'
    str_out += results['name'] + '\t' + str(results['population'])
    str_out += '\t' + str(results['date_mod'])
    print(str_out)
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
  'projectId': 'my-project-2020-01-22',
})

db = firestore.client()
#
users_ref = db.collection('cities')
docs = users_ref.stream()
#
for doc in docs:
    data_read_proc(doc)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行コマンド

export GOOGLE_APPLICATION_CREDENTIALS="***.json"
./firestore_read.py

実行結果

*** 開始 ***
t0921   宇都宮   38921   2020-12-16 04:36:37.271232+00:00
t0922   小山  56417   2020-12-16 04:36:37.953997+00:00
t0923   佐野  92385   2020-12-16 04:36:38.075886+00:00
t0924   足利  39546   2020-12-16 04:36:38.180650+00:00
t0925   日光  18492   2020-12-16 04:36:38.300083+00:00
*** 終了 ***