function.py 2.48 KB
Newer Older
1
import logging
2
3

from marshmallow.exceptions import ValidationError
4
from rest_framework.response import Response
5
from rest_framework.status import HTTP_422_UNPROCESSABLE_ENTITY
6
from rest_framework.viewsets import ModelViewSet
7

8
from metagenedb.api.catalog.filters import FunctionFilter
9
from metagenedb.api.catalog.qparams_validators.function import FunctionQueryParams
10
11
from metagenedb.apps.catalog.models import EggNOGv5, Function, KeggOrthology
from metagenedb.apps.catalog.serializers import EggNOGSerializer, FunctionSerializer, KeggOrthologySerializer
12
from metagenedb.common.utils.external_api.togows import GetFunctionExternalInfo
13

14
15
from .bulk_viewset import BulkViewSet

16

17
18
19
logger = logging.getLogger(__name__)


20
class FunctionViewSet(BulkViewSet):
21
22
23
    queryset = Function.objects.all()
    serializer_class = FunctionSerializer
    lookup_field = 'function_id'
24
    filterset_class = FunctionFilter
25
26
27
28
29
30


class KeggOrthologyViewSet(ModelViewSet):
    queryset = KeggOrthology.objects.all()
    serializer_class = KeggOrthologySerializer
    lookup_field = 'function_id'
31
    query_params_parser = FunctionQueryParams
32

33
    def _get_external_info(self, db_data):
34
        detailed_info_retriever = GetFunctionExternalInfo(db_data['function_id'], 'kegg')
35
36
37
38
39
40
        try:
            detailed_data = detailed_info_retriever.get_details()
        except NotImplementedError as not_implemented_error:
            logger.warning("Could not found API for the source, returning item from the DB. Error: %s" %
                           not_implemented_error)
            detailed_data = db_data
41
42
        return detailed_data

43
    def retrieve(self, request, *args, **kwargs):
44
        try:
45
            query_params = self.query_params_parser().load(request.query_params)
46
        except ValidationError as validation_error:
47
48
49
50
51
            error_message = validation_error.normalized_messages()
            error_message.update({
                'allowed_query_params': ', '.join(self.query_params_parser().declared_fields.keys())
            })
            return Response(error_message, status=HTTP_422_UNPROCESSABLE_ENTITY)
52
53
        instance = self.get_object()
        serializer = self.get_serializer(instance)
54
        returned_data = serializer.data
55
        if query_params.get('detailed', False) is True:
56
57
            returned_data = self._get_external_info(returned_data)
        return Response(returned_data)
58
59


60
61
62
class EggNOGv5ViewSet(ModelViewSet):
    queryset = EggNOGv5.objects.all()
    serializer_class = EggNOGSerializer
63
    lookup_field = 'function_id'