views:

222

answers:

1

Hi,

does anybody have example how to use BLOB in SQLAlchemy?

Regards, Steve

+3  A: 
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
Denis Otkidach