【问题标题】:Google Firebase: Get, update or create documents using PythonGoogle Firebase:使用 Python 获取、更新或创建文档
【发布时间】:2019-07-20 18:02:38
【问题描述】:

我无法使用 Python 在 Google Firebase (Cloud Firestore) 数据库中获取、更新或创建文档。

我有什么:

A) 带有集合和文档的数据库(在网络上手动插入):

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 blogthe 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&amp;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


【解决方案1】:

再过一个晚上,我可以回答自己(感谢 Doug 在讨论中的提示):

对我来说问题是有两个类似的文档(对于 Python 部分,第二个比 Python 更广泛)。我发现第一个更有帮助,但有时我也需要使用第二个的一部分:

1) 访问文档:

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)

database = firestore.client()
col_ref = database.collection('items') # col_ref is CollectionReference
results = col_ref.where('name', '==', 'Pepa').get() # one way to query
results = col_ref.order_by('date',direction='DESCENDING').limit(1).get() # another way - get the last document by date
for item in results:
    print(item.to_dict())
    print(item.id)
# item is DocumentSnapshot
# note: the documentation says get() is depreciated in favour of stream(), however stream() did not work for me

2) 仍然不知道,但我不需要它,因为 1) 工作正常。

3) 更新或创建文档:

# Continuing from 1)

# Udpdate:
doc = col_ref.document(item.id) # doc is DocumentReference
field_updates = {"description": "Updated description"}
doc.update(field_updates)

# Create:
import datetime
new_values = {
    "name": "Newbie",
    "description": "Shiny New Document",
    "date": datetime.datetime.now()
}
col_ref.document().create(new_values)

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多