在GAE中存储词典列表

时间:2011-05-03 18:30:41

标签: python google-app-engine google-cloud-datastore

我有一个大约20个对象的列表,对于每个对象,我返回一个包含10个词典的列表 我试图在GAE的列表中存储每个对象的10个词典列表;我不认为我正在编写代码以将此信息存储到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

我不确定这段代码是否完全是写的。如果有人能请求帮助,我将不胜感激。

3 个答案:

答案 0 :(得分:4)

欢迎使用Stack Overflow!

我看到一些问题:

  1. App Engine属性的词典不是supported value types
  2. 你只存储最后一个实体;其余的都被丢弃了。
  3. 您正在使用ListProperty,但不是附加dict_info的每个元素,而是在整个列表中添加一个附加内容。
  4. 由于您无法在属性中存储原始字典,因此需要将其序列化为其他格式,如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)检索词典列表。

答案 1 :(得分:4)

当我处理Google App Engine不直接支持的数据类型(如字典或自定义数据类型)时,我通常采用方便的PickleProperty

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)

PickleProperty模块中宣布commons.py课程后,您可以使用它来存储您的自定义数据:

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

答案 2 :(得分:4)

由于这是编写的,App Engine已经推出了他们的实验性“ndb”Python数据库模型,其中特别包含了JsonProperty,它可以很好地直接实现你想要的东西。

现在,你需要运行App Engine的Python 2.7版本,它仍然没有为生产做好准备,但这些天看起来都很稳定,GvR自己似乎写了很多代码哪个是bodes很好的代码质量,我打算在今年的某个时候在生产中使用它......

相关问题