Search code examples
pythonpython-3.xberkeley-dbbsddb

Storing data in a Berkeley DB database with Python and bsddb3


I’m trying to write data to a Berkeley DB database using Python 3.5 and bsddb3. I don’t have any experience with Berkeley DB, but I like to use a time stamp as the key and some JSON data as the respective value. The following example leads to an error:

#!/usr/bin/env python3

import bsddb3
import time

fn = 'berkeley.db'
db = bsddb3.hashopen(fn, 'c')
t = time.time()
d = "{ data: 'foo' }"
db[t] = d
db.close()

The error:

$ python3 example.py
[...]
self.db[key] = value
TypeError: Bytes or Integer object expected for key, float found

Using an integer instead of time.time(), for instance, db[0] = data, doesn’t work either: TypeError: Integer keys only allowed for Recno and Queue DB's.

Unfortunately, there is no comprehensive documentation on how to use Berkeley DB with Python. Any suggestions regarding what I’m doing wrong?


Solution

  • I got the solution while reading the documentation of Kyoto Cabinet. The key has to be encoded as byte:

    db[b'key'] = d
    print((db.get(b'key')))
    

    Running the example with the above changes will lead to an output of the stored data set:

    $ python3 main.py
    b"{ data: 'random' }"