Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Export products in batches
IKarbowiakd414cafad33d
diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex 53dd522ff1..b748acc115 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -1,11 +1,14 @@+import osfrom tempfile import NamedTemporaryFile-from typing import IO, TYPE_CHECKING, Dict, List, Union+from typing import IO, TYPE_CHECKING, Dict, List, Set, Unionimport petl as etl+from django.conf import settingsfrom django.utils import timezonefrom ...celeryconf import appfrom ...core import JobStatus+from ...core.utils import build_absolute_urifrom ...product.models import Productfrom .. import FileTypes, eventsfrom ..emails import send_email_with_link_to_download_csv, send_export_failed_info@@ -17,10 +20,17 @@ if TYPE_CHECKING:from django.db.models import QuerySet+BATCH_SIZE = 10000++def on_task_failure(self, exc, task_id, args, kwargs, einfo):export_file_id = args[0]export_file = ExportFile.objects.get(pk=export_file_id)- update_export_file_when_task_finished(export_file, JobStatus.FAILED)++ export_file.content_file = None+ export_file.status = JobStatus.FAILED+ export_file.save(update_fields=["status", "updated_at", "content_file"])+events.export_failed_event(export_file=export_file,user=export_file.created_by,@@ -32,15 +42,13 @@ def on_task_failure(self, exc, task_id, args, kwargs, einfo):def on_task_success(self, retval, task_id, args, kwargs):export_file_id = args[0]- export_file = ExportFile.objects.get(pk=export_file_id)- update_export_file_when_task_finished(export_file, JobStatus.SUCCESS)- events.export_success_event(export_file=export_file, user=export_file.created_by)--def update_export_file_when_task_finished(export_file: ExportFile, status: JobStatus):- export_file.status = status # type: ignore+ export_file = ExportFile.objects.get(pk=export_file_id)+ export_file.status = JobStatus.SUCCESSexport_file.save(update_fields=["status", "updated_at"])+ events.export_success_event(export_file=export_file, user=export_file.created_by)+@app.task(on_success=on_task_success, on_failure=on_task_failure)def export_products(@@ -56,17 +64,12 @@ def export_products(export_fields, csv_headers_mapping, headers = get_export_fields_and_headers_info(export_info)+ export_file = ExportFile.objects.get(pk=export_file_id)- export_data = get_products_data(+ export_products_in_batches(queryset,+ export_info,set(export_fields),- export_info.get("warehouses"),- export_info.get("attributes"),- )-- export_file = ExportFile.objects.get(pk=export_file_id)- create_csv_file_and_save_in_export_file(- export_data,headers,csv_headers_mapping,delimiter,@@ -94,13 +97,68 @@ def get_product_queryset(scope: Dict[str, Union[str, dict]]) -> "QuerySet":elif "filter" in scope:queryset = ProductFilter(data=scope["filter"], queryset=queryset).qs- queryset = queryset.order_by("pk").prefetch_related(- "attributes", "variants", "collections", "images", "product_type", "category"- )+ queryset = queryset.order_by("pk")return queryset+def export_products_in_batches(+ queryset: "QuerySet",+ export_info: Dict[str, list],+ export_fields: Set[str],+ headers: List[str],+ csv_headers_mapping: Dict[str, str],+ delimiter: str,+ export_file: ExportFile,+ file_name: str,+ file_type: str,+):+ products_count = queryset.count()+ warehouses = export_info.get("warehouses")+ attributes = export_info.get("attributes")++ create_file = True+ counter = 0+ while counter < products_count:+ qs = queryset[counter : counter + BATCH_SIZE]+ # filter cancel limiting the query, so we need to ensure that only part of+ # products will be fetch from database+ product_batch = (+ Product.objects.filter(pk__in=qs.values_list("pk", flat=True))+ .order_by("pk")+ .prefetch_related(+ "attributes",+ "variants",+ "collections",+ "images",+ "product_type",+ "category",+ )+ )++ export_data = get_products_data(+ product_batch, export_fields, warehouses, attributes,+ )++ if create_file:+ create_csv_file_and_save_in_export_file(+ export_data,+ headers,+ csv_headers_mapping,+ delimiter,+ export_file,+ file_name,+ file_type,+ )+ create_file = False+ else:+ append_to_file(export_data, headers, export_file, file_type, delimiter)++ counter += BATCH_SIZE++ send_email_with_link_to_download_csv(export_file, "export_products")++def create_csv_file_and_save_in_export_file(export_data: List[Dict[str, Union[str, bool]]],headers: List[str],@@ -122,6 +180,21 @@ def create_csv_file_and_save_in_export_file(save_csv_file_in_export_file(export_file, temporary_file, file_name)+def append_to_file(+ export_data: List[Dict[str, Union[str, bool]]],+ headers: List[str],+ export_file: ExportFile,+ file_type: str,+ delimiter: str,+):+ table = etl.fromdicts(export_data, header=headers, missing=" ")++ if file_type == FileTypes.CSV:+ etl.io.csv.appendcsv(table, export_file.content_file, delimiter=delimiter)+ else:+ etl.io.xlsx.appendxlsx(table, export_file.content_file.path)++def save_csv_file_in_export_file(export_file: ExportFile, temporary_file: IO[bytes], file_name: str):diff --git a/tests/test_csv_export.py b/tests/test_csv_export.pyindex 2d122a8e89..e7e69310f2 100644--- a/tests/test_csv_export.py+++ b/tests/test_csv_export.py@@ -1,8 +1,10 @@import datetimeimport shutil+from tempfile import NamedTemporaryFilefrom unittest.mock import ANY, MagicMock, Mock, patchimport openpyxl+import petl as etlimport pytestimport pytzfrom django.core.files import File@@ -12,6 +14,7 @@ from saleor.core import JobStatusfrom saleor.csv import ExportEvents, FileTypesfrom saleor.csv.models import ExportEvent, ExportFilefrom saleor.csv.utils.export import (+ append_to_file,create_csv_file_and_save_in_export_file,export_products,get_filename,@@ -19,8 +22,8 @@ from saleor.csv.utils.export import (on_task_failure,on_task_success,save_csv_file_in_export_file,- update_export_file_when_task_finished,)+from saleor.graphql.csv.enums import ProductFieldEnum@patch("saleor.csv.utils.export.send_export_failed_info")@@ -36,9 +39,13 @@ def test_on_task_failure(send_export_failed_info_mock, export_file):assert export_file.created_atprevious_updated_at = export_file.updated_at- on_task_failure(None, exc, task_id, args, kwargs, info)+ with freeze_time(datetime.datetime.now()) as frozen_datetime:+ on_task_failure(None, exc, task_id, args, kwargs, info)- export_file.refresh_from_db()+ export_file.refresh_from_db()+ assert export_file.updated_at == pytz.utc.localize(frozen_datetime())++ assert export_file.updated_at != previous_updated_atassert export_file.status == JobStatus.FAILEDassert export_file.created_atassert export_file.updated_at != previous_updated_at@@ -64,12 +71,15 @@ def test_on_task_success(export_file):assert export_file.created_atprevious_updated_at = export_file.updated_at- on_task_success(None, None, task_id, args, kwargs)+ with freeze_time(datetime.datetime.now()) as frozen_datetime:+ on_task_success(None, None, task_id, args, kwargs)++ export_file.refresh_from_db()+ assert export_file.updated_at == pytz.utc.localize(frozen_datetime())+ assert export_file.updated_at != previous_updated_at- export_file.refresh_from_db()assert export_file.status == JobStatus.SUCCESSassert export_file.created_at- assert export_file.updated_at != previous_updated_atassert ExportEvent.objects.filter(export_file=export_file,user=export_file.created_by,@@ -77,18 +87,8 @@ def test_on_task_success(export_file):)-def test_update_export_file_when_task_finished(export_file):- with freeze_time(datetime.datetime.now()) as frozen_datetime:- previous_updated_at = export_file.updated_at- update_export_file_when_task_finished(export_file, JobStatus.FAILED)-- export_file.refresh_from_db()- assert export_file.updated_at == pytz.utc.localize(frozen_datetime())- assert export_file.updated_at != previous_updated_at--@pytest.mark.parametrize(- "scope, filet_type",+ "scope, file_type",[({"filter": {"is_published": True}}, FileTypes.CSV),({"all": ""}, FileTypes.XLSX),@@ -96,17 +96,34 @@ def test_update_export_file_when_task_finished(export_file):)@patch("saleor.csv.utils.export.send_email_with_link_to_download_csv")@patch("saleor.csv.utils.export.save_csv_file_in_export_file")+@patch("saleor.csv.utils.export.export_products_in_batches")def test_export_products(+ export_products_in_batches_mock,save_csv_file_in_export_file_mock,send_email_mock,product_list,export_file,scope,- filet_type,+ file_type,):- export_info = {"fields": [], "warehouses": [], "attributes": []}- export_products(export_file.id, scope, export_info, filet_type)-+ export_info = {+ "fields": [ProductFieldEnum.NAME.value],+ "warehouses": [],+ "attributes": [],+ }+ export_products(export_file.id, scope, export_info, file_type)++ export_products_in_batches_mock.called_once_with(+ ANY,+ export_info,+ {"id", "name"},+ ["id", "name"],+ {"id": "id", "name": "name"},+ ";",+ ANY,+ ANY,+ file_type,+ )save_csv_file_in_export_file_mock.called_once_with(export_file, ANY)send_email_mock.called_once_with(export_file)@@ -166,11 +183,7 @@ def get_product_queryset_filter(product_list):assert queryset.count() == len(product_list) - 1-def test_create_csv_file_and_save_in_export_file_csv(export_file, tmpdir):- from django.conf import settings-- settings.MEDIA_ROOT = tmpdir-+def test_create_csv_file_and_save_in_export_file_csv(export_file, tmpdir, media_root):export_data = [{"id": "123", "name": "test1", "collections": "coll1"},{"id": "345", "name": "test2"},@@ -210,11 +223,7 @@ def test_create_csv_file_and_save_in_export_file_csv(export_file, tmpdir):shutil.rmtree(tmpdir)-def test_create_csv_file_and_save_in_export_file_xlsx(export_file, tmpdir):- from django.conf import settings-- settings.MEDIA_ROOT = tmpdir-+def test_create_csv_file_and_save_in_export_file_xlsx(export_file, tmpdir, media_root):export_data = [{"id": "123", "name": "test1", "collections": "coll1"},{"id": "345", "name": "test2"},@@ -222,7 +231,6 @@ def test_create_csv_file_and_save_in_export_file_xlsx(export_file, tmpdir):headers = ["id", "name", "collections"]csv_headers_mapping = {"id": "ID", "name": "NAME", "collections": "COLLECTIONS"}delimiter = ";"- export_file = export_filefile_name = "test.xlsx"export_file_csv_upload_dir = ExportFile.content_file.field.upload_to@@ -267,11 +275,7 @@ def test_create_csv_file_and_save_in_export_file_xlsx(export_file, tmpdir):shutil.rmtree(tmpdir)-def test_save_csv_file_in_export_file(export_file, tmpdir):- from django.conf import settings-- settings.MEDIA_ROOT = tmpdir-+def test_save_csv_file_in_export_file(export_file, tmpdir, media_root):file_mock = MagicMock(spec=File)file_mock.name = "temp_file.csv"file_name = "test.csv"@@ -284,3 +288,87 @@ def test_save_csv_file_in_export_file(export_file, tmpdir):assert export_file.content_fileshutil.rmtree(tmpdir)+++def test_append_to_file_for_csv(export_file, tmpdir, media_root):+ # given+ export_data = [+ {"id": "123", "name": "test1", "collections": "coll1"},+ {"id": "345", "name": "test2"},+ ]+ headers = ["id", "name", "collections"]+ delimiter = ";"++ file_name = "test.csv"++ table = etl.fromdicts([{"id": "1", "name": "A"}], header=headers, missing=" ")++ with NamedTemporaryFile() as temp_file:+ etl.tocsv(table, temp_file.name, delimiter=delimiter)+ export_file.content_file.save(file_name, temp_file)++ # when+ append_to_file(export_data, headers, export_file, FileTypes.CSV, delimiter)++ # then+ export_file.refresh_from_db()++ csv_file = export_file.content_file+ file_content = csv_file.read().decode().split("\r\n")+ assert ";".join(headers) in file_content+ assert ";".join(export_data[0].values()) in file_content+ assert (";".join(export_data[1].values()) + "; ") in file_content++ shutil.rmtree(tmpdir)+++def test_append_to_file_for_xlsx(export_file, tmpdir, media_root):+ # given+ export_data = [+ {"id": "123", "name": "test1", "collections": "coll1"},+ {"id": "345", "name": "test2"},+ ]+ expected_headers = ["id", "name", "collections"]+ delimiter = ";"++ file_name = "test.xlsx"++ table = etl.fromdicts(+ [{"id": "1", "name": "A"}], header=expected_headers, missing=" "+ )++ with NamedTemporaryFile() as temp_file:+ etl.io.xlsx.toxlsx(table, temp_file.name)+ export_file.content_file.save(file_name, temp_file)++ # when+ append_to_file(+ export_data, expected_headers, export_file, FileTypes.XLSX, delimiter+ )++ # then+ export_file.refresh_from_db()++ xlsx_file = export_file.content_file+ wb_obj = openpyxl.load_workbook(xlsx_file)++ sheet_obj = wb_obj.active+ max_col = sheet_obj.max_column+ max_row = sheet_obj.max_row+ expected_headers = expected_headers+ headers = [sheet_obj.cell(row=1, column=i).value for i in range(1, max_col + 1)]+ data = []+ for i in range(2, max_row + 1):+ row = []+ for j in range(1, max_col + 1):+ row.append(sheet_obj.cell(row=i, column=j).value)+ data.append(row)++ assert headers == expected_headers+ assert list(export_data[0].values()) in data+ row2 = list(export_data[1].values())+ # add string with space for collections column+ row2.append(" ")+ assert row2 in data++ shutil.rmtree(tmpdir)