gpt4 book ai didi

django - 原子事务不起作用 django rest

转载 作者:行者123 更新时间:2023-12-05 08:27:30 24 4
gpt4 key购买 nike

我正在使用 DRF、基于 API View 类的 View 、post 方法。参数是:文件逻辑:对文件进行一些验证并逐步保存文件(不同类型的对象)如果在保存文件的其余部分时发生异常,我将尝试回滚事务。我设置了 'ATOMIC_REQUESTS': True

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)

我故意在文件已保存一半时抛出异常,但提交的事务不会回滚,即使在此过程中引发异常也是如此。

如有任何想法,我们将不胜感激。

最佳答案

您应该阅读更多有关事务如何与 Django 一起工作的内容。由于您正在捕获异常,无论您的响应代码是什么,Django 都会看到一切正常并提交事务。取自https://docs.djangoproject.com/en/1.10/topics/db/transactions/#tying-transactions-to-http-requests :

It works like this. Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction.

因此,由于您正在捕获异常并返回响应,Django 认为没有理由执行回滚。

关于django - 原子事务不起作用 django rest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39566210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com