add RPC API to retrieve fact(s)

This commit is contained in:
Brian S. Stephan 2021-04-25 18:48:34 -05:00
parent 1fc8af09f8
commit 3aa3fb14e4
3 changed files with 56 additions and 1 deletions

14
facts/serializers.py Normal file
View File

@ -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')

View File

@ -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/<category>/', rpc_get_facts, name='weather_rpc_get_facts'),
path('rpc/<category>/random/', rpc_get_random_fact, name='weather_rpc_get_random_fact'),
url(r'^$', index, name='facts_index'),
url(r'^(?P<factcategory_name>.+)/$', factcategory_detail, name='facts_factcategory_detail'),
]

View File

@ -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()