Thursday, May 21, 2009

Persisting Python Objects With pod.

Some Python applications are so lightweight, it is a challenge to justify incorporating a big RDBMS into the ORM logic. Popular Python ORM packages such as SQLObject and SQLAlchemy, support many major relational database management systems. These RDBMS packages are hardly suitable for more modest Python packages. The pod Python package offers a nice alternative to using the more popular Python ORM technologies. At the core of the pod storage engine is SQLite. Although the other popular ORM technologies support SQLite, you also get support for the larger RDBMS packages even if you don't need them. The pod codebase is thus much smaller than any equivalent. Similar ORM concepts apply when using pod to store Python instances. The following is an example of the pod Python library in use.
#Example; Using the pod Python Object Database.

#Import the library.
import pod

#Initialize the database connection.
db=pod.Db(file='myblog.sqlite3', very_chatty=False)

#The blog schema. Extends the core pod.Object class.
class Blog(pod.Object):
#Schema fields.
name=pod.column.String(index=False)

#Constructor.
def __init__(self, **kw):
pod.Object.__init__(self, **kw)

#Called before any instances of this class are deleted
#from the database.
def pre_delete(self):
#Ensure that all blog entries associated with this
#blog are also deleted from the database.
print "Destroying blog entries."
for entry in BlogEntry.owner==self:
entry.delete()

#The blog entry schema. Extends the core pod.Object class.
class BlogEntry(pod.Object):
#Schema fields.
owner=pod.column.Object(index=True)
title=pod.column.String(index=False)
body=pod.column.String(index=False)

#Constructor.
def __init__(self, **kw):
pod.Object.__init__(self, **kw)

#Instantiate the main blog instance.
def make_main_blog():
print "Creating main blog."
blog=Blog(name="main")
db.commit()
return blog

#Instantiate two blog entry instances.
def make_entries():
print "Creating blog entries."
blog_obj=get_main_blog()
BlogEntry(owner=blog_obj, title="Title1", body="Body1")
BlogEntry(owner=blog_obj, title="Title2", body="Body2")
db.commit()

#Retrieve the main blog instance, creating it if not found.
def get_main_blog():
for blog in Blog.name=="main":
return blog
return make_main_blog()

#Retrieve the blog entries associated with the main blog.
def get_entries():
entries=[]
for entry in BlogEntry.owner==get_main_blog():
entries.append(entry)
return entries

#Delete the main blog from the database.
def cleanup():
print "Destroying main blog."
blog_obj=get_main_blog()
blog_obj.delete()
db.commit()

#Main program.
if __name__=="__main__":
#Build the main blog instance.
blog_obj=get_main_blog()
#Build the blog entry instances.
make_entries()
#Retrieve and display the blog entries.
for entry in get_entries():
print "Entry Title:",entry.title
#Destroy the blog.
cleanup()