在 Google App Engine 项目中使用 Firestore

问题描述 投票:0回答:2

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

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

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

google-app-engine google-cloud-platform google-cloud-firestore
2个回答
7
投票

是的,最佳实践是使用 Firestore Rest API。

关于身份验证,应用程序引擎服务有其默认服务帐户,您可以在应用程序引擎页面上找到该帐户。 只需向项目 B 上的此服务帐户授予访问和写入 firestore 的权限,Lib SDK 将顺利处理所有事情!

您使用哪种语言?所以我可以用演示代码编辑我的答案

编辑1:

您可能误解了项目的概念。项目是一个可以使用服务的信封。在此示例中:您可以拥有一个包含 Firestore 和 App Engine 的 GCP 项目。

编辑2:

正如我所想,Google 演示存储库上有一个代码示例。看一下这个 ! https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/firestore


2
投票

访问 Google Cloud Firestore 的最佳方式是使用其客户端库(而不是 REST API)。我的意思是,您可以使用 REST API,这根本没有任何问题,但是它通常涉及您更多的编码,而客户端库则完成更多繁重的工作。

使用客户端库,设置 API 客户端是一件简单的事情,然后访问它就很简单。下面是一个简单 Web 应用程序的 Python 代码片段,该应用程序跟踪所有网站访问,只是为了向您展示基本用法(适用于 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

您没有指定应用程序的语言,因此如果您使用 Java、Go、Node.js、PHP 或 Ruby,使用方法类似,您可以将此 Python 示例用作“伪代码”。

我没有对代码进行太多注释,但它足够基本,您将了解它是如何工作的。更正式地说,这里是官方的 Firestore 快速入门教程 和后续的 更深入的深入教程,它比我的小代码片段更详细地介绍了所有内容。

FWIW,我尝试想出同样的方法,但使用 REST API 并遇到了一些权限问题(403)。也许我稍后会再次访问。 (仅仅尝试15-20分钟对我来说太难了。)

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

© www.soinside.com 2019 - 2024. All rights reserved.