2017-07-06 70 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())