source.py 2.96 KB
Newer Older
1
2
import logging

3
from drf_yasg.utils import swagger_auto_schema
4
5
6
from marshmallow.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.status import HTTP_422_UNPROCESSABLE_ENTITY
7
from requests.models import HTTPError
8
9
10

from metagenedb.apps.catalog.models import Source
from metagenedb.apps.catalog.serializers import SourceSerializer
11
12
from metagenedb.api.catalog.qparams_validators.source import SourceQueryParams
from metagenedb.common.utils.external_api.doi_api import GetDOIExternalInfo
13
14
15
16

from .base import BulkViewSet


17
18
19
logger = logging.getLogger(__name__)


20
21
22
23
class SourceViewSet(BulkViewSet):
    queryset = Source.objects.all()
    serializer_class = SourceSerializer
    lookup_field = 'slug'
24
    query_params_parser = SourceQueryParams
25
26
27
28
29
30
31
32
33

    @swagger_auto_schema(
        operation_description="List all gene sources",
        operation_summary="API to list all gene sources of the catalog.",
        tags=['Source'],
    )
    def list(self, *args, **kwargs):
        return super().list(*args, **kwargs)

34
35
36
    def _get_external_info(self, db_data):
        detailed_info_retriever = GetDOIExternalInfo(db_data['doi'])
        try:
Kenzo-Hugo Hillion's avatar
Kenzo-Hugo Hillion committed
37
            db_data['doi-info'] = detailed_info_retriever.get_details()
38
39
40
        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)
41
42
        except HTTPError:
            logger.warning("Could not get info from external API source, returning default response.")
43
        return db_data
44

45
46
47
48
49
    @swagger_auto_schema(
        operation_description="Retrieve gene source from a name",
        operation_summary="API to retrieve gene source.",
        tags=['Source'],
    )
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    def retrieve(self, request, *args, **kwargs):
        try:
            query_params = self.query_params_parser().load(request.query_params)
        except ValidationError as validation_error:
            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)
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        returned_data = serializer.data
        if query_params.get('detailed', False) is True:
            returned_data = self._get_external_info(returned_data)
        return Response(returned_data)
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

    @swagger_auto_schema(
        tags=['Source'],
    )
    def create(self, *args, **kwargs):
        return super().create(*args, **kwargs)

    @swagger_auto_schema(
        tags=['Source'],
    )
    def update(self, *args, **kwargs):
        return super().update(*args, **kwargs)

    @swagger_auto_schema(
        tags=['Source'],
    )
    def partial_update(self, *args, **kwargs):
        return super().partial_update(*args, **kwargs)