Я пытаюсь воссоздать игру хаков, потому что нет API для создания моих собственных вопросов и реализации на внешнем сайте, однако я использую django с restful framework для этой задачи. (Я не уверен, является ли это правильным для достижения этой цели). Я сделаю это через сервер, потому что я не хочу, чтобы люди меняли js и обходили вещи или даже отключали js и останавливали время, и продолжали с тем же вопросом, но как я могу перевести на django это?
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Question, Choice
from .serializers import QuestionListPageSerializer, QuestionDetailPageSerializer, ChoiceSerializer, VoteSerializer, QuestionResultPageSerializer
@api_view(['GET', 'POST'])
def questions_view(request):
if request.method == 'GET':
questions = Question.objects.all()
serializer = QuestionListPageSerializer(questions, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = QuestionListPageSerializer(data=request.data)
if serializer.is_valid():
question = serializer.save()
return Response(QuestionListPageSerializer(question).data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class QuestionListPageSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
question_text = serializers.CharField(max_length=200)
pub_date = serializers.DateTimeField()
was_published_recently = serializers.BooleanField(read_only=True) # Serializer is smart enough to understand that was_published_recently is a method on Question
code = serializers.CharField(max_length=200)
def create(self, validated_data):
return Question.objects.create(**validated_data)
def update(self, instance, validated_data):
for key, value in validated_data.items():
setattr(instance, key, value)
instance.save()
return instance
python контрольный пример
import random
import pprint
def pick_ten(fname):
question_list = []
for question in open(fname):
# strip off new line character
question = question.rstrip()
question_list.append(question)
return random.sample(question_list, 1)
# testing ...
filename = "Questions101.txt"
question_list = pick_ten(filename)
pprint.pprint(question_list)
ответный контрольный пример
xxxxxx@xxxxxx:~$ python3 quiz.py
['What was the first brand name for Bubble Gum?']
xxxxxx@xxxxxx:~$ python3 quiz.py
['Which game uses the phrase "en passant"?']
xxxxxx@xxxxxx:~$ python3 quiz.py
['What type of organism causes malaria?']
xxxxxx@xxxxxx:~$