2017-07-06 71 views
0

我试图用Google Cloud ndb和REST体系结构创建CRUD应用程序。JSON编码带密钥的NDB实体

因此,我有不同的API调用来创建和检索。

现在为了更新我需要在前端显示它们的实体,并给出一个标识符,所以ndb知道稍后要更新哪个实体。

我尝试用model.query得到实体,然后将它们编码为JSON具有扩展编码序列化datetimendb.Key

# JSONEncoder extension to handle datetime & ndb.Key 
class CustomJsonEncoder(json.JSONEncoder): 
    def default(self, obj): 
     if isinstance(obj, datetime): 
      return obj.strftime('%Y-%m-%d-%H-%M-%S') 
     if isinstance(obj, ndb.Key): 
      return obj.urlsafe() 
     return json.JSONEncoder.default(self, obj) 

# Get JSON data from ndb 
query = Card.query(Card.category==category, ancestor=ancestor_key()).fetch() 
cards = json.dumps([c.to_dict() for c in query], cls=CustomJsonEncoder) 
       self.response.headers['Content-Type'] = 'application/json' 
       self.response.out.write(cards) 

我现在的问题是实体键就会消失,并且不显示在json.dump了。我没有得到任何错误,它只是没有编码和传递。

打印时datetime对象显示正确。关于如何发送URL安全ndb密钥以及json.dump的任何想法?

回答

0

您正在倾销Card实体对象,其中不是包含各自的对象键。为了证实这只是临时添加一个logging语句这样您CustomJsonEncoder

  if isinstance(obj, ndb.Key): 
       logging.error('key found: %s' % obj.urlsafe()) 
       return obj.urlsafe() 

您需要的实体按键明确地添加到数据,如果你想他们是JSON编码。

或者你可以使用该实体的模型ComputedProperty(但后来你会浪费一些存储):

key_str = ndb.ComputedProperty(lambda self: self.key.urlsafe())