Python ndb 数据存储将列表放入数据存储

Python ndb Datastore put list to Datastore

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

我似乎无法在数据存储中获取以前的注释,并且一直在翻阅 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)

提前致谢。并且请不要因为您比我聪明而认为我的问题很愚蠢而将我打分。我在尝试。如果您不想回答,请继续。

首先要注意的是,appengine 数据存储是最终一致的。阅读这篇文章: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)