Can't uncover the error of an object object when an object comes from SQLAlchemy?

I am using YAML and SQLAlchemy. I defined my object and I can use YAML for printing, this is just fine. However, when I try to use YAML for the object returned from the SQLAlchemy query, it does not work with an error can't pickle int objects. I printed the instance returned from SQLAlchemy and it displays the correct type. I will let the code say:

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))
+5
source share
2 answers

Try adding the following to your class:

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

, _ex (im , (), .), , sqlalchemy active, _sa_instance_state , API reduce_ex, PyYAML .

, SqlAlchemy, , .

, PyYAML. , PDB submit_object SQLAlchemy.

, , , , python.

(, session.new session.dirty), PyYAML.

, , , , "" * - , SQLAlchemy, , , .

:

DeclBase = declarative_base()

class Base(DeclBase):
    __abstract__ = True

    def __reduce_ex__(self, proto):
        ret = super(Base, self).__reduce_ex__(proto)
        ret = ( ret[0], ret[1], dict(ret[2]) ) + ret[3:]
        ret[2].pop('_sa_instance_state', None) # remove bad yamly from reduce state
        return ret

/ yaml, . , , . , , .

NOTE/EDIT: reduce_ex , . https://docs.python.org/2/library/pickle.html#object. reduce_ex, , , ().

Redux... reduce dict - , __reduce * , dict.

+1

All Articles