App Engine NDB 简单的创建、读取与更新

1 投票
1 回答
698 浏览
提问于 2025-04-17 22:28

在Python的Google App Engine中,存储一个可以编辑的字符串最好的方法是什么呢?我尝试使用NDB,设置了一个路由来创建、读取和更新这个字符串。但是,这似乎不太管用:

class Storage(ndb.Model):
    content  = ndb.StringProperty()

class CreateReadUpdate(webapp2.RequestHandler):
    def get(self):
        entity = ndb.Key(Storage, 'name').get()
        self.response.out.write(entity.content)
    def post(self):
        content = json.loads(self.request.body).get('content')
        entity = ndb.Key(Storage, 'name').get()
        if not entity:
            entity = Storage(content='')
        entity.content = content
        entity.put()

我不太确定在这个环境中怎么调试。所以我得问一下,这里到底出了什么问题?我只想要一个最简单的App Engine的增删改查功能。

1 个回答

3

开始调试时,可以在开发环境和生产环境中使用日志记录。

简单的例子:

import logging

...

logging.info(entity.property)

你的问题是,你在保存实体时没有提供一个关键名称或ID(如果其他部分都没问题的话),所以当你尝试显示它时就什么都看不到。

把你的保存逻辑改成这样:

def post(self):
    content = json.loads(self.request.body).get('content')
    entity = ndb.Key(Storage, 'name').get()
    if not entity:
        entity = Storage(id='name', content='') # see here
    entity.content = content
    entity.put()

或者你也可以这样做:

def post(self):
    content = json.loads(self.request.body).get('content')
    entity = Storage.get_or_insert('name')
    entity.content = content
    entity.put()

如果你需要一个例子,可以查看之前的回答中的“如何在GAE中使用AJAX”,还有这个是代码库。

撰写回答