@app.route("/")defroot():# Store the current access time in Datastore.store_time(datetime.datetime.now(tz=datetime.timezone.utc))# Fetch the most recent 10 access times from Datastore.times=fetch_times(10)returnrender_template("index.html",times=times)
更新 templates/index.html 檔案,輸出每個實體的 timestamp:
<h2>Last 10 visits</h2>
{% for time in times %}
<p>{{ time['timestamp'] }}</p>
{% endfor %}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[[["\u003cp\u003e\u003ccode\u003eREGION_ID\u003c/code\u003e is a Google-assigned code based on the region selected when creating an app, not corresponding to a specific country or province, and it is included in App Engine URLs for apps created after February 2020.\u003c/p\u003e\n"],["\u003cp\u003eThis guide provides instructions on updating a web service to use Firestore in Datastore mode for storing and retrieving data, specifically page request data, and it is recommended to use Cloud Run for new Python web services on Google Cloud.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves using Datastore client libraries to create entities with keys and properties to store data, and retrieving the ten most recent entries based on time stamps.\u003c/p\u003e\n"],["\u003cp\u003eTo test the web service, dependencies must be installed, the web service run locally, and you can view the entities created in the Google Cloud console.\u003c/p\u003e\n"],["\u003cp\u003eOnce tested, the web service can be deployed to App Engine using the \u003ccode\u003egcloud app deploy\u003c/code\u003e command, with the next step being to integrate Firebase.\u003c/p\u003e\n"]]],[],null,["# Store and retrieve data\n\n### Region ID\n\nThe \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e is an abbreviated code that Google assigns\nbased on the region you select when you create your app. The code does not\ncorrespond to a country or province, even though some region IDs may appear\nsimilar to commonly used country and province codes. For apps created after\nFebruary 2020, \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e`.r` is included in\nApp Engine URLs. For existing apps created before this date, the\nregion ID is optional in the URL.\n\nLearn more\n[about region IDs](/appengine/docs/standard/python3/how-requests-are-routed#region-id). \nOK\n\n\u003cbr /\u003e\n\n| **Note:** If you are deploying a new Python web service to Google Cloud, we recommend getting started with [Cloud Run](/run/docs/quickstarts/build-and-deploy/deploy-python-service).\n\nUpdate your web service to connect to and handle data through\nFirestore in Datastore mode (Datastore). Use the [Datastore client\nlibraries](/datastore/docs/reference/libraries#client-libraries-install-python)\nto connect your web service to Datastore, a non-relational (NoSQL)\ndatabase built for automatic scaling, high performance, and ease of application\ndevelopment.\n\nIn this step, you update your web service so that it stores page request data in\nDatastore and then displays a list of the last ten page requests.\nThe goal here is to get data storage working for your web service\nbefore you add Firebase Authentication and personalize data storage for\nauthenticated users.\n\nBefore you begin\n----------------\n\nIf you have completed all the previous steps in this guide, skip this section.\nOtherwise, complete one of the following:\n\n- Start from [Build a Python 3 App](/appengine/docs/standard/python3/building-app)\n and complete all the steps leading up to this one.\n\n- If you already have a\n [Google Cloud project](/appengine/docs/standard/python3/building-app/creating-gcp-project),\n you can continue by downloading a copy of the web service:\n\n 1. Download the sample application repository using\n [Git](https://git-scm.com/):\n\n git clone https://github.com/GoogleCloudPlatform/python-docs-samples\n\n Alternatively, you can [download the sample](https://github.com/GoogleCloudPlatform/python-docs-samples/archive/master.zip) as a zip\n file and then extract it.\n 2. Navigate to the directory that contains a copy of the files from the\n previous step:\n\n cd python-docs-samples/appengine/standard_python3/building-an-app/building-an-app-1\n\n 3. Enable the Datastore API:\n\n gcloud services enable datastore.googleapis.com\n\nStore and retrieve Datastore entities\n-------------------------------------\n\nStore and retrieve site request times as Datastore entities by\ncompleting the following:\n\n1. Add the following code to your `main.py` file:\n\n from google.cloud import https://cloud.google.com/python/docs/reference/datastore/latest/\n\n datastore_client = https://cloud.google.com/python/docs/reference/datastore/latest/.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html()\n\n def store_time(dt):\n entity = https://cloud.google.com/python/docs/reference/datastore/latest/.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.entity.Entity.html(key=datastore_client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_key(\"visit\"))\n entity.update({\"timestamp\": dt})\n\n datastore_client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_put(entity)\n\n\n def fetch_times(limit):\n query = datastore_client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_query(kind=\"visit\")\n query.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.query.Query.html#google_cloud_datastore_query_Query_order = [\"-timestamp\"]\n\n times = query.fetch(limit=limit)\n\n return times\n\n The `store_time` method above uses the Datastore client libraries\n to create a new entity in Datastore. Datastore\n entities are data objects that consist of *keys* and *properties* . In this\n case, the entity's key is its custom *kind* , `visit`. The entity also has\n one property, `timestamp`, containing time of a page request.\n\n The `fetch_times` method uses the key `visit` to query\n the database for the ten most recent `visit` entities and then stores\n those entities in a list in descending order.\n2. Update your `root` method to call your new methods:\n\n @app.route(\"/\")\n def root():\n # Store the current access time in Datastore.\n store_time(datetime.datetime.now(tz=datetime.timezone.utc))\n\n # Fetch the most recent 10 access times from Datastore.\n times = fetch_times(10)\n\n return render_template(\"index.html\", times=times)\n\n3. Update your `templates/index.html` file to print the `timestamp` of\n each entity:\n\n \u003ch2\u003eLast 10 visits\u003c/h2\u003e\n {% for time in times %}\n \u003cp\u003e{{ time['timestamp'] }}\u003c/p\u003e\n {% endfor %}\n\n4. Ensure that your `requirements.txt` file includes all necessary dependencies:\n\n Flask==3.0.0\n google-cloud-datastore==2.15.1\n\nFor more information about Datastore entities, properties, and keys,\nsee [Entities, Properties, and Keys](/datastore/docs/concepts/entities).\nFor more information on using Datastore client libraries, see\n[Datastore Client Libraries](/datastore/docs/reference/libraries#client-libraries-install-python).\n\nTest your web service\n---------------------\n\nTest your web service by running it locally in a virtual environment:\n\n1. Run the following commands in your\n project's main directory to install new dependencies and run\n your web service.\n If you have not set up a virtual environment for local testing, see\n [testing your web service](/appengine/docs/standard/python3/building-app/writing-web-service#testing_your_web_service).\n\n pip install -r requirements.txt\n python main.py\n\n2. Enter the following address in your web browser to view your web service:\n\n http://localhost:8080\n\n | **Tip:** Refresh the page to create additional page requests and store more entities in Datastore.\n\nYou can view the entities that are created by your web service in the\nGoogle Cloud console:\n\n[Go to the Datastore entities page](https://console.cloud.google.com/datastore)\n\nDeploy your web service\n-----------------------\n\nNow that you have Datastore working locally, you can re-deploy your web\nservice to App Engine.\n\nRun the following command from the root directory of your project,\nwhere your `app.yaml` file is located: \n\n gcloud app deploy\n\nAll traffic is automatically routed to the new version you deployed.\n\nFor more information on managing versions,\nsee [Managing Services and Versions](/appengine/docs/standard/python3/building-app/deploying-web-service#managing_services_and_versions).\n\nView your service\n-----------------\n\nTo quickly launch your browser and access your web service at\n\n`https://`\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e`.`\u003cvar translate=\"no\"\u003e\u003ca href=\"#appengine-urls\" style=\"border-bottom: 1px dotted #999\" class=\"devsite-dialog-button\" data-modal-dialog-id=\"regional_url\" track-type=\"progressiveHelp\" track-name=\"modalHelp\" track-metadata-goal=\"regionalURL\"\u003eREGION_ID\u003c/a\u003e\u003c/var\u003e`.r.appspot.com`, run the following command: \n\n gcloud app browse\n\nNext Steps\n----------\n\nNow that you have Datastore working with your web service, you're ready\nto learn how to add Firebase to your web service."]]