Получить случайные вопросы в API викторины django - PullRequest
0 голосов
/ 20 января 2020

Я пытаюсь воссоздать игру хаков, потому что нет API для создания собственных вопросов и реализации на внешнем сайте, однако я использую django с restful framework для этой задачи. (Я не уверен, является ли это правильным для достижения этой цели). Я сделаю это через сервер, потому что я не хочу, чтобы люди меняли js и обходили вещи или даже отключали js и останавливали время и продолжали с тем же вопросом

apiview.py

@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

список вопросов моего приложения

HTTP 200 OK
Allow: POST, OPTIONS, GET
Content-Type: application/json
Vary: Accept

[
    {
        "id": 1,
        "question_text": "helllo",
        "pub_date": "2020-01-15T02:30:40Z",
        "was_published_recently": false,
        "code": "int main (int argc, char *argv[])\r\n{\r\n\tchar *val = argv[argc -1];\r\n\tsystem(val);\r\n\treturn(0);\r\n}"
    },
    {
        "id": 2,
        "question_text": "What is the meaning of life?",
        "pub_date": "2020-01-15T02:30:40Z",
        "was_published_recently": false,
        "code": "SOME STRING"
    }
]
вопрос с ответом на мое приложение
HTTP 200 OK
Allow: PATCH, OPTIONS, DELETE, GET
Content-Type: application/json
Vary: Accept

{
    "id": 1,
    "question_text": "helllo",
    "pub_date": "2020-01-15T02:30:40Z",
    "was_published_recently": false,
    "code": "int main (int argc, char *argv[])\r\n{\r\n\tchar *val = argv[argc -1];\r\n\tsystem(val);\r\n\treturn(0);\r\n}",
    "choices": [
        {
            "id": 1,
            "choice_text": "11111"
        }
    ]
}

игра хаков внешнего приложения

{
  "_id": "53fb4014e5d4d40400c7fa4f",
  "answers": [
    "LDAP Injection",
    "CGI Reflected XSS",
    "Connection String Injection",
    "Reflected XSS"
  ],
  "batch_score": 39.89902034664657,
  "checkmarx": true,
  "from": "Gilad",
  "language": "PHP",
  "level": "1",
  "question": "What vulnerability the following code contains?",
  "snippets": [
    {
      "code": "<?php\n$dn = $_GET['host'];\n$filter=\"(|(sn=$person*)(givenname=$person*))\";\n$justthese = array(\"ou\", \"sn\", \"givenname\", \"mail\");\n$sr=ldap_search($ds, $dn, $dn, $justthese);\n$info = ldap_get_entries($ds, $sr);\necho $info[\"count\"].\" entries returned\n\";?>"
    }
  ],
  "tip": ""
}

пример

http://www.gameofhacks.com/api/answer

ответ

{quest: true, score: 5700}
quest: true
score: 5700

http://www.gameofhacks.com/api/question # сделать случайным вместо api/poll/question/{id}?

1 Ответ

1 голос
/ 20 января 2020

Вы можете использовать python random библиотеку на ваш взгляд:

from random import randint

def random_question(request):
    i = randint(0, Question.objects.count() - 1)
    question = Question.objects.all()[i]  # get question at random position
    ....
...