NDB JsonProperty 和 Cloud Datastore 库兼容性
NDB JsonProperty and Cloud Datastore library compatibility
我在使用 NDB 的 Standar GAE 上有代码 运行,在使用 Google 云数据存储库的灵活环境中有代码 运行。两者都访问相同的实体。
我在处理 ndb.JsonProperty 时遇到问题。据我所知,这些属性存储为 blob,因此我尝试使用云库来模拟 属性。在存储值之前,我执行以下操作:
value_to_store = json.dumps(value, separators=[',',':'])
value_to_store = base64.b64encode(value_to_store)
当我读到 属性 时正好相反:
read_value = base64.b64decode(from_db_value)
read_value = json.loads(read_value)
在这种情况下一切正常:
Insert using NDB ---> Read using Cloud Library
Insert using Cloud Library ---> Read using Cloud Library
但失败时:
Insert using Cloud Library --> Read using NDB
存储这些类型的属性以使其与 NDB 兼容的正确方法是什么?
谢谢。
终于找到解决方法了
重点是 NDB 将值存储为 blob,而库将其存储为字符串。
解决方案就是不要 encode/decode 字符串值,库会这样做并将值存储为 blob,这正是 NDB 所期望的。
写作:
value_to_store = json.dumps(value, separators=[',',':'])
阅读中:
read_value = json.loads(read_value)
简单!
我在使用 NDB 的 Standar GAE 上有代码 运行,在使用 Google 云数据存储库的灵活环境中有代码 运行。两者都访问相同的实体。
我在处理 ndb.JsonProperty 时遇到问题。据我所知,这些属性存储为 blob,因此我尝试使用云库来模拟 属性。在存储值之前,我执行以下操作:
value_to_store = json.dumps(value, separators=[',',':'])
value_to_store = base64.b64encode(value_to_store)
当我读到 属性 时正好相反:
read_value = base64.b64decode(from_db_value)
read_value = json.loads(read_value)
在这种情况下一切正常:
Insert using NDB ---> Read using Cloud Library
Insert using Cloud Library ---> Read using Cloud Library
但失败时:
Insert using Cloud Library --> Read using NDB
存储这些类型的属性以使其与 NDB 兼容的正确方法是什么?
谢谢。
终于找到解决方法了
重点是 NDB 将值存储为 blob,而库将其存储为字符串。
解决方案就是不要 encode/decode 字符串值,库会这样做并将值存储为 blob,这正是 NDB 所期望的。
写作:
value_to_store = json.dumps(value, separators=[',',':'])
阅读中:
read_value = json.loads(read_value)
简单!