简体   繁体   中英

Cannot connect to firestore firebase in Python

I created a firebaseconfig.json file with my apikey, authodomain, databaseurl, projected, storagebucket, messagingsenderid, appid and measurementid. this comes standard in the SDK setup and configuration section of the yourapps section in project setting. but when I try running my python code.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import os


print(os.getcwd())
if not firebase_admin._apps:
    cred = credentials.Certificate('src/firebaseconfig.json') 
    default_app = firebase_admin.initialize_app(cred)
db = firestore.client()


users_ref = db.collection(u'users')
docs = users_ref.stream()

for doc in docs:
    print(f'{doc.id} => {doc.to_dict()}')

I get the Error: ValueError: Invalid service account certificate. Certificate must contain a "type" field set to "service_account".

The Firebase Admin SDK requires a service account for authentication, as opposed to a configuration file with the project keys (which is primarily used for web/iOS/Android clients).

If you have not used a service account, you need to generate a key file to use within your application through the Firebase console (Settings -> Service Accounts -> Generate New Private Key).

Afterwards, you can initialize the firestore client within your code as follows (relevant doc ):

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

# Use the json key generated from the Firebase console
cred = credentials.Certificate('path/to/serviceAccount.json')
firebase_admin.initialize_app(cred)

db = firestore.client()

Let me know if this information was useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM