【问题标题】:App Engine NDB Simple Create Read UpdateApp Engine NDB 简单创建读取更新
【发布时间】:2014-04-21 03:30: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 CRUD。

【问题讨论】:

  • 如果有任何东西,您是否检查过数据存储查看器?

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


【解决方案1】:

通过登录开发和生产开始调试。

简单示例:

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 是回购协议

【讨论】:

  • 对于获取请求 - 我想 Storage.get_by_id('name') 将是正确的使用方法。谢谢!
  • @benshope 是的。尽管我更喜欢使用您使用的密钥构造方法。它更加一致。
猜你喜欢
  • 2014-03-06
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多