我收到了很多错误的信息:
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"
作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。
代码保持不变,只是不知道这些错误来自哪里。
我收到了很多错误的信息:
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"
作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。
代码保持不变,只是不知道这些错误来自哪里。
当前回答
我相信@AnujGupta的答案是正确的。然而,回滚本身会引发一个异常,你应该捕获和处理:
from django.db import transaction, DatabaseError
try:
a.save()
except DatabaseError:
try:
transaction.rollback()
except transaction.TransactionManagementError:
# Log or handle otherwise
如果你发现你在不同的save()位置重写这段代码,你可以extract-method:
import traceback
def try_rolling_back():
try:
transaction.rollback()
log.warning('rolled back') # example handling
except transaction.TransactionManagementError:
log.exception(traceback.format_exc()) # example handling
最后,你可以使用一个保护使用save()的方法的装饰器来美化它:
from functools import wraps
def try_rolling_back_on_exception(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except:
traceback.print_exc()
try_rolling_back()
return wrapped
@try_rolling_back_on_exception
def some_saving_method():
# ...
model.save()
# ...
即使实现了上面的装饰器,保留try_rolling_back()作为提取的方法仍然很方便,以便在需要特定处理的情况下手动使用它,而通用的装饰器处理还不够。
其他回答
在Flask中,你只需要写:
curs = conn.cursor()
curs.execute("ROLLBACK")
conn.commit()
附注:文档在这里https://www.postgresql.org/docs/9.4/static/sql-rollback.html
我相信@AnujGupta的答案是正确的。然而,回滚本身会引发一个异常,你应该捕获和处理:
from django.db import transaction, DatabaseError
try:
a.save()
except DatabaseError:
try:
transaction.rollback()
except transaction.TransactionManagementError:
# Log or handle otherwise
如果你发现你在不同的save()位置重写这段代码,你可以extract-method:
import traceback
def try_rolling_back():
try:
transaction.rollback()
log.warning('rolled back') # example handling
except transaction.TransactionManagementError:
log.exception(traceback.format_exc()) # example handling
最后,你可以使用一个保护使用save()的方法的装饰器来美化它:
from functools import wraps
def try_rolling_back_on_exception(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except:
traceback.print_exc()
try_rolling_back()
return wrapped
@try_rolling_back_on_exception
def some_saving_method():
# ...
model.save()
# ...
即使实现了上面的装饰器,保留try_rolling_back()作为提取的方法仍然很方便,以便在需要特定处理的情况下手动使用它,而通用的装饰器处理还不够。
我也有这个错误,但它掩盖了另一个更相关的错误消息,代码试图在100个字符的列中存储125个字符的字符串:
DatabaseError: value too long for type character varying(100)
我必须调试代码才能显示上面的消息,否则就会显示
DatabaseError: current transaction is aborted
你只需要跑
rollback;
在PostgreSQL中,就是这样!
您可以通过“set_isolation_level(0)”禁用事务