我有一段代码在后台进程中工作,看起来像
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。
最佳答案
Default TestCase 对事务一无所知,你需要使用TransactionalTestCase在这种情况下。
关于python - Django 和 Postgres 事务回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161723/