我有一个 python 字典,我想将其存储在 Google 的 BigTable 数据存储中(它是 db.Model 类中的一个属性)。
有没有简单的方法来做到这一点?即使用 db.DictionaryProperty?或者我必须使用 pickle 来序列化我的字典吗?我的字典比较简单。它由作为键的字符串组成,但它也可能包含某些键的子字典。例如:
{
'myKey' : 100,
'another' : 'aha',
'a sub dictionary' : { 'a': 1, 'b':2 }
}
PS:如果可能的话,我想序列化为二进制,而不是文本。
请您参考如下方法:
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
