Commit befb3537 authored by Samuel GAIST's avatar Samuel GAIST
Browse files

[databases][api] Code cleanup

parent dbbed637
...@@ -27,13 +27,12 @@ ...@@ -27,13 +27,12 @@
import os import os
import json import json
import logging
from django.http import HttpResponse
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework import permissions from rest_framework import permissions
from rest_framework import exceptions as drf_exceptions
from rest_framework import views from rest_framework import views
from rest_framework import status
from .models import Database from .models import Database
from .models import DatabaseSetTemplate from .models import DatabaseSetTemplate
...@@ -44,10 +43,8 @@ from ..common import is_true ...@@ -44,10 +43,8 @@ from ..common import is_true
from ..common.mixins import IsAdminOrReadOnlyMixin from ..common.mixins import IsAdminOrReadOnlyMixin
from ..common.api import ListCreateBaseView from ..common.api import ListCreateBaseView
from ..common.utils import ensure_html from ..common.utils import ensure_html
from ..dataformats.serializers import ReferencedDataFormatSerializer
import logging from ..dataformats.serializers import ReferencedDataFormatSerializer
import traceback
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -55,7 +52,7 @@ logger = logging.getLogger(__name__) ...@@ -55,7 +52,7 @@ logger = logging.getLogger(__name__)
# ---------------------------------------------------------- # ----------------------------------------------------------
def database_to_json(database, request_user, fields_to_return, last_version=None): def database_to_json(database, request_user, fields_to_return):
# Prepare the response # Prepare the response
result = {} result = {}
...@@ -67,7 +64,14 @@ def database_to_json(database, request_user, fields_to_return, last_version=None ...@@ -67,7 +64,14 @@ def database_to_json(database, request_user, fields_to_return, last_version=None
result["version"] = database.version result["version"] = database.version
if "last_version" in fields_to_return: if "last_version" in fields_to_return:
result["last_version"] = last_version latest = (
Database.objects.for_user(request_user, True)
.filter(name=database.name)
.order_by("-version")[:1]
.first()
)
result["last_version"] = database.version == latest.version
if "short_description" in fields_to_return: if "short_description" in fields_to_return:
result["short_description"] = database.short_description result["short_description"] = database.short_description
...@@ -204,35 +208,25 @@ class RetrieveDatabaseView(views.APIView): ...@@ -204,35 +208,25 @@ class RetrieveDatabaseView(views.APIView):
Returns the given database details Returns the given database details
""" """
model = Database
permission_classes = [permissions.AllowAny] permission_classes = [permissions.AllowAny]
def get(self, request, database_name, version=None): def get_object(self):
# Retrieve the database version = self.kwargs["version"]
database_name = self.kwargs["database_name"]
user = self.request.user
try: try:
if version is not None: obj = self.model.objects.for_user(user, True).get(
version = int(version) name__iexact=database_name, version=version
)
databases = ( except self.model.DoesNotExist:
Database.objects.for_user(request.user, True) raise drf_exceptions.NotFound()
.filter(name__iexact=database_name, version__gte=version) return obj
.order_by("version")
)
database = databases[0]
if database.version != version:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
last_version = len(databases) == 1 def get(self, request, database_name, version):
else: # Retrieve the database
database = ( database = self.get_object()
Database.objects.for_user(request.user, True) self.check_object_permissions(request, database)
.filter(name__iexact=database_name)
.order_by("-version")[0]
)
last_version = True
except Exception:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
# Process the query string # Process the query string
if "fields" in request.GET: if "fields" in request.GET:
...@@ -256,68 +250,50 @@ class RetrieveDatabaseView(views.APIView): ...@@ -256,68 +250,50 @@ class RetrieveDatabaseView(views.APIView):
"code", "code",
] ]
try: # Prepare the response
# Prepare the response result = database_to_json(database, request.user, fields_to_return)
result = database_to_json(
database, request.user, fields_to_return, last_version=last_version
)
# Retrieve the code # Retrieve the code
if "declaration" in fields_to_return: if "declaration" in fields_to_return:
try: declaration = database.declaration
declaration = database.declaration cleaned_declaration = clean_paths(declaration)
except Exception: result["declaration"] = json.dumps(cleaned_declaration)
logger.error(traceback.format_exc())
return HttpResponse(status=500) # Retrieve the source code
cleaned_declaration = clean_paths(declaration) if "code" in fields_to_return:
result["declaration"] = json.dumps(cleaned_declaration) result["code"] = database.source_code
# Retrieve the source code # Retrieve the description in HTML format
if "code" in fields_to_return: if "html_description" in fields_to_return:
try: description = database.description
result["code"] = database.source_code if len(description) > 0:
except Exception: result["html_description"] = ensure_html(description)
logger.error(traceback.format_exc()) else:
return HttpResponse(status=500) result["html_description"] = ""
# Retrieve the description in HTML format # Retrieve the referenced data formats
if "html_description" in fields_to_return: if "referenced_dataformats" in fields_to_return:
description = database.description dataformats = database.all_referenced_dataformats()
if len(description) > 0:
result["html_description"] = ensure_html(description) referenced_dataformats = []
else: for dataformat in dataformats:
result["html_description"] = "" (has_access, accessibility) = dataformat.accessibility_for(request.user)
if has_access:
# Retrieve the referenced data formats referenced_dataformats.append(dataformat)
if "referenced_dataformats" in fields_to_return: serializer = ReferencedDataFormatSerializer(referenced_dataformats)
dataformats = database.all_referenced_dataformats() result["referenced_dataformats"] = serializer.data
referenced_dataformats = [] # Retrieve the needed data formats
for dataformat in dataformats: if "needed_dataformats" in fields_to_return:
(has_access, accessibility) = dataformat.accessibility_for( dataformats = database.all_needed_dataformats()
request.user
) needed_dataformats = []
if has_access: for dataformat in dataformats:
referenced_dataformats.append(dataformat) (has_access, accessibility) = dataformat.accessibility_for(request.user)
serializer = ReferencedDataFormatSerializer(referenced_dataformats) if has_access:
result["referenced_dataformats"] = serializer.data needed_dataformats.append(dataformat)
serializer = ReferencedDataFormatSerializer(needed_dataformats)
# Retrieve the needed data formats result["needed_dataformats"] = serializer.data
if "needed_dataformats" in fields_to_return:
dataformats = database.all_needed_dataformats() # Return the result
return Response(result)
needed_dataformats = []
for dataformat in dataformats:
(has_access, accessibility) = dataformat.accessibility_for(
request.user
)
if has_access:
needed_dataformats.append(dataformat)
serializer = ReferencedDataFormatSerializer(needed_dataformats)
result["needed_dataformats"] = serializer.data
# Return the result
return Response(result)
except Exception:
logger.error(traceback.format_exc())
return HttpResponse(status=500)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment