示例应用会记录、检索和显示访问者的 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"]],["最后更新时间 (UTC):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."]]],[]]