Python 在GAE中存储词典列表

Python 在GAE中存储词典列表,python,google-app-engine,google-cloud-datastore,Python,Google App Engine,Google Cloud Datastore,我有一个大约20个对象的列表,对于每个对象,我返回10个字典的列表。 我试图将列表中每个对象的10个词典列表存储在GAE上;我认为我没有正确编写代码以将此信息存储到GAE。 以下是我所拥有的: 在主请求处理程序之前,我有以下类: class Tw(db.Model): tags = db.ListProperty() ip = db.StringProperty() 在我的主请求处理程序中,我有以下内容: for city in lst_of_cities: # this is the

我有一个大约20个对象的列表,对于每个对象,我返回10个字典的列表。
我试图将列表中每个对象的10个词典列表存储在GAE上;我认为我没有正确编写代码以将此信息存储到GAE。
以下是我所拥有的: 在主请求处理程序之前,我有以下类:

class Tw(db.Model):
  tags = db.ListProperty()
  ip = db.StringProperty()
在我的主请求处理程序中,我有以下内容:

for city in lst_of_cities: # this is the list of 20 objects
  dict_info = hw12.twitter(city) # this is the function to get the list of 10 dictionaries for each object in the list
  datastore = Tw() # this is the class defined for db.model
  datastore.tags.append(dict_info) # 
  datastore.ip = self.request.remote_addr
datastore.put()

data = Data.gql("") #data entities we need to fetch

我不确定这段代码是否是编写的。如果有人能帮忙,我们将不胜感激。

欢迎来到Stack Overflow

我看到一些问题:

  • 字典不适用于应用程序引擎属性
  • 您只存储最后一个实体;其余的都被丢弃了
  • 您使用的是ListProperty,但不是追加dict_info的每个元素,而是对整个列表进行单个追加
  • 由于不能在属性中存储原始字典,因此需要将其序列化为其他格式,如JSON或pickle。下面是一个使用pickle的修订示例:

    from google.appengine.ext import db
    import pickle
    
    class Tw(db.Model):
      tags = db.BlobProperty()
      ip = db.StringProperty()
    
    entities = []
    for city in lst_of_cities:
      dict_info = hw12.twitter(city)
      entity = Tw()
      entity.tags = db.Blob(pickle.dumps(dict_info))
      entity.ip = self.request.remote_addr
      entities.append(entity)
    
    db.put(entities)
    

    稍后获取实体时,可以使用
    pickle.loads(entity.tags)
    检索字典列表

    当我处理Google应用程序引擎不直接支持的数据类型(如字典或自定义数据类型)时,我通常采用handy
    pickle属性

    from google.appengine.ext import db
    import pickle
    
    class PickleProperty(db.Property):
        def get_value_for_datastore(self, model_instance):
            value = getattr(model_instance, self.name, None)
            return pickle.dumps(value)
    
        def make_value_from_datastore(self, value):
            return pickle.loads(value)
    
    一旦在
    commons.py
    模块中声明了
    PickleProperty
    类,您就可以使用它来存储自定义数据,如下所示:

    from google.appengine.ext import db
    from commons import PickleProperty
    
    class Tw(db.Model):
      tags = PickleProperty()
      ip = db.StringProperty()
    
    entities = []
    for city in lst_of_cities:
      dict_info = hw12.twitter(city)
      entity = Tw()
      entity.tags = dict_info
      entity.ip = self.request.remote_addr
      entities.append(entity)
    
    db.put(entities)
    
    要检索回数据,请执行以下操作:

    entity.tags
    

    自从写了这篇文章之后,appengine推出了他们实验性的“ndb”Python数据库模型,其中特别包含JsonProperty,它可以很好地直接实现您想要的东西


    现在,您需要运行Python 2.7版本的应用程序引擎,它还没有完全准备好投入生产,但最近一切似乎都很稳定,GvR自己似乎正在编写大量代码,这对代码质量是个好兆头,我打算在今年的某个时候在生产中使用它…

    听起来你的列表是相当静态的。为什么不将其存储在代码或数据文件中?