【Django杂记】django Django的事务操作方法

Django框架本身提供了两种事务操作的方法(针对mysql)
      从django1.6开始,Django的事务操作方法主要通过django.db.transation模块完成

启用事务用法1:

from django.db import transaction
from rest_framework.views import APIView

class OrderAPIView(APIView):
    @transaction.atomic  # 开启事务,当方法执行完以后,自动提交事务
    def post(self, request):
        pass    

启用事务用法2:

from django.db import transaction
from rest_framework.views import APIView

class OrderAPIView(APIView):
    def post(self, request):
        with transaction.atomic(): # 开启事务,当with语句执行完成以后,自动提交事务
            pass # 数据库操作
在使用事务过程中,有时候会出现异常,当出现异常的时候,我们需要让程序停下来,同时回滚事务。
from django.db import transaction
from rest_framework.views import APIView

class OrderAPIView(APIView):
    def post(self, request):
        with transaction.atomic():
            # 设置事务回滚的标记点
            sid = transation.savepoint()
            ...
            
            try:
               	...
            except:
                transation.savepoint_rallback(sid)
posted @ 2022-05-31 13:44  郭祺迦  阅读(203)  评论(0)    收藏  举报