Django与Postgres事务回滚
我有一段代码,它在后台进程中运行,代码大概是这样的:
from django.db import transaction
try:
<some code>
transaction.commit()
except Exception, e:
print e
transaction.rollback()
在测试中,我用一些数据故意让它出错,导致数据库出现问题。错误信息如下:
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 个回答
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
6
默认的测试案例(TestCase)并不知道事务的事情,如果你想要测试事务,就需要使用TransactionalTestCase。