one more transactional issue.  Let's say that something goes wrong with the query on line 48 and an exception is raised.  There should never be an execution path out of your database code that doesn't encounter a commit or rollback.  

I think you need to protect the database work in a try:except block with the exception handler calling rollback and then re-raising the exception.