Jonah Kornberg
Jonah Kornberg

Reputation: 183

ZODB Blob storage

I require the storage of images in my ZODB database. I was trying to use blobs, but the lack of documentation and examples online has made this very difficult. I don't understand how to use the IBlobStorage interface. I currently make my database as so:

storage = FileStorage.FileStorage('DummyData.fs')
db = DB(storage)
connection = db.open()
root = connection.root()
root.users = BTrees.OOBTree.BTree()

My first attempt was to make a list of blobs:

l = []
l.append(Blob((np.random.rand(1200,1200,3)* 255).astype('uint8').tobytes()))

And store this in the Btree(). However, this tree does not support blobs. I cannot figure out how to use IBlobStorage or other storage interfaces and would greatly appreciate some guidance. Any references or links to examples would be sufficient answers. Thanks!

Upvotes: 1

Views: 237

Answers (1)

DirkR
DirkR

Reputation: 498

The BlobStorage is essentially an overlay over the regular storage, so you put it on top of that and use it instead.

Here is a pretty minimal example on how to use the BLOB storage in ZODB:

import ZODB, ZODB.FileStorage, transaction
from ZODB.blob import Blob, BlobStorage

# Create DB with BLOB
storage = ZODB.FileStorage.FileStorage("ZODB_minimal.fs")
blob_storage = BlobStorage("ZODB_minimal_blobs", storage)
db = ZODB.DB(blob_storage)
connection = db.open()

# Create BLOB
blob = Blob()
with blob.open('w') as bf:
    bf.write(b"I am a BLOB!")
    bf.close()

# Put into DB
connection.root.blob = blob

# Close DB
transaction.commit()
connection.close()
db.close()

# Read it back
storage = ZODB.FileStorage.FileStorage("ZODB_minimal.fs")
blob_storage = BlobStorage("ZODB_minimal_blobs", storage)
db = ZODB.DB(blob_storage)
connection = db.open()

blob = connection.root.blob
with blob.open('r') as bf:
    text = bf.readline()
    print(text)
    bf.close()

db.close()

Hope it helps!

Upvotes: 0

Related Questions