We have summarized the correspondence method when you want to connect from python code and Google Cloud Functions instead of Google Cloud Functions for Firebase.
It doesn't say that it will pull the credentials from Firebase, so please refer to other articles.
Google Cloud Functions made with python 3.7
firebase-admin 3.2.1
It seems that it only accepts main.py and requirements.txt. I couldn't read the usual serviceAccountKey.json file. It's a common way to authenticate by putting the file path in credentials.Certificate.
So I searched for other methods.
First, I checked the API specifications. https://firebase.google.com/docs/reference/admin/python/firebase_admin.credentials
A credential initialized from a JSON certificate keyfile.
So it seems that it is the one to do from the key file. By the way, from the javascript side, the API specification describes how to accept from files other than files, so if you are using javascript, please see the API specification.
I wondered what kind of processing it was, so I went to see the source. https://github.com/firebase/firebase-admin-python/blob/master/firebase_admin/credentials.py
#Quoted from line 81 of the above URL
if isinstance(cert, str):
with open(cert) as json_file:
json_data = json.load(json_file)
elif isinstance(cert, dict):
json_data = cert
Can you do it? So if you make it a dict type and hand it over, it will read it. You read the source.
In my case, I publish this code on github, so I set the contents of serviceAccountKey.json as it is in the environment variable and load it. It's okay for people to embed it in python code because it's not published, but be careful when handling it as it's bad if it leaks.
The environment variable part uses python-dotenv, but I will omit it.
The version extracted from the client creation code is as follows.
import os
import json
import firebase_admin
from firebase_admin import firestore
from firebase_admin import credentials
cred = credentials.Certificate(json.loads(os.environ.get("FIREBASE_KEY")))
firebase_admin.initialize_app(cred)
db = firestore.client()
Dependent libraries
firebase-admin
google-cloud-firestore
There are two, so please put them in.
Only firebase-admin
appears in the code, but both are needed because firebase-admin
depends on google-cloud-firestore
.
Google Cloud Functions For Firebase now supports python (then there was nothing wrong)
Recommended Posts