Django - 引发错误后在 transaction.atomic 块内对数据库进行操作
Django - operate on database within transaction.atomic block after raising error
我想在 transaction.atomic() 块中对我的数据库执行操作,即使出现错误也是如此。下面是一些示例代码来演示我的问题:
示例代码
# Outer try block
try:
# Enclose in atomic transaction for database rollbacks
with transaction.atomic():
# If this line fails, all database updates within the outer try: block should be rolled back
u = UU.create(email='test@test.com')
# Inner try block
try:
cc = CC.objects.get(id=1)
perform_action(cc)
# If this exception triggers, the 'cc' object should be deleted, but all other database updates within the outer try: block should be rolled back
except:
cc.delete()
raise
# If this line fails, all database updates within the outer try: block should be rolled back
u = UU.create(email='test@test.com')
# If any exception triggers, this error should be printed
except:
print("Error occured.")
如果我的内部 try:
块发生错误,我希望删除 cc
对象,但回滚外部 try:
块内的所有其他数据库事务.但是,按照现在的代码,如果内部 try:
块中发生任何错误,cc.delete()
事务将被回滚。
有什么建议吗?
不能只保留数据库事务的一部分,也不能在回滚外部事务的同时保留内部事务。
相反,您可以使用自定义异常来指示该特定错误状态,然后在回滚之后捕获它时进行额外处理。类似于:
class BadCCException(Exception):
def __init__(self, badid):
super().__init__()
self.badid = badid
try:
with transaction.atomic():
u = UU.create(email='test@test.com')
try:
cc = CC.objects.get(id=1)
perform_action(cc)
except Exception as e:
raise BadCCException(1) from e
u = UU.create(email='test@test.com')
except BadCCException as e:
CC.objects.filter(id=e.badid).delete()
print("Error occured.")
except:
print("Error occured.")
我想在 transaction.atomic() 块中对我的数据库执行操作,即使出现错误也是如此。下面是一些示例代码来演示我的问题:
示例代码
# Outer try block
try:
# Enclose in atomic transaction for database rollbacks
with transaction.atomic():
# If this line fails, all database updates within the outer try: block should be rolled back
u = UU.create(email='test@test.com')
# Inner try block
try:
cc = CC.objects.get(id=1)
perform_action(cc)
# If this exception triggers, the 'cc' object should be deleted, but all other database updates within the outer try: block should be rolled back
except:
cc.delete()
raise
# If this line fails, all database updates within the outer try: block should be rolled back
u = UU.create(email='test@test.com')
# If any exception triggers, this error should be printed
except:
print("Error occured.")
如果我的内部 try:
块发生错误,我希望删除 cc
对象,但回滚外部 try:
块内的所有其他数据库事务.但是,按照现在的代码,如果内部 try:
块中发生任何错误,cc.delete()
事务将被回滚。
有什么建议吗?
不能只保留数据库事务的一部分,也不能在回滚外部事务的同时保留内部事务。
相反,您可以使用自定义异常来指示该特定错误状态,然后在回滚之后捕获它时进行额外处理。类似于:
class BadCCException(Exception):
def __init__(self, badid):
super().__init__()
self.badid = badid
try:
with transaction.atomic():
u = UU.create(email='test@test.com')
try:
cc = CC.objects.get(id=1)
perform_action(cc)
except Exception as e:
raise BadCCException(1) from e
u = UU.create(email='test@test.com')
except BadCCException as e:
CC.objects.filter(id=e.badid).delete()
print("Error occured.")
except:
print("Error occured.")