Can I store a python dictionary in google's BigTable datastore without serializing it explicitly?

后端 未结 3 794
别跟我提以往
别跟我提以往 2021-02-11 09:20

I have a python dictionary that I would like to store in Google\'s BigTable datastore (it is an attribute in a db.Model class).

Is there an easy way to do t

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-11 10:16

    Here's another approach:

    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
    

提交回复
热议问题