From 3e7f96c0b8e5edcc89a62c1cc1b1c8843dd2b0f6 Mon Sep 17 00:00:00 2001 From: vabene1111 Date: Sun, 7 Feb 2021 13:43:24 +0100 Subject: [PATCH] basic export to zip working --- cookbook/integration/default.py | 17 ++++++++++++----- cookbook/views/views.py | 3 +-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/cookbook/integration/default.py b/cookbook/integration/default.py index fb91377e..c202b04d 100644 --- a/cookbook/integration/default.py +++ b/cookbook/integration/default.py @@ -1,7 +1,10 @@ import json import os +from io import StringIO, BytesIO +from os.path import basename from zipfile import ZipFile +from django.http import HttpResponse from rest_framework.renderers import JSONRenderer from cookbook.integration.integration import Integration @@ -12,7 +15,8 @@ class Default(Integration): def do_export(self, recipes): path = self.get_tmp_dir_path() - export_zip_obj = ZipFile(os.path.join(path, 'export.zip'), 'w') + s = BytesIO() + export_zip_obj = ZipFile(s, 'w') for r in recipes: if r.internal: @@ -22,15 +26,18 @@ class Default(Integration): f = open(os.path.join(path, str(r.pk), 'recipe.json'), "w", encoding="utf-8") f.write(self.get_export(r)) - recipe_zip_obj.write(f.name) - recipe_zip_obj.write(r.image.path) + recipe_zip_obj.write(f.name, basename(f.name)) + recipe_zip_obj.write(r.image.path, basename(r.image.path)) f.close() recipe_zip_obj.close() - export_zip_obj.write(recipe_zip_obj.filename) + export_zip_obj.write(recipe_zip_obj.filename, basename(recipe_zip_obj.filename)) export_zip_obj.close() - return export_zip_obj.filename + + response = HttpResponse(s.getvalue(), content_type='application/force-download') + response['Content-Disposition'] = 'attachment; filename="export.zip"' + return response def get_recipe(self, string): data = json.loads(string) diff --git a/cookbook/views/views.py b/cookbook/views/views.py index 08341377..a6ef2adf 100644 --- a/cookbook/views/views.py +++ b/cookbook/views/views.py @@ -506,8 +506,7 @@ def test2(request): form = NewExportForm(request.POST) if form.is_valid(): integration = Default(request) - integration.do_export(form.cleaned_data['recipes']) - return render(request, 'test2.html', {'form': form}) + return integration.do_export(form.cleaned_data['recipes']) else: form = NewExportForm()