Lee Gellie Lee Gellie - 3 months ago 37
Python Question

Python ndb Datastore put list to Datastore

I am trying to populate a Datastore with my older course notes so that in future I can add notes like a comments board or guestbook.

I can't seem to get the previous notes in the Datastore and have been trolling over GAE documentation and searching the web to no avail.

Here is my code, if anyone can point me in the right direction to fix I would be most greatful.

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])

class MainHandler(webapp2.RequestHandler):
def get(self):
<title>Lee's Notes</title>
<link href="../styles.css" rel="stylesheet" type="text/css">
<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)

Thanks in advance. And please don't mark me down because you are smarter than me and think my question is stupid. I am trying. If you don't want to answer just move on.


First thing to note is that the appengine datastore is eventually consistent. Read this article: https://cloud.google.com/appengine/docs/python/datastore/structuring_for_strong_consistency?hl=en

For you're case you don't really need a query. Make a good index and then retrieval is a lot easier with a key.get(). Note, this is assuming you don't want to use 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])

Retrieval then becomes:

entity_key = CourseData.build_key(4)