【发布时间】:2019-07-20 18:02:38
【问题描述】:
我无法使用 Python 在 Google Firebase (Cloud Firestore) 数据库中获取、更新或创建文档。
我有什么:
B) 凭证 JSON 文件保存为 test.json(在文档中通常称为 path/to/serviceKey.json),如下所示(已编辑):
{
"type": "service_account",
"project_id": "test-6f02d",
"private_key_id": "fffca ... 5b7",
"private_key": "-----BEGIN PRIVATE KEY-----\n ... 1IHE=\n-----END PRIVATE KEY-----\n",
"client_email": "test-admin@test-6f02d.iam.gserviceaccount.com",
"client_id": "112 ... 060",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/ ... .gserviceaccount.com"
}
这个用户有一个角色所有者。
C) firebase_admin 已安装(使用 virtualenv、pip),我可以这样做:
import firebase_admin
from firebase_admin import credentials, firestore
databaseURL = {'databaseURL': "https://test-6f02d.firebaseio.com"}
cred = credentials.Certificate("test.json")
firebase_admin.initialize_app(cred, databaseURL)
<firebase_admin.App object at 0x7f20056534e0>
以下是有效的:
db = firestore.client()
for k in db.collection('items').get():
print(k)
我正在获取 3 个文档,我可以访问文档的 ID
<google.cloud.firestore_v1beta1.document.DocumentSnapshot object at 0x7f2003bebc18>
<google.cloud.firestore_v1beta1.document.DocumentSnapshot object at 0x7f2003bebdd8>
<google.cloud.firestore_v1beta1.document.DocumentSnapshot object at 0x7f2003bebcf8>
print(k.id)
a3BxcpWpavHmuz6DpZH3
但是,这是我能得到的最大值。
1) 我不知道如何访问文档的值。像这样的:
from firebase_admin import db
ref = db.reference('items')
print(ref)
<firebase_admin.db.Reference object at 0x7f20013b2828>
# GET?
ref.get()
# empty
2) 我不知道如何直接访问这些值(例如,使用浏览器或requests),例如:
https://test-6f02d.firebaseio.com/items.json
返回
{
"error" : "Permission denied"
}
3) 我不知道如何更新现有文档或在集合items 中创建新文档。
# UPDATE?
# PUSH?
我尝试关注this blog 和the documentation(但它没有示例)以及关于 SO 的几个答案,但没有任何成功。
提前致谢。
【问题讨论】:
-
请在每个帖子中限制自己一个问题。看来您的很多问题都可以通过阅读 Firestore 文档来解决。
-
@DougStevenson 我花了最后一天阅读文档并尝试操纵数据,相信我。但我什至无法使用 python 读取/获取数据(我能够使用 js 来完成)。但是我理解您对多个问题的评论(但是,它仍然可以称为单个问题:“我无法在 python 中操作数据”)。
-
我认为没有人能够添加文档中尚未包含的任何内容。您的出发点是实际尝试一件简单的事情,如果这不符合您的预期,请发布您的一项实验的结果,并指出哪些不符合您的预期。
-
我将专门向您推荐 DocumentSnapshot 的 API 文档(在页面中搜索它),因为这似乎是您错过的内容。 googleapis.github.io/google-cloud-python/latest/firestore/…
-
@jay serviceKey.json 是一个凭证 JSON 文件,您可以在
Actions下的https://console.cloud.google.com/iam-admin/serviceaccounts?authuser=0&project=YOUR_PROJECT_NAME生成它->Create Key。这将创建一个 JSON 文件,您将其保存到某个地方(例如/home/jay/project/test/testServiceKey.json),这就是手册中提到的path/to/serviceKey.json。有关此类文件的示例,请参见上述问题中的步骤 B)。
标签: python firebase google-cloud-firestore firebase-admin