--I'll leave a note about how to use Firebase's Cloud Firestore and Cloud Storage from Python. --Please prepare a CSV file and use it when uploading or downloading from python.
-Preparation --Add SDK --Preparation of authentication file -[Use Cloud Firestore](Use # cloud-firestore) --Library import --Authentication information initialization --Get data --Add data --Delete data -[Use Cloud Storage](use # cloud-storage) --Library import --Authentication information initialization --Get data --Add data --Delete data --Summary
--First, prepare the SDK and authentication file.
--Execute the following command to add the SDK.
python
pip install firebase-admin # firebase firestore
pip install --upgrade google-cloud-storage # cloud storage
--This is the authentication file used to access firebase programmatically. --Get the json file by following the steps below.
From https://firebase.google.com/docs/admin/setup?hl=ja
- In the Firebase console, open Settings> Service Accounts.
--I will summarize how to use firestore from python.
--First, import the libraries to be used.
import
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
--Allow firebase to be accessed programmatically using the json authentication file prepared earlier. --Initialize with the following code.
initialize
cred = credentials.Certificate('<pass_to_json_file>')
default_app = firebase_admin.initialize_app(cred)
-** Replace <pass_to_json_file>
with the path (character string) to the json file. ** **
-** Be sure to initialize before accessing firebase data. ** **
--If you do not initialize, an error will occur and you will not be able to acquire the data.
--It may be a little convenient to reserve cred
and default_app
as global variables and prepare an initialization function as shown below.
initialize2
cred = None
default_app = None
def initializeFirebaseAPP():
global cred
global default_app
cred = credentials.Certificate("< pass_to_json_file >")
default_app = firebase_admin.initialize_app(cred)
export
export GOOGLE_APPLICATION_CREDENTIALS="<pass_to_json_file>"
initialize
default_app = firebase_admin.initialize_app()
-** This is an example of specifying a single document ** and retrieving the contents.
--Use get
.
--At this time, an exception will be thrown if the document pointed to by doc_ref
does not exist.
--This exception is google.cloud.exceptions.NotFound
, so let's deal with it with try
if necessary.
--For doc_ref
, you can check if the document exists by using the ʻexists` method.
getFirestoreData
def getFirestoreData(collectionName, documentName):
db = firestore.client()
doc_ref = db.collection(collectionName).document(documentName)
doc = doc_ref.get()
print(u'Document data: {}'.format(doc.to_dict()))
--Use stream
for collection
to get all ** documents ** directly under the collection.
getFirestoreData2
def getFirestoreData2(collectionName):
db = firestore.client()
docs = db.collection(collectionName).stream()
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
--To access the collection in the document, use the collection method for the document. ――You can do it as you intuitively.
getFirestoreData3
def getFirestoreData3(col_name, doc_name, col_name2):
db = firestore.client()
doc_ref = db.collection(col_name).document(doc_name)
col_ref2 = doc_ref.collection(col_name2)
--Currently, it is not possible to get a list of document subcollections in python. ――If you want to get the list of subcollections, use other languages together.
――For example, if you write in ruby, it is as follows.
getCollectionList.rb
require "google/cloud/firestore"
firestore = Google::Cloud::Firestore.new project_id: "<project_id>", keyfile: "<path_to_json>"
doc_ref = firestore.doc "<col_name>/<doc_name>"
doc_ref.cols do |col|
puts col.collection_id
end
--This is an example of registering dictionary type data by specifying the collection name and document name.
uploadData2Firestore
def uploadData2Firestore(collectionName, documentName, data):
db = firestore.client()
doc_ref = db.collection(collectionName).document(documentName)
doc_ref.set(data)
--How to update a field on an existing document.
update_data
def update_data(collectionName, documentName, key, value):
db = firestore.client()
doc_ref = db.collection(collectionName).document(documentName)
doc_ref.update({key: value})
--This is an example of deleting data by specifying the collection name and document name.
deleteFirestoreDocument
def deleteFirestoreDocument(collectionName, documentName):
db = firestore.client()
db.collection(collectionName).document(documentName).delete()
--First, import the libraries to be used.
import
import firebase_admin
from firebase_admin import credentials
from google.cloud import storage
--Allow firebase to be accessed programmatically using the json authentication file prepared earlier. --Initialize with the following code.
initialize
storage_client = storage.Client.from_service_account_json('<pass_to_json_file>')
-** Replace <pass_to_json_file>
with the path to the json file. ** **
-** The variables initialized here will be used later. ** **
export
export GOOGLE_APPLICATION_CREDENTIALS="<pass_to_json_file>"
initialize
storage_client = storage.Client()
--This is an example of downloading data to a file by specifying the blob url.
download_blob
def download_blob(src_blob_url, dst_file):
bucket_name = '<bucket_name>'
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(src_blob_url)
storage_client.download_blob_to_file(blob, dst_file)
print('Blob {} downloaded to {}.'.format(src_blob_url, dst_file))
--This is an example of registering by specifying the file name and data.
upload_blob
def upload_blob(file_name, data_sorce):
bucket_name = '<bucket_name>'
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(file_name)
blob.upload_from_filename(filename=data_sorce)
if file_name in bucket.list_blobs():
print("cloud storage: upload success")
else:
print("cloud storage: upload failed")
--This is an example of deleting data by specifying the blob url.
delete_blob
def delete_blob(blob_url):
bucket_name = '<bucket_name>'
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_url)
blob.delete()
――I didn't have much information about how to avoid using environment variables, so I summarized it. ――It may be safer to use environment variables in actual operation, but ...
――The following is a site I often visited. -Try Cloud Firestore --Add data to Cloud Firestore -Get data with Cloud Firestore --Cloud Firestore: python API Reference ――We would appreciate it if you could contact us if you have any typographical errors.
Recommended Posts