Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
tree: 4391615f35
Fetching contributors…

Cannot retrieve contributors at this time

63 lines (45 sloc) 1.466 kB
layout title
default
How to use database transactions

How to use database transactions

Problem

How to use database transactions

Solution

The web.DB class has a method transaction which returns a transaction object. The transaction object can be used to commit or rollback a transaction.

import web

db = web.databse(dbn="postgres", db="webpy", user="foo", pw="")
t = db.transaction()
try:
    db.insert('person', name='foo')
    db.insert('person', name='bar')
except:
    t.rollback()
    raise
else:
    t.commit()

With python 2.5+, transaction can be used as with statement also.

db = web.databse(dbn="postgres", db="webpy", user="foo", pw="")

with db.transaction():
    db.insert('person', name='foo')
    db.insert('person', name='bar')

It is also possible to have nested transactions.

def post(title, body, tags):
    t = db.transaction()
    try:
        post_id = db.insert('post', title=title, body=body)
        add_tags(post_id, tags)
    except:
        t.rollback()
    else:
        t.commit()

def add_tags(post_id, tags):
    t = db.transaction()
    try:
        for tag in tags:
            db.insert('tag', post_id=post_id, tag=tag)
    except:
        t.rollback()
    else:
        t.commit()

Nested transactions are ignored for sqlite as they are not supported.

Jump to Line
Something went wrong with that request. Please try again.