Skip to main content
 首页 » 编程设计

Python ndb Datastore 将列表放入 Datastore

2025年05月04日12zhenyulu

我正在尝试用我以前的类(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)