為已驗證使用者提供個人化資料

區域 ID

REGION_ID 是 Google 根據您在建立應用程式時選取的地區所指派的簡寫代碼。雖然某些區域 ID 可能看起來與常用的國家/地區代碼相似,但此代碼並非對應國家/地區或省份。如果是 2020 年 2 月後建立的應用程式,App Engine 網址會包含 REGION_ID.r。如果是在此日期之前建立的現有應用程式,網址中則可選擇加入地區 ID。

進一步瞭解區域 ID

使用已驗證使用者的資訊儲存及擷取使用者特定資料,並個人化每位使用者的網路服務使用體驗。

在之前的步驟中,您已將網路服務更新為顯示來自所有使用者的最後十個要求。在這個步驟中,您會使用已驗證使用者的資訊更新網路服務,使頁面僅顯示由目前已驗證使用者提出之最後十個要求的清單。

事前準備

如果您已完成本指南先前提過的所有步驟,請跳過本節。 否則,請完成下列其中一個步驟:

  • 從「建構 Python 3 應用程式」開始,完成這個步驟之前的所有步驟。

  • 如果您已經有 Google Cloud 專案,接下來可以下載網路服務的複本並新增 Firebase:

    1. 使用 Git 下載範例應用程式存放區:

      git clone https://github.com/GoogleCloudPlatform/python-docs-samples
      

      您也可以下載 zip 格式的範例,然後解壓縮該檔案。

    2. 前往包含上一步驟檔案複本的目錄:

      cd python-docs-samples/appengine/standard_python3/building-an-app/building-an-app-3
      
    3. 將 Firebase 新增至 Google Cloud 專案和網路服務

儲存及擷取使用者特定資料

您可以使用 Datastore 模式的 Firestore (Datastore) 祖系,指出資料已連結至特定使用者,進而讓您以階層化的方式整理 Datastore 資料。

如要這樣做,請按照下列步驟進行:

  1. 更新 store_timefetch_time 方法,以使用 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,且該 ID 為已驗證使用者的電子郵件地址。使用祖系金鑰的情況下,您可以只查詢資料庫中與特定使用者相關聯的時間。

  2. root 方法中更新 store_times 方法呼叫,並將其移到 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. 在專案的根目錄 (例如 building-an-app) 中建立 index.yaml 檔案,然後新增下列索引:

    # 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 索引」一文。

測試您的網路服務

請在虛擬環境中本機執行網路服務,以便進行測試:

  1. 在專案的主要目錄中執行下列指令,執行網路服務。如果您尚未設定本機測試用的 virtualenv,請參閱測試您的網路服務

    python main.py
    
  2. 請在網路瀏覽器中輸入下列網址,以便查看網路服務:

    http://localhost:8080
    

部署您的網路服務

現在您已在本機執行 Datastore,接下來可以將網路服務重新部署至 App Engine。

您可以在 app.yaml 檔案所在的專案根目錄中執行下列指令:

gcloud app deploy

系統會自動將所有流量轉送至您部署的新版本。

如要進一步瞭解如何管理版本,請參閱「管理服務和版本」。

查看服務

如要快速啟動瀏覽器並前往 https://PROJECT_ID.REGION_ID.r.appspot.com 使用網路服務,請執行下列指令:

gcloud app browse

後續步驟

恭喜!您已成功建構網路服務,進而使用 Datastore 資料儲存與 Firebase 驗證,向已驗證使用者提供個人化的網頁。

現在您可以關閉、停用專案或停用計費功能來清除所用資源。