【问题标题】:How to connect to firestore with Python without Service Account Key?如何在没有服务帐户密钥的情况下使用 Python 连接到 Firestore?
【发布时间】:2019-02-18 04:28:44
【问题描述】:

我需要使用 python 连接 firestore 数据库,但我不想使用服务帐户密钥。我可以仅通过 ProjectId 和 ApiKey 使用 python 连接吗?

使用 javascript 我可以这样做:

firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
});

但我无法使用 Python 执行此操作,但出现此错误:

self._g_credential, self._project_id = google.auth.default(scopes=_scopes)
  File "/home/caique/.local/lib/python2.7/site-packages/google/auth/_default.py", line 306, in default
    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically 
determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or 
explicitly create credentials and re-run the application.

这是我现在的代码:

import firebase_admin
from firebase_admin import credentials, firestore, auth

cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
'projectId': "my-project-id",
'apiKey': "my-api-key"
})

db = firestore.client()

【问题讨论】:

    标签: javascript python firebase google-cloud-firestore


    【解决方案1】:

    您必须使用服务帐户才能连接。这就是授权您的代码访问您项目中的 Firestore 和其他 Google Cloud 资源的原因。

    您唯一不需要提供服务帐号的情况是您的代码在安全的 Google Cloud 环境中运行,例如 Cloud Functions 或 App Engine。在这种情况下,Google Cloud 库将自动从执行环境中获取默认服务帐户凭据。但是在自己的机器上运行时,需要使用服务帐号进行初始化。

    【讨论】:

    • 我是否必须在我的生产应用程序(android)中包含服务帐户密钥 Json 文件才能访问 Firestore?
    • 不,您永远不想将服务帐户放入发送给您的用户的移动应用程序中。这是一个巨大的安全漏洞。
    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2021-03-07
    • 2012-10-22
    • 1970-01-01
    相关资源
    最近更新 更多