Unpickle 用 SQLAlchemy 腌制的元素 "by hand"

Unpickle element that was pickled with SQLAlchemy "by hand"

我有一个应用程序可以将一些 python 元素放入数据库中。 SQLAlchemyCode 如下所示:

class DatabaseTable(base):
    __tablename__ = 'TableName'
    id = db.Column(Integer, primary_key=True, autoincrement=True)
    pickeled_element_column = Column(sqlalchemy.types.PickleType, nullable=False)

不,我可以将元素放入我的数据库:

db_object = DatabaseTable()
db_object.pickeled_element_column = object_to_pickle
session.add(db_object)
session.commit()

目前有效。

上面提到的应用程序已经可以投入生产使用了。我现在想做的是将其中一些数据库元素复制到我的 jupyter notebook 中进行测试。

我的想法是手动将我的对象从数据库复制到 jupyter 中的 python 字符串中。我数据库中的 pickle 字符串如下所示:

pickle_string = 0x800495FF020000000...5622E

当我不尝试解开那个字符串时,我得到一个解开堆栈下溢错误:

pickle.loads(pickle_string.encode())

---------------------------------------------------------------------------
UnpicklingError                           Traceback (most recent call last)
<ipython-input-508-58d250332c2d> in <module>()
      1 pickeled_string = "0x800495FF020000..E"
      2 
----> 3 pickle.loads(pickeled_string.encode())

UnpicklingError: unpickling stack underflow

所以最后是我的问题。 如何将 SQLAlchemy 腌制的元素复制到数据库中并在其他地方取消腌制。

0x800495FF020000..E 是一个 T-SQL binary constant, or in other words the way SQL Server displays binary data. Python's pickle on the other hand expects bytes – 不是包含 T-SQL 二进制常量表示的字符串。您必须先转换表示,然后才能解开您的对象:

# I'll assume you actually have the full binary string without the `..` truncation
binary_constant = "0x800495FF020000..E"
pickled_data = bytes.fromhex(binary_constant[2:])
obj = pickle.loads(pickled_data)

如果您仍在使用 Python 2(您应该迁移到 3),您似乎认为 pickle.loads() 接受字符串值,您将不得不使用有点不同的方法:

import binascii

binary_constant = "0x800495FF020000..E"
pickled_data = binascii.unhexlify(binary_constant[2:])
obj = pickle.loads(pickled_data)