对经过身份验证的用户的数据进行个性化设置

区域 ID

REGION_ID 是 Google 根据您在创建应用时选择的区域分配的缩写代码。此代码不对应于国家/地区或省,尽管某些区域 ID 可能类似于常用国家/地区代码和省代码。对于 2020 年 2 月以后创建的应用,REGION_ID.r 包含在 App Engine 网址中。对于在此日期之前创建的现有应用,网址中的区域 ID 是可选的。

详细了解区域 ID

使用经过身份验证的用户信息来存储和检索特定于用户的数据,并让每位用户在使用您的网络服务时得到个性化的体验。

在上一步中,您更新了网络服务,可显示所有用户的最近十个请求。此步骤中将使用经过身份验证的用户信息来更新网络服务,以便该页面仅列出当前经过身份验证的用户发出的最近十个请求。

准备工作

如果您已完成本指南中前面的所有步骤,请跳过此部分。 否则,请完成以下任一操作:

存储和检索特定于用户的数据

您可以使用 Datastore 模式的 Firestore (Datastore) 祖先实体指示数据已连接到特定用户,从而以分层方式组织 Datastore 数据。

为此,请完成以下步骤:

  1. 更新 store_timefetch_time 方法,以使用 Cloud Datastore 祖先实体来存储和检索 visit 实体:

    datastore_client = datastore.Client()
    
    def store_time(email, dt):
        entity = datastore.Entity(key=datastore_client.key("User", email, "visit"))
        entity.update({"timestamp": dt})
    
        datastore_client.put(entity)
    
    def fetch_times(email, limit):
        ancestor = datastore_client.key("User", email)
        query = datastore_client.query(kind="visit", ancestor=ancestor)
        query.order = ["-timestamp"]
    
        times = query.fetch(limit=limit)
    
        return times
    
    

    每个 visit 实体现在都有一个与之相连的祖先实体。这些祖先实体是 Datastore 实体,用于表示各个经过身份验证的用户。每个祖先实体的键都包含 User 种类和自定义 ID,即经过身份验证的用户的电子邮件地址。使用祖先键查询数据库中仅与特定用户关联的时间。

  2. 更新 store_times 方法中的 root 方法调用并将其移至 id_token 条件内,以便在服务器对用户进行身份验证后才使其运行:

    @app.route("/")
    def root():
        # Verify Firebase auth.
        id_token = request.cookies.get("token")
        error_message = None
        claims = None
        times = None
    
        if id_token:
            try:
                # Verify the token against the Firebase Auth API. This example
                # verifies the token on each page load. For improved performance,
                # some applications may wish to cache results in an encrypted
                # session store (see for instance
                # http://flask.pocoo.org/docs/1.0/quickstart/#sessions).
                claims = google.oauth2.id_token.verify_firebase_token(
                    id_token, firebase_request_adapter
                )
    
                store_time(claims["email"], datetime.datetime.now(tz=datetime.timezone.utc))
                times = fetch_times(claims["email"], 10)
    
            except ValueError as exc:
                # This will be raised if the token is expired or any other
                # verification checks fail.
                error_message = str(exc)
    
        return render_template(
            "index.html", user_data=claims, error_message=error_message, times=times
        )
    
    

配置索引

Datastore 基于索引进行查询。对于简单实体,Datastore 会自动生成这些索引。但它无法为较复杂的实体(包括具有祖先实体的实体)自动生成索引。 因此,您需要为 visit 实体手动创建索引,以便 Datastore 能够执行涉及 visit 实体的查询。

要为 visit 实体创建索引,请完成以下步骤:

  1. 在项目的根目录中创建 index.yaml 文件(例如 building-an-app),并添加以下索引:

    # Copyright 2021 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    indexes:
    
    - kind: visit
      ancestor: yes
      properties:
      - name: timestamp
        direction: desc
    
  2. 通过运行以下命令并按照提示在 Datastore 中部署 index.yaml 索引:

    gcloud datastore indexes create index.yaml
    

Datastore 可能需要一段时间才能创建索引。如果在将网络服务部署到 App Engine 之前创建索引,则您可以使用这些索引在本地进行测试,如果查询需要的索引仍在构建过程中,还可防止此类查询发生可能的异常。

查看索引

如需详细了解如何配置 Datastore 索引,请参阅配置 Datastore 索引

测试网络服务

通过在虚拟环境中本地运行 Web 服务来对其进行测试:

  1. 在项目的主目录中运行以下命令,以运行 Web 服务。 如果您尚未为本地测试设置虚拟环境,请参阅测试 Web 服务

    python main.py
    
  2. 在网络浏览器中输入以下地址,查看您的网络服务:

    http://localhost:8080
    

部署网络服务

在本地正常运行 Datastore 后,您可以将 Web 服务重新部署到 App Engine。

app.yaml 文件所在项目的根目录运行以下命令:

gcloud app deploy

所有流量都会自动路由到您部署的新版本。

如需详细了解如何管理版本,请参阅管理服务和版本

查看您的服务

如需快速启动浏览器并通过 https://PROJECT_ID.REGION_ID.r.appspot.com 访问您的 Web 服务,请运行以下命令:

gcloud app browse

后续步骤

恭喜!您已成功构建网络服务,该服务使用 Datastore 数据存储和 Firebase 身份验证为经过身份验证的用户提供个性化网页。

现在,您可通过关停、禁用或停用项目的结算功能来进行清理。