esa*_*sac 5 python yaml sqlalchemy 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))
Run Code Online (Sandbox Code Playgroud)
尝试将以下内容添加到您的班级中:
def __reduce__(self):
'Return state information for pickling'
return self.__class__, (int(self.hash_code), str(self.file_pointer))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2975 次 |
| 最近记录: |