REGION_ID는 앱을 만들 때 선택한 리전을 기준으로 Google에서 할당하는 축약된 코드입니다. 일부 리전 ID는 일반적으로 사용되는 국가 및 주/도 코드와 비슷하게 표시될 수 있지만 코드는 국가 또는 주/도와 일치하지 않습니다. 2020년 2월 이후에 생성된 앱의 경우 REGION_ID.r이 App Engine URL에 포함됩니다. 이 날짜 이전에 만든 기존 앱의 경우 URL에서 리전 ID는 선택사항입니다.
Datastore 모드의 Firestore(Datastore)를 통해 데이터를 연결하고 처리하도록 웹 서비스를 업데이트합니다. Datastore 클라이언트 라이브러리를 사용하여 자동 확장, 고성능, 간편한 애플리케이션 개발을 위해 설계된 비관계형(NoSQL) 데이터베이스인 Datastore에 웹 서비스를 연결합니다.
이 단계에서는 페이지 요청 데이터를 Datastore에 저장한 후 최근의 페이지 요청 10개의 목록을 표시하도록 웹 서비스를 업데이트합니다.
여기서는 Firebase 인증을 추가하고 인증된 사용자를 위해 데이터 스토리지를 맞춤설정하기 전에 웹 서비스용 데이터 스토리지를 작동시키는 것을 목표로 합니다.
시작하기 전에
이 가이드의 이전 단계를 모두 완료했다면 이 섹션을 건너뜁니다.
그렇지 않으면 다음 중 하나를 완료합니다.
위의 store_time 메서드는 Datastore 클라이언트 라이브러리를 사용하여 Datastore에 새 항목을 만듭니다. Datastore 항목은 키 및 속성으로 구성되는 데이터 객체입니다. 이 경우 항목 키는 커스텀 종류인 visit입니다. 항목에는 페이지 요청 시간이 포함된 timestamp라는 속성도 하나 있습니다.
fetch_times 메서드는 visit 키를 사용하여 가장 최근의 visit 항목 10개를 데이터베이스에 쿼리한 후 이러한 항목을 내림차순으로 목록에 저장합니다.
root 메서드를 업데이트하여 새 메서드를 호출합니다.
@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(UTC)"],[[["\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."]]