Django和Postgres事务回滚

5

我有一段在后台进程中运行的代码,看起来像这样:

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后尝试访问DB时仍然会收到相同的错误。我该怎么做才能成功回滚事务并再次使用连接呢?
另外,我还尝试插入print connection.queries来调试代码,但它总是返回一个空列表。难道Django正在使用其他DB连接吗?
该代码在请求-响应周期之外运行。我尝试开启和关闭TransactionMiddleware,但没有效果。
我正在使用Django 1.1和Postgres 8.4。

如果您将“transaction.commit()”移到“try”语句的“else”子句中会发生什么? - Milen A. Radev
相同的行为。 - Dmitry Risenberg
你有DB服务器的控制权吗?如果有,请打开查询日志记录 - “log_statement = all”(ALTER DATABASE <your_db> SET log_statement TO 'all')。然后重试并查看日志。 - Milen A. Radev
2个回答

6

谢谢,我错过了这部分的文档! - Dmitry Risenberg

2
我根据事务中间件 源代码 编写了这个装饰器。希望它能帮到你,对我来说完美地工作。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接