diff --git a/dice/urls.py b/dice/urls.py new file mode 100644 index 0000000..9ac7509 --- /dev/null +++ b/dice/urls.py @@ -0,0 +1,8 @@ +"""URL patterns for the dice views.""" +from django.urls import path + +from dice.views import rpc_roll_dice + +urlpatterns = [ + path('rpc/roll/', rpc_roll_dice, name='dice_rpc_roll_dice'), +] diff --git a/dice/views.py b/dice/views.py new file mode 100644 index 0000000..4653f04 --- /dev/null +++ b/dice/views.py @@ -0,0 +1,36 @@ +"""Views for rolling dice.""" +import json +import logging + +from rest_framework.authentication import BasicAuthentication +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from rest_framework.decorators import api_view, authentication_classes, permission_classes + +from dice.roller import DiceRoller + +logger = logging.getLogger(__name__) +roller = DiceRoller() + + +@api_view(['POST']) +@authentication_classes((BasicAuthentication, )) +@permission_classes((IsAuthenticated, )) +def rpc_roll_dice(request): + """Get a dice string from the client, roll the dice, and give the result.""" + if request.method != 'POST': + return Response({'detail': "Supported method: POST."}, status=405) + + try: + roll_data = json.loads(request.body) + dice_str = roll_data['dice'] + except (json.decoder.JSONDecodeError, KeyError): + return Response({'detail': "Request must be JSON with a 'dice' parameter."}, status=400) + + try: + result_str = roller.do_roll(dice_str) + return Response({'dice': dice_str, 'result': result_str}) + except AssertionError as aex: + return Response({'detail': f"Could not roll dice: {aex}"}, status=400) + except ValueError: + return Response({'detail': f"Could not parse requested dice '{dice_str}'."}, status=400) diff --git a/dr_botzo/urls.py b/dr_botzo/urls.py index b163cf6..067163d 100644 --- a/dr_botzo/urls.py +++ b/dr_botzo/urls.py @@ -13,6 +13,7 @@ admin.autodiscover() urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'), + url(r'^dice/', include('dice.urls')), url(r'^dispatch/', include('dispatch.urls')), url(r'^itemsets/', include('facts.urls')), url(r'^karma/', include('karma.urls')),