<commit_before>"""
Polling Stations Open Data API
"""

from django.utils.encoding import smart_str
from rest_framework import routers, serializers, viewsets, views
from councils.models import Council
from data_finder.views import LogLookUpMixin
from pollingstations.models import (PollingStation, PollingDistrict,
    ResidentialAddress, CustomFinder)

# Fields define serialization of complex field types (GEO)
class PointField(serializers.Field):
    type_name = 'PointField'
    type_label = 'point'

    def to_representation(self, value):
        """
        Transform POINT object to json.
        """
        if value is None:
            return value

        value = {
            "latitude": smart_str(value.y),
            "longitude": smart_str(value.x)
        }
        return value


class PolygonField(serializers.Field):
    type_name = 'PolygonField'
    type_label = 'polygon'

    def to_representation(self, value):
        if value is None:
            return value
        return value.coords


# Serializers define the API representation.
class CouncilSerializer(serializers.HyperlinkedModelSerializer):
    location = PointField()
#    area = PolygonField()
    class Meta:
        model = Council
        fields = (
            'council_id', 'council_type', 'mapit_id', 'name',
            'email', 'phone', 'website', 'postcode', 'address',
            'location',
#            'area' # This is super slow ATM - TODO!
        )


class PollingStationSerializer(serializers.HyperlinkedModelSerializer):
    location = PointField()
    class Meta:
        model = PollingStation
        fields = ('council', 'postcode', 'address', 'location')


class ResidentialAddressSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = ResidentialAddress
        fields = ('address','postcode','council','polling_station_id')


class PollingDistrictSerializer(serializers.HyperlinkedModelSerializer):
    # area = PolygonField()
    class Meta:
        model = PollingDistrict
        fields = (
            'name', 'council',
#            'area' This is super slow ATM TODO!
        )


# ViewSets define the view behavior.
class CouncilViewSet(viewsets.ModelViewSet):
    queryset = Council.objects.all()
    serializer_class = CouncilSerializer


class PollingStationViewSet(viewsets.ModelViewSet):
    queryset = PollingStation.objects.all()
    serializer_class = PollingStationSerializer


class PollingDistrictViewSet(viewsets.ModelViewSet):
    queryset = PollingDistrict.objects.all()
    serializer_class = PollingDistrictSerializer

from rest_framework.response import Response
from data_finder.helpers import (
    geocode,
    PostcodeError,
    RateLimitError,
    RoutingHelper
)
from django.contrib.gis.geos import Point


class PostcodeViewSet(viewsets.ViewSet, LogLookUpMixin):
    def get_queryset(self, **kwargs):
        if not kwargs:
            return PollingStation.objects.all()
        assert 'location' in kwargs
        assert 'council' in kwargs
        return PollingStation.objects.get_polling_station(
            kwargs['council']['council_id'],
            location=kwargs['location']
        )

    def retrieve(self, requst, pk=None, format=None):
        postcode = pk.replace(' ', '')
        ret = {}
        ret['polling_station_known'] = False
        polling_station = None

        try:
            l = geocode(pk)
        except (PostcodeError, RateLimitError) as e:
            ret['error'] = e.args[0]
            return Response(ret)

        location = Point(l['wgs84_lon'], l['wgs84_lat'])
        ret['postcode_location'] = PointField().to_representation(
            location)<commit_msg>return correct HTTP response codes on error<commit_after>"""
Polling Stations Open Data API
"""

from django.utils.encoding import smart_str
from rest_framework import routers, serializers, viewsets, views
from councils.models import Council
from data_finder.views import LogLookUpMixin
from pollingstations.models import (PollingStation, PollingDistrict,
    ResidentialAddress, CustomFinder)

# Fields define serialization of complex field types (GEO)
class PointField(serializers.Field):
    type_name = 'PointField'
    type_label = 'point'

    def to_representation(self, value):
        """
        Transform POINT object to json.
        """
        if value is None:
            return value

        value = {
            "latitude": smart_str(value.y),
            "longitude": smart_str(value.x)
        }
        return value


class PolygonField(serializers.Field):
    type_name = 'PolygonField'
    type_label = 'polygon'

    def to_representation(self, value):
        if value is None:
            return value
        return value.coords


# Serializers define the API representation.
class CouncilSerializer(serializers.HyperlinkedModelSerializer):
    location = PointField()
#    area = PolygonField()
    class Meta:
        model = Council
        fields = (
            'council_id', 'council_type', 'mapit_id', 'name',
            'email', 'phone', 'website', 'postcode', 'address',
            'location',
#            'area' # This is super slow ATM - TODO!
        )


class PollingStationSerializer(serializers.HyperlinkedModelSerializer):
    location = PointField()
    class Meta:
        model = PollingStation
        fields = ('council', 'postcode', 'address', 'location')


class ResidentialAddressSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = ResidentialAddress
        fields = ('address','postcode','council','polling_station_id')


class PollingDistrictSerializer(serializers.HyperlinkedModelSerializer):
    # area = PolygonField()
    class Meta:
        model = PollingDistrict
        fields = (
            'name', 'council',
#            'area' This is super slow ATM TODO!
        )


# ViewSets define the view behavior.
class CouncilViewSet(viewsets.ModelViewSet):
    queryset = Council.objects.all()
    serializer_class = CouncilSerializer


class PollingStationViewSet(viewsets.ModelViewSet):
    queryset = PollingStation.objects.all()
    serializer_class = PollingStationSerializer


class PollingDistrictViewSet(viewsets.ModelViewSet):
    queryset = PollingDistrict.objects.all()
    serializer_class = PollingDistrictSerializer

from rest_framework.response import Response
from data_finder.helpers import (
    geocode,
    PostcodeError,
    RateLimitError,
    RoutingHelper
)
from django.contrib.gis.geos import Point


class PostcodeViewSet(viewsets.ViewSet, LogLookUpMixin):
    def get_queryset(self, **kwargs):
        if not kwargs:
            return PollingStation.objects.all()
        assert 'location' in kwargs
        assert 'council' in kwargs
        return PollingStation.objects.get_polling_station(
            kwargs['council']['council_id'],
            location=kwargs['location']
        )

    def retrieve(self, requst, pk=None, format=None):
        postcode = pk.replace(' ', '')
        ret = {}
        ret['polling_station_known'] = False
        polling_station = None

        try:
            l = geocode(pk)
        except PostcodeError as e:
            ret['error'] = e.args[0]
            return Response(ret, status=400)
        except RateLimitError as e:
            ret['error'] = e.args[0]
            return Response(ret, status=403)

        location = Point(l['wgs84_lon'], l['wgs84_lat'])
        ret['postcode_location'] = PointField().to_representation(
            location)
{'fraction_non_alphanumeric': 0.0935002663825253, 'fraction_numerical': 0.002264251465103889, 'mean_word_length': 2.9150156412930137, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2191232', 'n_tokens_mistral': 2134, 'n_tokens_neox': 2040, 'n_words': 508}