From 30c3c3eb7a75ca6610a0c0dba6bdf228db9b4630 Mon Sep 17 00:00:00 2001 From: Dariusz Niemczyk Date: Mon, 17 Jul 2023 20:14:06 +0200 Subject: [PATCH] Deduplicate print function --- storage/apiviews.py | 20 +++++++++----------- storage/models.py | 14 +++++++------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/storage/apiviews.py b/storage/apiviews.py index fbc2f3b..6e632e8 100644 --- a/storage/apiviews.py +++ b/storage/apiviews.py @@ -12,6 +12,13 @@ from django.shortcuts import get_object_or_404 from storage.views import apply_smart_search +def api_print(quantity, obj): + amount = min(int(quantity), 5) + for _ in range(amount): + obj.print() + return Response({"status": "success"}) + + class SmartSearchFilterBackend(filters.BaseFilterBackend): """ Filters query using smartsearch filter @@ -35,11 +42,7 @@ class LabelViewSet(viewsets.ModelViewSet): @action(detail=True, methods=["post"], permission_classes=[AllowAny]) def print(self, request, pk): - quantity = min(int(request.query_params.get("quantity", 1)), 5) - obj = self.get_object() - for _ in range(quantity): - obj.print() - return obj + return api_print(request.query_params.get("quantity", 1), self.get_object()) class ItemViewSet(viewsets.ModelViewSet): @@ -76,12 +79,7 @@ class ItemViewSet(viewsets.ModelViewSet): @action(detail=True, methods=["post"], permission_classes=[AllowAny]) def print(self, request, pk): - # todo: deduplicate - quantity = min(int(request.query_params.get("quantity", 1)), 5) - obj = self.get_object() - for _ in range(quantity): - obj.print() - return obj + return api_print(request.query_params.get("quantity", 1), self.get_object()) @action( detail=True, diff --git a/storage/models.py b/storage/models.py index b546fb0..91395ad 100644 --- a/storage/models.py +++ b/storage/models.py @@ -23,6 +23,11 @@ STATES = ( ) +def api_print(id): + resp = requests.post("{}/api/1/print/{}".format(settings.LABEL_API, id)) + resp.raise_for_status() + + class Category(models.Model): name = models.CharField(max_length=127) @@ -103,11 +108,7 @@ class Item(models.Model, TreeModelMixin): return next((c for c in self.categories.all() if c.icon_id), None) def print(self): - # todo: deduplicate - resp = requests.post( - "{}/api/1/print/{}".format(settings.LABEL_API, self.short_id()) - ) - resp.raise_for_status() + api_print(self.short_id()) class Meta: ordering = ("path",) @@ -135,5 +136,4 @@ class Label(models.Model): return "{}".format(self.id) def print(self): - resp = requests.post("{}/api/1/print/{}".format(settings.LABEL_API, self.id)) - resp.raise_for_status() + api_print(self.id)