From 7a58c60954fea0d131caeaa37382e72645185f41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Gasser?= Date: Tue, 25 Feb 2020 10:37:33 -0500 Subject: [PATCH] gzip models during download (#168) --- backend/substrapp/views/model.py | 14 ++++++++++++++ backend/substrapp/views/utils.py | 8 ++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/backend/substrapp/views/model.py b/backend/substrapp/views/model.py index 65cac1f02..96fc5d88c 100644 --- a/backend/substrapp/views/model.py +++ b/backend/substrapp/views/model.py @@ -1,6 +1,8 @@ import tempfile import logging from django.http import Http404 +from functools import wraps +from django.middleware.gzip import GZipMiddleware from rest_framework import status, mixins from rest_framework.decorators import action from rest_framework.response import Response @@ -116,6 +118,17 @@ def details(self, request, *args, **kwargs): return Response(data, status=status.HTTP_200_OK) +def gzip_action(func): + gz = GZipMiddleware() + + @wraps(func) + def wrapper(self, request, *args, **kwargs): + resp = func(self, request, *args, **kwargs) + return gz.process_response(request, resp) + + return wrapper + + class ModelPermissionViewSet(PermissionMixin, GenericViewSet): @@ -137,6 +150,7 @@ def has_access(self, user, asset): return permissions['public'] or node_id in permissions['authorizedIDs'] + @gzip_action @action(detail=True) def file(self, request, *args, **kwargs): return self.download_local_file(request, django_field='file') diff --git a/backend/substrapp/views/utils.py b/backend/substrapp/views/utils.py index deacfa400..012f644dd 100644 --- a/backend/substrapp/views/utils.py +++ b/backend/substrapp/views/utils.py @@ -1,7 +1,7 @@ import os -from django.http import FileResponse +from django.http import FileResponse, HttpResponse from rest_framework.authentication import BasicAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @@ -106,11 +106,11 @@ def download_local_file(self, request, django_field, ledger_field=None): try: asset = get_object_from_ledger(pk, self.ledger_query_call) except LedgerError as e: - return Response({'message': str(e.msg)}, status=e.status) + return HttpResponse({'message': str(e.msg)}, status=e.status) if not self.has_access(request.user, asset): - return Response({'message': 'Unauthorized'}, - status=status.HTTP_403_FORBIDDEN) + return HttpResponse({'message': 'Unauthorized'}, + status=status.HTTP_403_FORBIDDEN) if not ledger_field: ledger_field = django_field