範例應用程式會記錄、擷取及顯示訪客 IP。您可以看到記錄項目是雙欄位類別,其中註明類型 visit,且透過 put 指令儲存在 Datastore 模式中。然後,系統會使用 query() 指令,以遞減順序擷取最近的十筆造訪記錄。
@app.route("/")defindex():ds=datastore.Client()user_ip=request.remote_addr# Keep only the first two octets of the IP address.ifis_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=[]forxinquery.fetch(limit=10):try:results.append("Time: {timestamp} Addr: {user_ip}".format(**x))exceptKeyError:print("Error with result format, skipping entry.")output="Last 10 visits:\n{}".format("\n".join(results))returnoutput,200,{"Content-Type":"text/plain; charset=utf-8"}
[[["容易理解","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-05-13 (世界標準時間)。"],[[["Firestore in Datastore mode is a NoSQL document database optimized for server use cases and App Engine, making it ideal for applications primarily used within App Engine."],["Firestore in Native mode is better suited for mobile applications and those requiring real-time notifications, offering a different set of functionalities compared to Datastore mode."],["Using Datastore mode queries often requires defining indexes in an `index.yaml` file, which can be created manually or generated automatically during local testing of your application."],["Developers can use the Datastore mode emulator for local development and testing of applications, allowing for a simulated environment before deployment."],["Comprehensive information on Datastore mode, including optimizations and core concepts, can be found in the Firestore in Datastore mode documentation."]]],[]]