3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ローカルPCからFirestoreのデータにアクセスする

Posted at

Python用Googleクライアントライブラリーを使ってFirestoreのデータへアクセスする。
そのためにはサービスアカウントを作成して鍵(jsonファイル)を準備する必要がある。

GCPのコンソールからサービスアカウントを作成する方法

  • GCPコンソール->IAMと管理->サービスアカウントで作成する
  • 鍵(jsonファイル)が作成されるのでローカルPCへダウンロードする
  • pipコマンドでライブラリをインストールする
$ pip install google-cloud-firestore

実際に取得してみる

from google.cloud import firestore
# 上で作成したjsonファイルを読み込ませる
client = firestore.Client.from_service_account_json('/key.json')
# 「/A/docid」のドキュメントを受信する
client.collection('A').document('docid').get().to_dict()
> {u'foo': u'bar'} # 取得できた

Firebaseのコンソールからサービスアカウントを作成する方法

GCPコンソールに行かなくてもFirebaseコンソールからサービスアカウントを作成できる。

  • Firebaseコンソール->ギアアイコンをクリック->プロジェクトの設定->サービスアカウントへ移動
  • Admin SDK 構成スニペットでpythonを選択して「新しい秘密鍵の生成」ボタンをクリック
  • 鍵(jsonファイル)がPCへダウンロードされるのを確認する

このやり方だと
 アカウント名:firebase-adminsdk
 role: 編集者
でサービスアカウントが作成される。

  • pipコマンドでライブラリをインストールする
$ pip install firebase-admin

実際に取得してみる


import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate('/key.json')
default_app = firebase_admin.initialize_app(cred)
db = firestore.client()
# 「/A/docid」のドキュメントを受信する
db.collection('A').document('docid').get().to_dict()
> {u'foo': u'bar'} # 取得できた
3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?