Python Can';t使用SqlAlchemy pickle对象错误
我正在尝试使用SqlAlchemy在postgresql数据库中存储一个可变对象。对象的类别大致如下:Python Can';t使用SqlAlchemy pickle对象错误,python,sqlalchemy,pickle,Python,Sqlalchemy,Pickle,我正在尝试使用SqlAlchemy在postgresql数据库中存储一个可变对象。对象的类别大致如下: class Data(Mutable, object): @classmethod def coerce(cls, key, value): return value def __init__(self, foo, bar): self._foo = foo # foo is an array of short strings
class Data(Mutable, object):
@classmethod
def coerce(cls, key, value):
return value
def __init__(self, foo, bar):
self._foo = foo # foo is an array of short strings
self._bar = bar # bar is a single short string
def append_to_foo(self, baz):
self._foo.append(baz)
self.changed()
# Various other methods for mutating/accessing foo and bar, which call self.changed()
# when they finish
列定义为:
data = Column(Data.as_mutable(PickleType))
每当我尝试向包含此列的表中添加行时,都会出现以下错误:
sqlalchemy.exc.StatementError: (builtins.AttributeError) Can't pickle local object 'WeakKeyDictionary.__init__.<locals>.remove' [SQL: "INSERT INTO table (id, user_id, data) VALUES (nextval('data_id_seq'), %(user_id)s, %(data)s) RETURNING data.id"] [parameters: [{'data': <mypkg.foo.Data object at 0x7f79b3b52c88>, 'user_id': 36}]]
sqlalchemy.exc.StatementError:(builtins.AttributeError)无法pickle本地对象“WeakKeyDictionary.”删除“[SQL:”插入到表(id,用户id,数据)值(nextval('data_id_seq'),%%(user_id)s,%%(data)s)返回数据.id”][参数:[{'data':,'user_id':36}]
我已经确保数据类本身可以使用Python提示符进行pickle;我可以pickle.dumps
和pickle.load
实例,没有任何问题。谷歌没有结果,我也找不到任何相关的bug报告
我使用的是SqlAlchemy 1.0.13和Python 3.5。从阅读中可以看出,您必须至少为自定义可变类型提供\uuuu getstate\uuu
方法:
这里,开发人员的责任只是提供一个\uuu getstate\uuu
方法,该方法从pickle流中排除\u parents()
集合:
这是因为可变扩展在value对象上放置了一个weakref.WeakKeyDictionary
,它不能被pickle。文档中提供了一个最小的\uuu getstate\uuu
实现:
class Data(Mutable, object):
...
def __getstate__(self):
d = self.__dict__.copy()
d.pop('_parents', None)
return d
根据您的类型的实现方式,您可能还必须提供\uuuu setstate\uuuu
。您阅读了吗?可能是您必须提供\uuuuu getstate\uuuu
。是的,就是这样-我还必须提供\uuuu setstate\uuuu
。你能回答一下吗?这样我就可以接受了?