LoginSignup
1
1

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-01-31
firestore_read_rest.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   firestore_read_rest.py
#
#                   Jan/31/2020
#
# ------------------------------------------------------------------
import  sys
import  json
import  requests
#
from get_token import get_token_proc
# ------------------------------------------------------------------
def row_proc(unit_aa):
#   print(unit_aa['name'])
#   print()
    tt = unit_aa['name'].split('/')
    llx = len(tt)
    key = tt[llx - 1]
#
    fields = unit_aa['fields']
#   print(fields)
    name = fields['name']['stringValue']
    population = fields['population']['integerValue']
    date_mod = fields['date_mod']['timestampValue']
    str_out = key + "\t"
    str_out += name + "\t"
    str_out += str(population) + "\t"
    str_out += str(date_mod)
    print(str_out)
#   print()
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
token = get_token_proc()
#
project = 'project-jan25-2020'
#
url="https://firestore.googleapis.com/v1/projects/" + project + "/databases/(default)/documents/cities"
#
try:
    rr=requests.get(url,headers={"Authorization": "Bearer " + token})
    dict_aa = json.loads(rr.text)
#
    for unit_aa in dict_aa['documents']:
        row_proc(unit_aa)
except Exception as ee:
    sys.stderr.write("*** error *** in requests.get ***\n")
    sys.stderr.write(str(ee) + "\n")
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

get_token.py はこちら
Python3 の Rest で Cloud Firestore のデータを作成 (Create)

実行コマンド

export GOOGLE_APPLICATION_CREDENTIALS="***.json"
./firestore_read_rest.py
1
1
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
1