App Engine NDB简单创建读取更新

时间:2014-03-15 19:36:22

标签: python google-app-engine google-cloud-datastore webapp2

在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 CRUD。

1 个答案:

答案 0 :(得分:3)

通过登录dev和on production开始调试。

简单示例:

import logging

...

logging.info(entity.property)

您的问题是您没有为要保存的实体提供key_name / 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()

如果您需要示例,请检查上一个答案中的“How to use GAE with AJAX”,this是回购