Skip to main content
 首页 » 编程设计

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

2025年05月04日17artech

我有一个 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