Python 在GAE中存储词典列表
我有一个大约20个对象的列表,对于每个对象,我返回10个字典的列表。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
我试图将列表中每个对象的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 我看到一些问题:
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应用程序引擎不直接支持的数据类型(如字典或自定义数据类型)时,我通常采用handypickle属性
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自己似乎正在编写大量代码,这对代码质量是个好兆头,我打算在今年的某个时候在生产中使用它…听起来你的列表是相当静态的。为什么不将其存储在代码或数据文件中?