[DB-SIG] Exeception Handling.

Heston James - Cold Beans heston.james at coldbeans.co.uk
Fri Jul 4 14:03:55 CEST 2008


> I'd put the whole transaction code into a try-except:
>
> try:
>      # Start of transaction
>      ... do stuff ...
> except Exception:
>      self.datasource.rollback()
>      raise
> else:
>      self.datasource.commit()
>
> This assures that a successful execution of your code results in
> the transaction to be committed. In case something goes wrong,
> the transaction is rolled back and the error reraised so that you
> can process it at some higher level.
>
> I'd really appreciate your advice on this, I'm relatively new to the world
> of db implementation using the dbapi and want to make this as water tight
as
> possible.

Hi Marc-Andre,

Thank you for your advice, that's really very helpful. I'd like to extend
this question a little if you don't mind. Let's say for instance that the
persistence of an object isn't just in the database but also on the file
system. And for instance this is done like so:

            # Open the file object in write binary mode.
            message = open("/files/%s/%s" % (self.message_id, self.name),
"wb")

           	# Write the binary to the file.
            message.write(base64.decodestring(self.binary_data))

            # Close the file object.
            message.close()

Now, within my object let's say that I have a method such as save() which I
need to save the object to the database (using the code we've already
discussed) and also run that file save code to write it to the file system.

How would you transaction ALL of this? So if either the file save or the
database persist fails then it rolls them both back? So I don't end up with
a file without a DB entry or a DB entry without a file?

I'd be interested to know A) how would you arrange a try/except block to
handle this, and B) would you put this method in the bean or abstract it out
into a service layer and have two methods in the bean, one for the file save
and one for the database save and wrap those in a transaction at a higher
level?

Many thanks

Heston



More information about the DB-SIG mailing list