我正在使用 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/