Python SQLObject
A few days ago I talked about using Python for web development together with CherryPy. I didn't mention at that time the other great thing about Python Web Development as oppose to PHP or Perl: SQLObject
It's rare nowadays to do a web development without a back-end database. And when we talk about databases we have to talk about all the usual queries we are tired of doing:
- Create database
- Create tables
- Write all the queries you'll need
- Handle foreign-keys
And many more. Most of the programmers (including myself) will do their own library to handle all of these and we keep reusing it in most of our projects. But still, it won't be as good as a well designed, purposed build and object orientated library as SQLObject.
On SQLObject each table becomes a python Class and it will produce the code to create, access, insert, update and delete tables and contents.
#!/usr/bin/env python
from sqlobject import *
import sys, os
class Person(SQLObject):
firstname = StringCol(length=30)
lastname = StringCol(length=30)
connection_string = 'sqlite:/tmp/test.db'
connection = connectionForURI(connection_string)
sqlhub.processConnection = connection
# Create table
Person.createTable('ifDoesNotExists')
# Add new entry
Person(firstname='Sergio', lastname='Rua')
Person(firstname='John', lastname='Doe')
# Get single entry by ID
p = Person.get(1)
print "1: Got entry: name=%s - Surname=%s" % (p.firstname, p.lastname)
# Get selected entries
p = Person.select(Person.q.firstname=='John')
print "2: Got entry: name=%s - Surname=%s" % (p[0].firstname, p[0].lastname)
# Get all entries
people = Person.select()
for p in people:
print "3: Got entry: name=%s - Surname=%s" % (p.firstname, p.lastname)
This is a very basic example to illustrate how easy is to use. Even if you don't know python I hope you see that there is no SQL involved in all of this. The class Person will in fact be a table on the database with the fields listed. You can then add or get rows from it with a very simple line of code.
I don't pretend to make a tutorial out of this. I just want to open your eyes to the possibilities. The website has a very good tutorial with everything you need to know. Otherwise, I'm here to help. You can always contact me or request an invitation to the free advice section.
The author, Ian Bicking, has done an excellent job.



