Jeff Watkins wrote:
>
>
> On 5 Nov, 2005, at 1:06 pm, DaveS wrote:
>
>> I'm trying to figure out how to structure my code so transactions do
>> the right thing when exceptions are raised. So far I've got
>>
>> def update(self):
>> hub.begin()
>> self.modify_database()
>> if i_dont_like_things:
>> hub.rollback()
>> else:
>> hub.commit()
>> hub.end()
>>
>> Is there any way to have a rollback happend automatically if
>> modify_database raises an exception? Or do I need to wrap everything
>> in a try/except to guarantee a rollback (and I assume I would also need
>> a hub.end() in there as well).
>
>
> You might consider writing your code like this:
>
> def update(self):
> try:
> hub.begin()
> # do some stuff
> hub.commit()
> finally:
> hub.rollback()
More proper would be:
hub.begin()
try:
do stuff
except:
hub.rollback()
raise
else:
hub.commit()
Though of course in the "else:" block you could commit or rollback based
on some flag, if you didn't want to automatically commit.
--
Ian Bicking | [EMAIL PROTECTED] | http://blog.ianbicking.org