Example using BLOB in SQLAlchemy

前端 未结 4 1309
野趣味
野趣味 2021-02-03 23:34

does anybody have example how to use BLOB in SQLAlchemy?

Regards, Steve

4条回答
  •  鱼传尺愫
    2021-02-03 23:58

    from sqlalchemy import *
    from sqlalchemy.orm import mapper, sessionmaker
    import os
    
    engine = create_engine('sqlite://', echo=True)
    metadata = MetaData(engine)
    
    sample = Table(
        'sample', metadata,
        Column('id', Integer, primary_key=True),
        Column('lob', Binary),
    )
    
    class Sample(object):
    
        def __init__(self, lob):
            self.lob = lob
    
    mapper(Sample, sample)
    
    metadata.create_all()
    
    session = sessionmaker(engine)()
    
    # Creating new object
    blob = os.urandom(100000)
    obj = Sample(lob=blob)
    session.add(obj)
    session.commit()
    obj_id = obj.id
    session.expunge_all()
    
    # Retrieving existing object
    obj = session.query(Sample).get(obj_id)
    assert obj.lob==blob
    

提交回复
热议问题