SQLite or files?

AggieDan04 danb_83 at yahoo.com
Mon Oct 5 22:08:59 EDT 2009


On Sep 17, 9:10 am, J Kenneth King <ja... at agentultra.com> wrote:
> ici <iltch... at gmail.com> writes:
> > I likeshelvefor saving small amounts of data, user preferences,
> > recent files etc.
> >http://docs.python.org/library/shelve.html
>
> I like it too, but I hear the great powers that be are going to
> deprecate it.

If you want the convenience of shelve without the limitations of dbm,
you can do:


"""Implementation of Python shelves using SQLite."""

from __future__ import division

import UserDict
import pickle
import sqlite3

def to_db_type(value):
    """
    If value's type is supported natively in SQLite, return value.
    Otherwise, return a pickled representation.
    """
    if value is None or isinstance(value, (int, long, float,
basestring)):
        return value
    else:
        return buffer(pickle.dumps(value))

def from_db_type(value):
    """
    Converts a value from the database to a Python object.
    """
    if isinstance(value, buffer):
        return pickle.loads(value)
    else:
        return value

class SQLiteShelf(UserDict.DictMixin):
    """
    Shelf implementation using an SQLite3 database.
    """
    def __init__(self, filename):
        self._database = sqlite3.connect(filename)
        self._database.execute("CREATE TABLE IF NOT EXISTS Shelf "
                               "(Key TEXT PRIMARY KEY NOT NULL, Value
BLOB)")
        self._open = True
    def __del__(self):
        self.close()
    def __getitem__(self, key):
        row = self._database.execute("SELECT Value FROM Shelf WHERE
Key=?",
                                     [key]).fetchone()
        if row:
            return from_db_type(row[0])
        else:
            raise KeyError(key)
    def __setitem__(self, key, value):
        self._database.execute("INSERT OR REPLACE INTO Shelf VALUES
(?, ?)",
                               [key, to_db_type(value)])
    def __delitem__(self, key):
        self._database.execute("DELETE FROM Shelf WHERE Key=?", [key])
    def keys(self):
        """Return a list of keys in the shelf."""
        return [row[0] for row in
                self._database.execute("SELECT Key FROM Shelf")]
    def close(self):
        """Commit changes and close the file."""
        if self._database is not None:
            self._database.commit()
            self._database.close()
            self._database = None



More information about the Python-list mailing list