python - 当对象来自 SQLAlchemy 时无法 pickle int 对象错误?

标签 python sqlalchemy yaml pickle

我正在使用 YAML 和 SQLAlchemy。我定义了我的对象,我可以使用 YAML 打印它。但是,当我尝试对从 SQLAlchemy 查询返回的对象使用 YAML 时,它失败并显示错误 can't pickle int objects。我打印出从 SQLAlchemy 返回的实例,它显示了正确的类型。我会让代码来说话:

class HashPointer(Base):
    __tablename__ = 'hash_pointers'

    id = Column(Integer, primary_key=True)
    hash_code = Column(VARBINARY(64), unique=True)
    file_pointer = Column(Text)

    def __init__(self, hash_code, file_pointer):
        self.hash_code = hash_code
        self.file_pointer = file_pointer

    def __repr__(self):
        return "<HashPointer('%s', '%s')>" % (self.hash_code, self.file_pointer)

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Engine = create_engine("mysql://user:pass@localhost/db", echo=True)
Session = sessionmaker(bind=Engine)
session = Session()
fhash = HashPointer(0x661623708235, "c:\\test\\001.txt")

# PRINTS FINE
print(yaml.dump(fhash))

for instance in session.query(HashPointer).all():
    # PRINTS FINE AS __repr__
    print instance

    # THROWS ERROR, 'CAN'T PICKLE INT OBJECTS'
    print(yaml.dump(instance))

最佳答案

尝试将以下内容添加到您的类(class)中:

def __reduce__(self):
    'Return state information for pickling'
    return self.__class__, (int(self.hash_code), str(self.file_pointer))

关于python - 当对象来自 SQLAlchemy 时无法 pickle int 对象错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844276/

相关文章:

从列表中设置路径的Pythonic方式

python - 有没有办法在python中重用线程工作器?

mysql - 如何使用 SQLAlchemy 向 mysql 中的表或列添加注释?

python - PyYAML 解析成任意对象

json - 如何创建过滤多个源的 EventPattern(在 EventBridge 规则内)?

yaml - 如何为 "safe"和 "round-trip"获取类似格式的 yaml

python - 树莓派pip安装

python - 在 kivy python 中将按钮的背景更改为不同的形状和样式,如阴影效果等

python - 您如何为 WTForms-Alchemy 指定 unique=True?

python - 搜索关系属性的精确匹配