1
當我需要將文件保存在服務器上並將相應的記錄放入數據庫時,我具有功能。我怎樣才能確保兩個事件都不發生?如何回滾數據庫查詢是否尚未保存在服務器上?
現在我有以下邏輯,但有沒有更好的解決方案?
def handle_uploaded_file(filename, file_content, request):
# Saves file on the server
try:
path_to_file = '{}/{}'.format(settings.REPORTS_FOLDER, filename)
with open(path_to_file, 'wb+') as destination:
for chunk in file_content.chunks():
destination.write(chunk)
except IOError:
raise
# Saves info about uploaded file in the database
try:
with transaction.atomic():
new_report = Reports(
path_to_file=path_to_file,
document_name=filename,
author=request.user,
document_type=request.POST['report_type']
)
new_report.save()
except IntegrityError:
os.remove(path_to_file)
raise
使用交易 – utkbansal