gpt4 book ai didi

Python ndb Datastore 将列表放入 Datastore

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:49 25 4
gpt4 key购买 nike

我正在尝试用我以前的类(class)笔记填充数据存储,以便将来我可以添加评论板或留言簿等笔记。

我似乎无法在数据存储中获取以前的注释,并且一直在翻阅 GAE 文档并在网上搜索无济于事。

这是我的代码:

import time
import cgi
import os
import jinja2
import webapp2
from google.appengine.ext import ndb

jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)

dataEntery = [[1, 4, 'Networks','''
<p>A network is a group of entities that can communicate, even </p>'''],
[2, 4, 'Measuring Networks','''
<p>The two main ways of measuring a network are;</p>
'''], etc]

class CourseData(ndb.Model):
id_index = ndb.IntegerProperty()
stage_number = ndb.IntegerProperty()
note_title = ndb.StringProperty(indexed=False)
note_content = ndb.StringProperty(indexed=False)

for a in dataEntery:
newEntry = CourseData(id_index=a[0], stage_number=a[1], note_title=a[2], note_content=a[3])
newEntry.put()
time.sleep(.2)

class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write('''
<!DOCTYPE HTML>
<html>
<head>
<title>Lee's Notes</title>
<link href="../styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 class="opener">Lee's Notes on Intro to Programming</h1>
''')
query = CourseData.query(stage_number == 4).fetch()
self.response.out.write('<article id="note%s"><h2>%s</h2>' % cgi.escape(query.note_title), cgi.escape(query.note_title))
self.response.out.write('%s</article>' % cgi.escape(query.note_content))

app = webapp2.WSGIApplication([
('/', MainHandler)], debug=True)

最佳答案

首先要注意的是应用引擎数据存储是最终一致的。阅读这篇文章:https://cloud.google.com/appengine/docs/python/datastore/structuring_for_strong_consistency?hl=en

如果您真的不需要查询。创建一个好的索引,然后使用 key.get() 检索就容易多了。请注意,这是假设您不想使用 id_index...

for a in dataEntery:
entityKey = ndb.Key(CourseData._get_kind(), stage_number=a[1])
newEntry = CourseData(key=entityKey, id_index=a[0], stage_number=a[1], note_title=a[2], note_content=a[3])
newEntry.put()

然后检索变成:

entity_key = CourseData.build_key(4)

关于Python ndb Datastore 将列表放入 Datastore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com