python - 使用 PickleProperty 在 GAE 中存储字典

标签 python google-app-engine webapp2

我有一个 python 字典,我试图通过 pickle 属性存储在 GAE Gql 数据存储中。

我试着按照这个问题和答案, Store a list of dictionaries in GAE

但它不适用于我下面的代码。我收到一条错误消息,提示我的列表有问题

我如下设置 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.mloads(value)

class MDB(db.Model):
    Name = db.StringProperty(required=True)
    Times = PickleProperty()
    created = db.DateTimeProperty(auto_now_add = True)

我的代码中有一个函数可以插入数据并将其读出

def m_time_manage(m=""):

    if not m:
        r = db.GqlQuery("select * from MDB")
    else:
        #find specific masjid requested
        r = db.GqlQuery("select * from MDB where Name = %s" % (s))

    #if masjid time data doesn't exist in db throw in placeholders...
    if r is None:
        times = {}
        times['a'] = "8:49"
        times['b'] = "10:19"

        times_entry = MDB(Name="abc",Times=times)
        times_entry.put()

    r = db.GqlQuery("select * from MasjidDB")
    return (r[0].Name, r[0].Times)

在我的 get 函数中,我调用 m_time_manage() ftn 如下,

(mName, times) = m_time_manage()
        self.write(times)

我得到这个错误,pickle.loads 和文件结束错误...完整的错误是,但我不确定如何在 python 中存储字典,

 line 31, in make_value_from_datastore
    return pickle.loads(value)
  File "/usr/lib/python2.7/pickle.py", line 1382, in loads
    return Unpickler(file).load()
  File "/usr/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
  File "/usr/lib/python2.7/pickle.py", line 880, in load_eof
    raise EOFError

提前感谢您的帮助

最佳答案

我建议切换到 NDB 并使用其内置的 PickleProperty。参见 https://developers.google.com/appengine/docs/python/ndb/properties

关于python - 使用 PickleProperty 在 GAE 中存储字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842693/

相关文章:

python - Keras:训练时出现值错误

python - Matplotlib 毫秒在 x 轴上打勾

google-app-engine - 谷歌应用引擎中的事务隔离

google-app-engine - GAE : Enabling Edge Cache with webapp2 (Python)

python - 为什么我的 webapp2 import/Google App Engine "Hello, World"不工作?

python - 在 Python 中使用 Pandas Groupby 按系列中的标签分组

python - 如何在整个目录中查找具有特定扩展名的文件,然后复制到另一台服务器

python - Google 云端硬盘文档中的实时查看者列表

python - 无法在代码中访问 UserProperty 的成员

python - 谷歌应用引擎。如何在处理程序构造函数内重定向