Thursday, March 14, 2013

Connecting To PostgreSQL With Shove

PostgreSQL is far from a basic key-value data store. Instead, you're typically using it for robust web applications that store mountains of data and perform sophisticated, high-speed, high-volume queries. So why would you want to use it as a key-value store, relational databases are supposed to have schemas. Of course they are, but maybe you already have PosgreSQL deployed in your development and production environments and don't feel like installing more database back-ends. You also don't feel like designing a new schema to support persisting values in a smaller application you're writing. This is where Shove is handy.

To get going with Shove and PostgreSQL is easy. Just create a "shove" user and database to experiment with. That's what I did at least, to keep it separate from everything else. Next, create a virtual environment and install shove. I had to install a couple dependencies after the fact, so here is a one-liner — pip install shove sqlalchemy psycopg2. And that's it, connect to PostgreSQL with your Python dictionary.

from shove import Shove

store = Shove("postgres://shove:shove@")

if __name__ == "__main__":

    print 'Existing keys...'
    print store.keys()

    print 'Cleaning up...'
    for key in store.keys():
        del store[key]

    print 'Storing a string...'
    store['astring'] = 'foo'

    print 'Storing a list...'
    store['alist'] = [1,2,3,'4']