2
3

More than 3 years have passed since last update.

Python3 で Cloud Firestore のデータを作成 (Create)

Last updated at Posted at 2020-01-24

ライブラリーのインストール

sudo pip install --upgrade firebase-admin
firestore_create.py
#! /usr/bin/python
#
import sys
import datetime
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore


# ------------------------------------------------------------------
def add_data_proc(db,key,name,population):
    sys.stderr.write("key = " + key + "\n")
    doc_ref = db.collection('cities').document(key)
    doc_ref.set({
        'name': name,
        'population': population,
        'date_mod': datetime.datetime.utcnow()
    })
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
try:
    cred = credentials.ApplicationDefault()
    firebase_admin.initialize_app(cred, {
        'projectId': 'my-project-2020-01-22',
        })

    db = firestore.client()
#
    add_data_proc(db,'t0921','宇都宮', 38921)
    add_data_proc(db,'t0922','小山', 56417)
    add_data_proc(db,'t0923','佐野', 92385)
    add_data_proc(db,'t0924','足利', 39546)
    add_data_proc(db,'t0925','日光', 18492)
#

except Exception as ee:
    sys.stderr.write("*** error *** in firestore.Client ***\n")
    sys.stderr.write(str(ee) + "\n")
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行コマンド

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

次のバージョンで確認しました。

$ python --version
Python 3.8.6

プロジェクトがないと次のようなエラーが出ます。

*** error *** in firestore.Client ***
404 The project project-jan25-2020 does not exist or it does not contain an active Cloud Datastore or Cloud Firestore database.
 Please visit http://console.cloud.google.com to create a project or https://console.cloud.google.com/datastore/setup?project=project-jan25-2020 to add a Cloud Datastore or Cloud Firestore database.
 Note that Cloud Datastore or Cloud Firestore always have an associated App Engine app and this app must not be disabled.

次のようなエラーが出たら API を有効にする必要があります。

*** error *** in firestore.Client ***
400 The Cloud Firestore API is not available for Datastore Mode projects.

次のようなエラーが出たら、CREDENTIALS の json ファイルを作り直します。

*** error *** in firestore.Client ***
403 Missing or insufficient permissions.

実行がうまく行くと、次のようなデータが作成されます。

firestore_dec16.png

CREDENTIALS の json ファイルは、次の方法でも作成できます。

gcloud beta auth application-default login
2
3
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
2
3