使用 Firestore

Firestore 是 NoSQL 文件資料庫,專為自動調整資源配置、提供高效能,以及協助輕鬆開發應用程式而打造。Firestore 是 Datastore 的後繼產品,建議用於所有新應用程式。Firestore 提供多種介面,包括與 Datastore 相容的 API,可支援以 Datastore 建構的舊版程式碼。

本文說明如何使用 Cloud 用戶端程式庫,在 Datastore 模式資料庫中儲存及擷取資料。 您可以在 app.yaml 檔案中指定執行階段版本和作業系統,針對任何支援的 Python 版本使用本指南中的範例應用程式。

事前準備和設定

  • 設定環境和專案,瞭解如何在 App Engine 中建構應用程式。請記下並儲存您的專案 ID,因為您需要這些資訊才能執行本文說明的範例應用程式。

複製存放區

下載 (複製) 此範例:

  git clone https://github.com/GoogleCloudPlatform/python-docs-samples
  cd python-docs-samples/appengine/flexible/datastore

編輯專案設定並設定依附元件

requirements.txt 檔案中加入 google-cloud-datastore 程式庫。這是 Datastore 模式的用戶端程式庫。

Flask==3.1.3; python_version >= '3.9'
google-cloud-datastore==2.20.2
gunicorn==23.0.0

應用程式程式碼

範例應用程式會記錄、擷取及顯示訪客 IP。您可以看到記錄項目是雙欄位類別,其中註明類型 visit,並使用 put 指令儲存於 Datastore 模式中。接著,系統會使用 query() 指令擷取資料儲存庫,以遞減順序呈現最近十個造訪記錄。

@app.route("/")
def index():
    ds = datastore.Client()

    user_ip = request.remote_addr

    # Keep only the first two octets of the IP address.
    if is_ipv6(user_ip):
        user_ip = ":".join(user_ip.split(":")[:2])
    else:
        user_ip = ".".join(user_ip.split(".")[:2])

    entity = datastore.Entity(key=ds.key("visit"))
    entity.update(
        {
            "user_ip": user_ip,
            "timestamp": datetime.datetime.now(tz=datetime.timezone.utc),
        }
    )

    ds.put(entity)
    query = ds.query(kind="visit", order=("-timestamp",))

    results = []
    for x in query.fetch(limit=10):
        try:
            results.append("Time: {timestamp} Addr: {user_ip}".format(**x))
        except KeyError:
            print("Error with result format, skipping entry.")

    output = "Last 10 visits:\n{}".format("\n".join(results))

    return output, 200, {"Content-Type": "text/plain; charset=utf-8"}

使用 index.yaml 檔案

範例應用程式會執行查詢。 更精細的 Datastore 模式查詢作業需要一或多個索引,因此您必須在與應用程式一併上傳的 index.yaml 檔案中指定這些索引。這個檔案可透過手動方式建立,或是在本機上測試應用程式時自動產生。

本機測試

如果需要在本機環境中開發及測試您的應用程式,可以使用 Datastore 模式模擬器

瞭解詳情

如需 Datastore 模式的完整資訊,包括最佳化與相關概念,請參閱 Firestore (Datastore 模式) 說明文件