Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
station_test_views.py 6.22 KiB
from .common import *
from ..models.stationtest import StationTest
from ..models.componenterror import ComponentError
from ..models.tileerror import TileError
from ..serializers.stationtest import StationTestSerializer
from ..serializers.componenterrors_generic import ComponentErrorPolymorphicSerializer

from ..serializers.tileerror import TileErrorPolymorphicSerializer
from rest_framework.serializers import Serializer
from ..station_test_raw_parser import parse_raw_station_test
import rest_framework.serializers as serializers
from ..exceptions import ItemAlreadyExists

import django.db.models.aggregates as aggregates

logger = logging.getLogger('views')


class ComponentErrorCountSummarySerializer(Serializer):
    parent__station_name = serializers.CharField()
    error_type = serializers.CharField()
    component_type = serializers.CharField()
    count = serializers.IntegerField()


class ComponentErrorCountSummaryViewSet(viewsets.ModelViewSet):
    queryset = ComponentError.objects.all(). \
        values('error_type', 'component_type', 'parent__station_name'). \
        annotate(count=aggregates.Count('error_type')).order_by('count')
    serializer_class = ComponentErrorCountSummarySerializer

    def get_queryset(self):
        """
        Optionally restrict the list of station test to a
            specific station
            time period
            station_type
        :return:
        """
        queryset = ComponentError.objects.all()
        for key, param in self.request.query_params.items():
            if key in RESERVED_FILTER_NAME:
                continue
            queryset = queryset.filter(**{key: param})
            logger.info(queryset.values('parent__station_name', 'error_type', 'component_type'))
        return queryset. \
            values('error_type', 'component_type', 'parent__station_name'). \
            annotate(count=aggregates.Count('error_type')).order_by('count')


# Create your views here.
class StationTestViewSet(viewsets.ModelViewSet):
    queryset = StationTest.objects.all()
    serializer_class = StationTestSerializer

    def get_queryset(self):
        """
        Optionally restrict the list of station test to a
            specific station
            time period
            station_type
        :return:
        """
        queryset = StationTest.objects.all()
        for key, param in self.request.query_params.items():
            if key in RESERVED_FILTER_NAME:
                continue
            queryset = queryset.filter(**{key: param})
        return queryset


class ComponentErrorViewSet(viewsets.ModelViewSet):
    queryset = ComponentError.objects.all()
    serializer_class = ComponentErrorPolymorphicSerializer

    def get_queryset(self):
        """
        Optionally restrict the list of station test to a
            specific station
            time period
            station_type
        :return:
        """
        queryset = ComponentError.objects.all()
        for key, param in self.request.query_params.items():
            if key in RESERVED_FILTER_NAME:
                continue
            queryset = queryset.filter(**{key: param})
        return queryset


class TileErrorViewSet(viewsets.ModelViewSet):
    queryset = TileError.objects.all()
    serializer_class = TileErrorPolymorphicSerializer

    def get_queryset(self):
        """
        Optionally restrict the list of station test to a
            specific station
            time period
            station_type
        :return:
        """
        queryset = TileError.objects.all()
        for key, param in self.request.query_params.items():
            if key in RESERVED_FILTER_NAME:
                continue
            queryset = queryset.filter(**{key: param})
        return queryset


@api_view(['POST'])
def insert_raw_station_test(request):
    """
    This function is meant to parse a request of the form
    {
    "content": "[STATION TEST RAW TEXT]"
    }
    parse the content field and create all the station_test entity related into the database
    :param request: HTTP request
    :return:
    """
    if request.method == 'POST':

        if 'content' in request.data:
            try:
                logger.info('handling raw request for %s', request)
                content = request.data['content']
                logger.info('handling raw request for data %s', content)
                parsed_content = parse_raw_station_test(content)
                if parsed_content is None:
                    raise Exception('cannot parse test {}'.format(content))
                logger.info('data parsed successfully for test')
                station_test_ids = []
                station_test_ids_already_present = []
                for entry in parsed_content:
                    try:
                        item = StationTestSerializer().create(entry)
                        station_test_ids.append(item.id)
                    except ItemAlreadyExists as e:
                        station_test_ids_already_present.append(e.instance_id)

            except Exception as e:
                logger.exception("exception occurred while parsing raw station info %s: %s", request.data['content'], e)
                return Response(exception=True,
                                data="the post message is not correct." +
                                     " It has to be of the form \{'content':[RAWSTRING]\}: %s. Request provided %s" % (
                                     e, request),
                                status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(exception=True,
                            data="the post message is not correct." +
                                 " It has to be of the form \{'content':[RAWSTRING]\}",
                            status=status.HTTP_400_BAD_REQUEST)
        logger.info('request processed correctly inserted %d of %d', len(station_test_ids),
                    len(station_test_ids) + len(station_test_ids_already_present))
        return Response(status=status.HTTP_200_OK,
                        data='Station tests inserted with ids {} \n'.format(station_test_ids) +
                             'Station tests already present with ids {}'.format(
                                 station_test_ids_already_present
                             )
                        )