2011-05-03 37 views
3

我有一个约20个对象的列表,并且为每个对象返回一个包含10个词典的列表。
我想存储每个对象在GAE列表中的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 

我不知道如果这个代码是根本写的。如果任何人可以请帮助它将不胜感激。

+0

听起来像您的列表相当静态。为什么不把它存储在代码或数据文件中? – 2011-05-03 19:40:03

回答

4

欢迎来到Stack Overflow!

我看到几个问题:

  1. Dictionary不supported value types App Engine的性能。
  2. 您只存储最后一个实体;其余的都被丢弃。
  3. 您正在使用ListProperty,但不是追加dict_info的每个元素,而是完成整个列表的单个附加。

既然你不能在一个属性中存储原始字典,你需要将它序列化为其他格式,比如JSON或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)检索您的字典清单。

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 
4

由于是这样写的,App Engine推出了他们的实验性“ndb”Python数据库模型,其中特别包含JsonProperty,帽子很好直接实现你想要的。

现在,您需要运行App Engine的Python 2.7版本,它仍然没有完全准备好生产,但现在看起来都很稳定,GvR自己似乎正在编写很多代码预示着代码质量,我打算在今年的某个时候使用它...