Django和Postgres事务回滚

时间:2010-01-29 12:02:54

标签: python django postgresql transactions

我有一段代码可以在后台进程中运行,看起来像

from django.db import transaction

try:

    <some code>

    transaction.commit()

except Exception, e:

    print e

    transaction.rollback()

在测试中,我使用导致数据库错误的数据中断<some_code>

是例外
File "/home/commando/Development/Diploma/streaminatr/stream/testcases/feeds.py", line 261, in testInterrupt

    form.save(self.user1)                                                                                    

File "/usr/lib/pymodules/python2.5/django/db/transaction.py", line 223, in _autocommit                     

    return func(*args, **kw)                                                                                 

File "/home/commando/Development/Diploma/streaminatr/stream/forms.py", line 99, in save                    

    print(models.FeedChannel.objects.all())                                                                  

File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 68, in `__repr__ `                       

    data = list(self[:REPR_OUTPUT_SIZE + 1])                                                                 

File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 83, in `__len__ `                        

    self._result_cache.extend(list(self._iter))                                                              

File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 238, in iterator                       

    for row in self.query.results_iter():                                                                    

File "/usr/lib/pymodules/python2.5/django/db/models/sql/query.py", line 287, in results_iter               

    for rows in self.execute_sql(MULTI):                                                                     

File "/usr/lib/pymodules/python2.5/django/db/models/sql/query.py", line 2369, in execute_sql               

    cursor.execute(sql, params)                                                                              

InternalError: current transaction is aborted, commands ignored until end of transaction block

这就是我的期望。不好的是,在我调用transaction.rollback后尝试访问数据库时,我仍然遇到同样的错误。我该怎么做才能成功回滚事务并再次使连接可用?

顺便说一句,我也尝试插入print connection.queries来调试代码,它总是返回一个空列表。可能是Django正在使用其他数据库连接吗?

代码在请求 - 响应周期之外运行。我尝试打开和关闭TransactionMiddleware,但它没有起作用。

我正在使用Django 1.1和Postgres 8.4。

2 个答案:

答案 0 :(得分:6)

默认的TestCase对事务没有任何了解,在这种情况下你需要使用TransactionalTestCase

答案 1 :(得分:2)

我根据事务中间件source编写了这个装饰器。希望它有所帮助,对我来说非常有效。

def djangoDBManaged(func):
    def f(*args, **kwargs):
        django.db.transaction.enter_transaction_management()
        django.db.transaction.managed(True)
        try:
            rs = func(*args, **kwargs)
        except Exception:
            if django.db.transaction.is_dirty():
                django.db.transaction.rollback()
            django.db.transaction.leave_transaction_management()
            raise
        finally:
            if django.db.transaction.is_managed():
                if django.db.transaction.is_dirty():
                    django.db.transaction.commit()
                django.db.transaction.leave_transaction_management()
        return rs
    # So logging gets the right call info whatever the decorator order is
    f.__name__ = func.__name__
    f.__doc__ = func.__doc__
    f.__dict__ = func.__dict__
    return f