1

我通过网络将 sqlalchemy 对象发送到另一台机器。首先我将它序列化为一个字符串,然后加密并发送。我用以下方式序列化它:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.serializer import loads, dumps
engine = create_engine(connection_str)
S = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))
session = S()

data = session(MyObj).all()
serialized = pickle.dumps([dumps(d) for d in data])

crypted = crypt(serialized) #encrypting the serialized data
send(machine, crypted)      #sending encripted data to 'machine'

在另一台机器上:

encrypted = get_data()
serialized = decrypt(encrypted)
data = [loads(d, Base.metadata, S) for d in pickle.loads(serialized)]

for d in data:
    session.merge(d)
session.commit()

但它抛出:(IntegrityError) node_type.id may not be NULL u'INSERT INTO myobj (col1, col2) VALUES (?, ?)' (None, None)

当我尝试打印时data它会抛出:DetachedInstanceError Instance <MyObj at 0x24e0c70> is not bound to a Session; attribute refresh operation cannot proceed 或:ObjectDeletedError

问题是什么?

此处: 如何从 SqlAlchemy 创建和恢复备份?被告知那session.merge()会很好,但它对我不起作用。

4

1 回答 1

1

来自sqlalchemy.ext.serializer的文档:

“序列化程序模块仅适用于查询结构。用户定义类的 [...] 实例不需要它”

对于这个用例,也许尝试只使用 pickle 而不是 sqlalchemy.ext.serializer 。

于 2012-12-20T12:08:52.837 回答