简体   繁体   English

无法在 Python 中连接到 Firestore Firebase

[英]Cannot connect to firestore firebase in Python

I created a firebaseconfig.json file with my apikey, authodomain, databaseurl, projected, storagebucket, messagingsenderid, appid and measurementid.我用我的 apikey、authodomain、databaseurl、projected、storagebucket、messagingsenderid、appid 和 measureid 创建了一个 firebaseconfig.json 文件。 this comes standard in the SDK setup and configuration section of the yourapps section in project setting.这是项目设置中 yourapps 部分的 SDK 设置和配置部分的标准配置。 but when I try running my python code.但是当我尝试运行我的python代码时。

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.我收到错误:ValueError:服务帐户证书无效。 Certificate must contain a "type" field set to "service_account".证书必须包含设置为“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). Firebase Admin SDK需要服务帐户进行身份验证,而不是带有项目密钥的配置文件(主要用于 Web/iOS/Android 客户端)。

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).如果您尚未使用服务帐户,则需要通过 Firebase 控制台(设置 -> 服务帐户 -> 生成新私钥)生成要在应用程序中使用的密钥文件。

Afterwards, you can initialize the firestore client within your code as follows (relevant doc ):之后,您可以在代码中初始化firestore客户端,如下所示(相关文档):

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.让我知道这些信息是否有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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