LoginSignup
0
0

More than 1 year has passed since last update.

Python3: Cloud Firestore に ndjson のデータを追加

Posted at

こちらを参考にしました。
ドキュメントの追加

put_firestore_docs.py
#! /usr/bin/python
#
#	put_firestore_docs.py
#
#						Apr/02/2022
# ------------------------------------------------------------------
import sys
import json
import ndjson
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from datetime import date, datetime
# ------------------------------------------------------------------
def file_to_str_proc(file_in):
	str_out = ""
	try:
		fp_in = open(file_in,encoding='utf-8')
		str_out = fp_in.read()
		fp_in.close()
	except Exception as ee:
		sys.stderr.write("*** error *** file_to_str_proc ***\n")
		sys.stderr.write(str (ee))
#
	return	str_out
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")

file_ndjson=sys.argv[1]
sys.stderr.write(file_ndjson + "\n")

str_in = file_to_str_proc(file_ndjson)

data = ndjson.loads(str_in)

project_id='project-apr02-2022'
collection_in='sample_collection'

cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
	'projectId': project_id
})

db = firestore.client()

count = 0
for unit in data:
	print(count)
#	print(unit['senderId'])
#	print()
	db.collection(collection_in).add(unit)
	count += 1

sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行スクリプト

export GOOGLE_APPLICATION_CREDENTIALS="key-file-apr02.json"
./put_firestore_docs.py in01.ndjson
0
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
0
0