2016-09-19 58 views
1

我正在使用DRF,基於API視圖的類視圖,post方法。 參數是:文件 邏輯:對文件進行一些驗證並逐步保存文件(不同類型的對象) 我試圖在保存文件的其餘部分時發生異常時回滾事務。我設置'ATOMIC_REQUESTS'True原子事務不工作Django休息

class SaveXMlFile(APIView): 
    authentication_classes = [TokenAuthentication] 
    permission_classes = [IsAuthenticated] 
    parser_classes = [FormParser, MultiPartParser] 

    def post(self, request): 
     """ 
      Save xml file 
      --- 
      # inputs 
      parameters: 
       - name: game_log_file 
       description: Game log file 
       type: file 
       required: true 
       paramType: post 
       allowMultiple: false 
     """ 
     try: 
      # import pdb; pdb.set_trace() 
      game_log_file = request.data['game_log_file'] 
      file_store = FileStore.objects.create(uploaded_file=game_log_file) 
      xml_file_processing = ProcessXmlFile(file_store) 
      already_saved = xml_file_processing.was_file_saved() 
      player_exists = xml_file_processing.player_exists() 
      if already_saved: 
       file_store.delete() 
       return Response({"info": "File was saved previously, no action taken place this time."}, status=200) 
      if not player_exists: 
       file_store.delete() 
       return Response({"info": "No player exists in the database, ask your administrator to create some."}, status=200) 
      xml_file_processing.save() 
      file_store.delete() 
      return Response({"success": "File has been saved."}, status=status.HTTP_201_CREATED) 
     except Exception as err: 
      error = "{0}".format(str(err)) 
      return JsonResponse({'exception': error}, status=500) 

我故意拋出異常時,該文件的一半已經被保存,但提交的事務不回滾甚至異常的過程中提出的。

任何想法將不勝感激。

+0

[ATOMIC \ _REQUEST和Django 1.6中的事務]的可能重複(http://stackoverflow.com/questions/20682954/atomic-request-and-transactions-in-django-1-6) –

回答

2

您應該多閱讀一下關於事務如何與Django一起工作的內容。 由於您正在捕獲異常,因此無論您的響應代碼是什麼,Django都會看到一切正常,並會提交事務。取自https://docs.djangoproject.com/en/1.10/topics/db/transactions/#tying-transactions-to-http-requests

它的工作原理是這樣的。在調用視圖函數之前,Django啓動一個 事務。如果響應沒有問題產生,Django 提交事務。如果視圖產生異常,Django 回滾事務。

因此,由於您正在捕捉異常並返回響應,Django認爲沒有理由執行回滾。