我可以在谷歌的BigTable数据存储中存储python字典而无需显式序列化吗?

wil*_*lem 1 python google-app-engine pickle

我有一个python字典,我想存储在Google的BigTable数据存储区中(它是一个db.Model类中的属性).

是否有捷径可寻?即使用db.DictionaryProperty?或者我是否必须使用pickle来序列化我的字典?我的字典相对简单.它由字符串作为键组成,但它也可能包含某些键的子字典.例如:

{ 
    'myKey' : 100,
    'another' : 'aha',
    'a sub dictionary' : { 'a': 1, 'b':2 }
}
Run Code Online (Sandbox Code Playgroud)

PS:我想序列化为二进制,而不是文本,如果可能的话.

jbo*_*chi 8

这是另一种方法:

class DictProperty(db.Property):
  data_type = dict

  def get_value_for_datastore(self, model_instance):
    value = super(DictProperty, self).get_value_for_datastore(model_instance)
    return db.Blob(pickle.dumps(value))

  def make_value_from_datastore(self, value):
    if value is None:
      return dict()
    return pickle.loads(value)

  def default_value(self):
    if self.default is None:
      return dict()
    else:
      return super(DictProperty, self).default_value().copy()

  def validate(self, value):
    if not isinstance(value, dict):
      raise db.BadValueError('Property %s needs to be convertible '
                             'to a dict instance (%s) of class dict' % (self.name, value))
    return super(DictProperty, self).validate(value)

  def empty(self, value):
    return value is None
Run Code Online (Sandbox Code Playgroud)