From 774bfdb9e7b392c21bc181543544cc3b849430b4 Mon Sep 17 00:00:00 2001 From: Oliver Date: Thu, 12 May 2022 11:22:34 +1000 Subject: [PATCH] Adds APIDownloadMixin class to implement common behaviour --- InvenTree/InvenTree/api.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/InvenTree/InvenTree/api.py b/InvenTree/InvenTree/api.py index 171fe414d2..3b440a1f3d 100644 --- a/InvenTree/InvenTree/api.py +++ b/InvenTree/InvenTree/api.py @@ -61,6 +61,44 @@ class NotFoundView(AjaxView): return JsonResponse(data, status=404) +class APIDownloadMixin: + """ + Mixin for enabling a LIST endpoint to be downloaded a file. + + To download the data, add the ?export= to the query string. + + The implementing class must provided a download_queryset method, + e.g. + + def download_queryset(self, queryset, export_format): + dataset = StockItemResource().export(queryset=queryset) + + filedata = dataset.export(export_format) + + filename = 'InvenTree_Stocktake_{date}.{fmt}'.format( + date=datetime.now().strftime("%d-%b-%Y"), + fmt=export_format + ) + + return DownloadFile(filedata, filename) + """ + + def get(self, request, *args, **kwargs): + + export_format = request.query_params.get('export', None) + + if export_format: + queryset = self.filter_queryset(self.get_queryset()) + return self.download_queryset(queryset, export_format) + + else: + # Default to the parent class implementation + return super().get(request, *args, **kwargs) + + def download_queryset(self, queryset, export_format): + raise NotImplementedError("download_queryset method not implemented!") + + class AttachmentMixin: """ Mixin for creating attachment objects,