django中使用开启事务的三种方式
全局开启事务
# settings.py
DATABASES = {
'default': {
#全局开启事务,绑定的是http请求响应整个过程
'ATOMIC_REQUESTS': True,
}
}
# 局部禁用
from django.db import transaction
# 局部禁用事务
@transaction.non_atomic_requests
def seckill(request):
return HttpResponse('秒杀成功')
视图中开启
# fbv开启
from django.db import transaction
@transaction.atomic
def seckill(request):
return HttpResponse('秒杀成功')
# cbv开启
from django.db import transaction
from rest_framework.views import APIView
class SeckillAPIView(APIView):
@transaction.atomic
def post(self, request):
pass
局部使用事务
transaction.atomic() # 开启事务
transaction.commit() # 提交事务
transaction.rollback() # 回滚事务
使用上下文
使用上线文模式会自动提交和回滚
from django.db import transaction
def seckill(request):
with transaction.atomic():
pass # 都在一个事物中
return HttpResponse('秒杀成功')
纯手动
from .models import Book
from django.db import transaction
def seckill(request):
with transaction.atomic():
# 设置回滚点,一定要开启事务
sid = transaction.savepoint()
print(sid)
try:
book = Book.objects.get(pk=1)
book.name = '红楼梦'
book.save()
except Exception as e:
# 如发生异常,回滚到指定地方
transaction.savepoint_rollback(sid)
print('出异常了,回滚')
# 如果没有异常,显式地提交一次事务
transaction.savepoint_commit(sid)
return HttpResponse('秒杀成功')
'''
在事务操作中,我们还会经常显式地设置保存点(savepoint)
一旦发生异常或错误,我们使用savepoint_rollback方法让程序回滚到指定的保存点
如果没有问题,就使用savepoint_commit方法提交事务
'''
transaction.atomic() # 开启事务
sid = transaction.savepoint() # 设置保存点
transaction.savepoint_rollback(sid) # 回滚到保存点
transaction.savepoint_commit(sid) #提交保存点
标签:事务,transaction,savepoint,开启,django,三种,atomic
From: https://www.cnblogs.com/yangyucai/p/17631330.html