在Google App Engine项目中使用Firestore

6

我想在Google App Engine项目中作为附加数据库访问Firestore的实时数据库。

从Google App Engine后端写入Firestore的最佳方法是什么?使用Firestore Rest API好吗?还是有更好的方法?

如何在两个项目之间进行身份验证?因为据我了解,Google App Engine项目和Firestore项目是两个不同的项目。

2个回答

7
是的,最佳实践是使用Firestore Rest API。
关于身份验证,应用程序引擎服务具有其默认服务帐户,您可以在应用程序引擎页面上找到。只需授予该服务帐户在项目B上访问并写入Firestore的权限,Lib SDK就能顺利处理一切!
你使用哪种语言?这样我就可以用演示代码编辑我的答案了。
编辑1:
你可能误解了项目的概念。项目是一个信封,在其中你可以使用服务。在这个例子中:你可以拥有一个包含你的Firestore和应用程序引擎的单个GCP项目。
编辑2:
正如我所想的那样,Google演示存储库中有代码示例。看看这个!https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/firestore

1
Java - 还需要8个字符 - Micro
1
关于您的第二次编辑,在您发布的链接中写道:“注意:您不能在同一项目中同时使用Cloud Firestore和Cloud Datastore,这可能会影响使用App Engine的应用程序。尝试使用不同的项目使用Cloud Firestore。” - 所以这就是我的情况。我有Datastore并想要使用Firestore。所以看起来我需要两个项目。不过您提供的链接还是很有帮助的。 - Micro

2
最佳访问Google Cloud Firestore的方式是使用其客户端库(而不是REST API)。我的意思是,你可以使用REST API,这并没有什么错,但通常需要更多的编程工作,而客户端库会更多地处理繁重的任务。
使用客户端库,设置API客户端只需一行代码,然后访问非常简单。下面是一个简单的Web应用程序代码片段,用于跟踪所有网站访问情况,以展示基本用法(适用于2.x和3.x):
'fs_visits.py -- Cloud Firestore sample Python snippet for web visit registry'

from __future__ import print_function
from datetime import datetime
from google.cloud import firestore

def store_visit(timestamp):
    visits = fs_client.collection('visitX')
    visits.add({'timestamp': timestamp})

def fetch_visits(limit):
    visits = fs_client.collection('visitX')
    return visits.order_by(u'timestamp',
            direction=firestore.Query.DESCENDING).limit(limit).stream()

TOP = 10                            # limit to 10 results
fs_client = firestore.Client()         # create Cloud Firestore client

if __name__ == '__main__':
    print('** Adding another visit')
    store_visit(datetime.now())          # store a "visit" object
    print('** Last %d visits' % TOP)
    times = fetch_visits(TOP)            # fetch most recent "visits"
    for obj in times:
        print('-', obj.to_dict()['timestamp'])

我运行它时得到的样本输出如下:

$ python fs-snip.py
** Adding another visit
** Last 10 visits
- 2020-03-23 09:14:09.742027+00:00
- 2020-03-11 01:06:47.103570+00:00
- 2020-03-11 01:03:29.487141+00:00
- 2020-03-11 01:03:16.583822+00:00
- 2020-03-11 01:02:35.844559+00:00
- 2020-03-11 00:59:51.939175+00:00
- 2020-03-11 00:59:39.874525+00:00
- 2020-03-11 00:58:51.127166+00:00
- 2020-03-11 00:58:34.768755+00:00
- 2020-03-11 00:58:21.952063+00:00

虽然它没有解释太多,但如果您能理解这段代码,您将对其工作原理有所了解。这里是官方的快速入门教程和一个后续的深入学习教程,比我的小代码片段详细得多。

顺便说一句,我尝试使用REST API来做同样的事情,但遇到了一些权限问题(403)。也许我以后会再次尝试。(只尝试了15-20分钟,任务太难了。)

就项目而言,Google Cloud(平台)项目是应用程序及其资源的单一逻辑实体。目前,每个项目可以拥有一个App Engine应用程序和一个NoSQL数据库(Cloud Datastore [现在称为Datastore模式下的Cloud Firestore]或Cloud Firestore [称为本机模式下的Cloud Firestore]...由您选择)。这意味着它们都可以在同一个项目中,因此您不必担心跨项目权限问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接