diff --git a/facts/serializers.py b/facts/serializers.py new file mode 100644 index 0000000..6cb8984 --- /dev/null +++ b/facts/serializers.py @@ -0,0 +1,14 @@ +"""Serializers for the fact objects.""" +from rest_framework import serializers + +from facts.models import Fact + + +class FactSerializer(serializers.ModelSerializer): + """Serializer for the REST API.""" + + class Meta: + """Meta options.""" + + model = Fact + fields = ('id', 'fact', 'category') diff --git a/facts/urls.py b/facts/urls.py index 826a334..1268182 100644 --- a/facts/urls.py +++ b/facts/urls.py @@ -1,9 +1,13 @@ """URL patterns for the facts web views.""" from django.conf.urls import url +from django.urls import path -from facts.views import index, factcategory_detail +from facts.views import factcategory_detail, index, rpc_get_facts, rpc_get_random_fact urlpatterns = [ + path('rpc//', rpc_get_facts, name='weather_rpc_get_facts'), + path('rpc//random/', rpc_get_random_fact, name='weather_rpc_get_random_fact'), + url(r'^$', index, name='facts_index'), url(r'^(?P.+)/$', factcategory_detail, name='facts_factcategory_detail'), ] diff --git a/facts/views.py b/facts/views.py index 3dfb112..896d5d4 100644 --- a/facts/views.py +++ b/facts/views.py @@ -2,12 +2,49 @@ import logging from django.shortcuts import get_object_or_404, render +from rest_framework.authentication import BasicAuthentication +from rest_framework.decorators import api_view, authentication_classes, permission_classes +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response from facts.models import FactCategory +from facts.serializers import FactSerializer log = logging.getLogger(__name__) +@api_view(['GET']) +@authentication_classes((BasicAuthentication, )) +@permission_classes((IsAuthenticated, )) +def rpc_get_facts(request, category): + """Get all the facts in a category.""" + if request.method != 'GET': + return Response({'detail': "Supported method: GET."}, status=405) + + try: + fact_category = FactCategory.objects.get(name=category) + except FactCategory.DoesNotExist: + return Response({'detail': f"Item set category '{category}' not found."}, status=404) + + return Response(FactSerializer(fact_category.fact_set.all(), many=True).data) + + +@api_view(['GET']) +@authentication_classes((BasicAuthentication, )) +@permission_classes((IsAuthenticated, )) +def rpc_get_random_fact(request, category): + """Get all the facts in a category.""" + if request.method != 'GET': + return Response({'detail': "Supported method: GET."}, status=405) + + try: + fact_category = FactCategory.objects.get(name=category) + except FactCategory.DoesNotExist: + return Response({'detail': f"Item set category '{category}' not found."}, status=404) + + return Response(FactSerializer(fact_category.random_fact()).data) + + def index(request): """Display a simple list of the fact categories, for the moment.""" factcategories = FactCategory.objects.all()