1

不确定我是否应该在标题上说父值或祖先,但这就是我想要做的。

我正在学习在 Google App Engine 中使用 Python。当我在留言簿教程中查看此页面的内容时,我想知道是否可以通过列出所有可能创建的留言簿来增强它。

为了提供一些上下文,这就是示例代码的工作方式。该应用程序呈现一个页面,允许您创建留言簿条目,以及为当前或将来的条目切换/创建新留言簿。我认为添加列出所有当前存储的留言簿以动态生成链接列表以查看每个留言簿的功能会很简单。

我认为这很简单,但我正在尝试,但我无法弄清楚。如何查询数据存储区以提供所有可用“留言簿”的列表,以便我可以动态构建链接?如果留言簿称为 guestbook_2,则 url 看起来像这样“?guestbook_name=guestbook_2”。

这是应用程序的代码(我添加了字符串“INSERT LIST HERE”,我想在其中添加我刚才提到的链接列表):

import cgi
import urllib

from google.appengine.api import users
from google.appengine.ext import ndb

import webapp2


MAIN_PAGE_FOOTER_TEMPLATE = """\
<form action="/sign?%s" method="post">
  <div><textarea name="content" rows="3" cols="60"></textarea></div>
  <div><input type="submit" value="Sign Guestbook"></div>
</form>

<hr>

<form>Guestbook name (you can create your own guestbook here):
  <input value="%s" name="guestbook_name">
  <input type="submit" value="switch">
</form>

<a href="%s">%s</a>

<br><br>
List of guestbooks: %s

  </body>
</html>
"""

DEFAULT_GUESTBOOK_NAME = 'default_guestbook'


# We set a parent key on the 'Greetings' to ensure that they are all in the same
# entity group. Queries across the single entity group will be consistent.
# However, the write rate should be limited to ~1/second.

def guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME):
    """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
    return ndb.Key('Guestbook', guestbook_name)


class Greeting(ndb.Model):
    """Models an individual Guestbook entry with author, content, and date."""
    author = ndb.UserProperty()
    content = ndb.StringProperty(indexed=False)
    date = ndb.DateTimeProperty(auto_now_add=True)


class MainPage(webapp2.RequestHandler):

    def get(self):
        self.response.write('<html><body>')
        guestbook_name = self.request.get('guestbook_name',
                                          DEFAULT_GUESTBOOK_NAME)

        # Ancestor Queries, as shown here, are strongly consistent with the High
        # Replication Datastore. Queries that span entity groups are eventually
        # consistent. If we omitted the ancestor from this query there would be
        # a slight chance that Greeting that had just been written would not
        # show up in a query.
        greetings_query = Greeting.query(
            ancestor=guestbook_key(guestbook_name)).order(-Greeting.date)
        greetings = greetings_query.fetch(10)

        for greeting in greetings:
            if greeting.author:
                self.response.write(
                        '<b>%s</b> wrote:' % greeting.author.nickname())
            else:
                self.response.write('An anonymous person wrote:')
            self.response.write('<blockquote>%s</blockquote>' %
                                cgi.escape(greeting.content))

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'


        # Write the submission form and the footer of the page
        sign_query_params = urllib.urlencode({'guestbook_name': guestbook_name})
        self.response.write(MAIN_PAGE_FOOTER_TEMPLATE %
                            (sign_query_params, 
                            cgi.escape(guestbook_name),
                             url, 
                             url_linktext,
                             "INSERT LIST HERE"
                             ))


class Guestbook(webapp2.RequestHandler):

    def post(self):
        # We set the same parent key on the 'Greeting' to ensure each Greeting
        # is in the same entity group. Queries across the single entity group
        # will be consistent. However, the write rate to a single entity group
        # should be limited to ~1/second.
        guestbook_name = self.request.get('guestbook_name',
                                          DEFAULT_GUESTBOOK_NAME)
        greeting = Greeting(parent=guestbook_key(guestbook_name))

        if users.get_current_user():
            greeting.author = users.get_current_user()

        greeting.content = self.request.get('content')
        greeting.put()

        query_params = {'guestbook_name': guestbook_name}
        self.redirect('/?' + urllib.urlencode(query_params))


application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/sign', Guestbook),
], debug=True)
4

1 回答 1

0

只需将留言簿名称存储在某处,或者最简单的方法是您可以获取所有问候语的密钥以获取父级,例如

guestbooks = [greeting.key().parent().name() for greeting in Greeting.all(keys_only=True)]
于 2013-08-24T05:39:37.463 回答