我收到了很多错误的信息:
"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。
代码保持不变,只是不知道这些错误来自哪里。
当前回答
在Flask shell中,我所需要做的就是一个session.rollback()来解决这个问题。
其他回答
要摆脱错误,在你修复了你的代码后回滚最后一个(错误的)事务:
from django.db import transaction
transaction.rollback()
你可以使用try-except来防止错误的发生:
from django.db import transaction, DatabaseError
try:
a.save()
except DatabaseError:
transaction.rollback()
参考:Django文档
您可以通过“set_isolation_level(0)”禁用事务
我遇到过这个问题,错误出现是因为错误事务没有正确结束,我在这里找到了事务控制命令的postgresql_transactions
事务控制
下面的命令用于控制事务
BEGIN TRANSACTION − To start a transaction.
COMMIT − To save the changes, alternatively you can use END TRANSACTION command.
ROLLBACK − To rollback the changes.
所以我使用END TRANSACTION来结束错误TRANSACTION,代码如下:
for key_of_attribute, command in sql_command.items():
cursor = connection.cursor()
g_logger.info("execute command :%s" % (command))
try:
cursor.execute(command)
rows = cursor.fetchall()
g_logger.info("the command:%s result is :%s" % (command, rows))
result_list[key_of_attribute] = rows
g_logger.info("result_list is :%s" % (result_list))
except Exception as e:
cursor.execute('END TRANSACTION;')
g_logger.info("error command :%s and error is :%s" % (command, e))
return result_list
我相信@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()作为提取的方法仍然很方便,以便在需要特定处理的情况下手动使用它,而通用的装饰器处理还不够。
这是一个糟糕的sql执行问题,它不允许其他查询执行,直到前一个查询被挂起/回滚。
在PgAdmin4-4.24中有一个回滚选项,可以尝试一下。