2016-09-19 9 views
1

私はDRF、API Viewクラスベースのビュー、メソッドを使用しています。 パラメータ:file ロジック:ファイルの検証を行い、ファイルを段階的に保存します(異なるタイプのオブジェクト) ファイルの残りの部分を保存している間に例外が発生した場合、トランザクションをロールバックしようとしています。私は'ATOMIC_REQUESTS'を設定:Trueアトミックトランザクションが機能していませんdjango rest

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はロールバックを実行する理由は見当たりません。

関連する問題