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

时间:2015-08-09 16:31:25

标签: python google-app-engine google-cloud-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)

提前致谢。请不要标记我,因为你比我聪明,认为我的问题是愚蠢的。我在尝试。如果你不想回答继续前进。

1 个答案:

答案 0 :(得分:1)

首先要注意的是,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)
相关问题