The next piece we'll need to construct before we get to React is our API that will serve content to our frontend. Let's look at the steps:
- n bot/views.py, set up the index route that we'll use for testing, and an API route that we'll serve our information with:
from django.http import HttpResponse
from django.template import Context, loader
from bot.models import Text
import random
import json
def index(request):
template = loader.get_template("bot/index.html")
return HttpResponse(template.render())
def api(request):
if request.method == 'POST':
data = json.loads(request.body.decode("utf8"))
query = data['chattext']
responses = Text.objects.filter(PlayerLine__contains=" %s "
% (query))
if len(responses) > 0:
return HttpResponse(responses[random.randint(0,
len(responses))])
else:
return HttpResponse("Get thee to a nunnery!")
All of this...