Skip to content

Commit

Permalink
feat(quiz): create quiz paper
Browse files Browse the repository at this point in the history
  • Loading branch information
CapooL committed Oct 19, 2023
1 parent 9575dbb commit 33d55c9
Show file tree
Hide file tree
Showing 12 changed files with 219 additions and 3 deletions.
1 change: 1 addition & 0 deletions hinghwa-dict-backend/quiz/dto/quiz_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ def quiz_all(quiz: Quiz) -> dict:
"explanation": quiz.explanation,
"voice_source": quiz.voice_source,
"visibility": quiz.visibility,
"type": quiz.type,
}
return response
83 changes: 83 additions & 0 deletions hinghwa-dict-backend/quiz/migrations/0004_auto_20231019_1116.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Generated by Django 3.1.14 on 2023-10-19 03:16

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("quiz", "0003_quiz_voice_source"),
]

operations = [
migrations.CreateModel(
name="Paper",
fields=[
(
"title",
models.CharField(blank=True, max_length=50, verbose_name="试卷标题"),
),
("quantity", models.IntegerField(blank=True, verbose_name="题目数量")),
(
"id",
models.CharField(
max_length=20,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
],
),
migrations.AddField(
model_name="quiz",
name="type",
field=models.CharField(blank=True, max_length=50, verbose_name="问题类型"),
),
migrations.CreateModel(
name="Record",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("timestamp", models.DateTimeField(blank=True, verbose_name="时间")),
(
"correct_answer",
models.IntegerField(blank=True, verbose_name="答对数量"),
),
(
"exam",
models.ManyToManyField(
related_name="exam_record", to="quiz.Paper", verbose_name="答卷记录"
),
),
(
"user_answer",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="user",
to=settings.AUTH_USER_MODEL,
verbose_name="词单作者",
),
),
],
),
migrations.AddField(
model_name="paper",
name="quizzes",
field=models.ManyToManyField(
blank=True,
related_name="exam_questions",
to="quiz.Quiz",
verbose_name="问题列表",
),
),
]
21 changes: 21 additions & 0 deletions hinghwa-dict-backend/quiz/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class Quiz(models.Model):
explanation = models.TextField(verbose_name="答案解析")
visibility = models.BooleanField(default=False, verbose_name="是否审核")
voice_source = models.URLField(max_length=200, verbose_name="播报语音链接", default="")
type = models.CharField(blank=True, max_length=50, verbose_name="问题类型")

def __str__(self):
return self.question
Expand All @@ -37,3 +38,23 @@ def save(self, *args, **kwargs):
class Meta:
verbose_name_plural = "测试题"
verbose_name = "测试题"


class Paper(models.Model):
title = models.CharField(blank=True, max_length=50, verbose_name="试卷标题")
quizzes = models.ManyToManyField(
Quiz, related_name="exam_questions", verbose_name="问题列表", blank=True
)
quantity = models.IntegerField(blank=True, verbose_name="题目数量")
id = models.CharField(max_length=20, verbose_name="ID", primary_key=True)


class Record(models.Model):
timestamp = models.DateTimeField(blank=True, verbose_name="时间")
correct_answer = models.IntegerField(blank=True, verbose_name="答对数量")
user_answer = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="user", verbose_name="词单作者"
)
exam = models.ManyToManyField(
Paper, related_name="exam_record", verbose_name="答卷记录"
)
16 changes: 16 additions & 0 deletions hinghwa-dict-backend/quiz/paper/dto/paper_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from ...models import Quiz, Paper, Record
from .record_all import record_all
from quiz.dto.quiz_all import quiz_all


# 返回问卷信息
def paper_all(paper: Paper):
response = {
"id": paper.id,
"title": paper.title,
"quantity": paper.quantity,
# "record": [record_all(x) for x in paper.record.all()]
"quizzes": [quiz_all(quiz) for quiz in paper.quizzes.all()],
}

return response
6 changes: 6 additions & 0 deletions hinghwa-dict-backend/quiz/paper/dto/record_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from ...models import Record


def record_all(record: Record):
response = {"timestamp": record.timestamp, "correct_answer": record.correct_answer}
return response
43 changes: 43 additions & 0 deletions hinghwa-dict-backend/quiz/paper/view/manage_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from django.http import JsonResponse
import demjson
from ..dto.paper_all import paper_all
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from ...models import Quiz, Paper, Record
from utils.exception.types.bad_request import InsufficientQuiz
from utils.token import token_pass, token_user
from django.utils import timezone
from utils.generate_id import generate_paper_id


class ManageAllPaper(View):
# QZ0203 测试题组卷
@csrf_exempt
def post(self, request):
token_pass(request.headers, -1)
number = int(request.GET["number"])
body = demjson.decode(request.body)
title = body["title"]
request_type = request.GET["type"]
type_list = request_type.split(",")
quizzes = Quiz.objects.filter(type__in=type_list).order_by("?")[:number]
if len(quizzes) != number:
raise InsufficientQuiz()
paper = Paper()
paper.quantity = number
paper.id = generate_paper_id()
paper.title = title
paper.save()
for quiz in quizzes:
paper.quizzes.add(quiz)
return JsonResponse(paper_all(paper), status=200)

# QZ0204 查询所有试卷
@csrf_exempt
def get(self, request):
# token_pass(request.headers, -1)
total_papers = Paper.objects.all()
result = []
for paper in total_papers:
result.append(paper_all(paper))
return JsonResponse({"total": len(result), "paper": result})
19 changes: 19 additions & 0 deletions hinghwa-dict-backend/quiz/paper/view/manage_single.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import demjson
from django.http import JsonResponse
from ..dto.paper_all import paper_all
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from ...models import Quiz, Paper, Record
from utils.exception.types.bad_request import InsufficientQuiz
from utils.exception.types.not_found import PaperNotFoundException


class ManageSinglePaper(View):
# QZ0205 查询特定试卷
@csrf_exempt
def get(self, request, paper_id) -> JsonResponse:
paper = Paper.objects.filter(id=paper_id)
if not paper.exists():
raise PaperNotFoundException()
paper = paper[0]
return JsonResponse(paper_all(paper), status=200)
6 changes: 4 additions & 2 deletions hinghwa-dict-backend/quiz/urls.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.urls import path

from .paper.view.manage_all import *
from .paper.view.manage_single import *
from .views import *

app_name = "users"
Expand All @@ -9,5 +10,6 @@
path("/<int:id>", csrf_exempt(SingleQuiz.as_view())), # QZ0101 QZ0103 QZ0104
path("/<int:id>/visibility", csrf_exempt(ManageVisibility.as_view())), # QZ0105
path("/random", csrf_exempt(RandomQuiz.as_view())), # QZ0202
path("/paper", csrf_exempt(QuizPaper.as_view())), # QZ0203
path("/paper", csrf_exempt(ManageAllPaper.as_view())), # QZ0203
path("/paper/<str:paper_id>", csrf_exempt(ManageSinglePaper.as_view())),
]
2 changes: 2 additions & 0 deletions hinghwa-dict-backend/quiz/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ def post(self, request) -> JsonResponse:
if not quiz_form.is_valid():
raise BadRequestException()
quiz = quiz_form.save(commit=False)
type_name = body["type"]
quiz.type = type_name
quiz.author = user
quiz.save()
return JsonResponse({"quiz": quiz_all(quiz)}, status=200)
Expand Down
14 changes: 13 additions & 1 deletion hinghwa-dict-backend/utils/exception/types/not_found.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,22 @@ def __init__(self, id=""):
class PronunciationNotFoundException(NotFoundException):
"""
语音条不存在异常
parma id:语音id
parma id:语音id
"""

def __init__(self, id=""):
super().__init__()
self.status = 404
self.msg = "语音{}不存在!".format(id)


class PaperNotFoundException(NotFoundException):
"""
试卷不存在异常
parma id:试卷id
"""

def __init__(self, id=""):
super().__init__()
self.status = 404
self.msg = "试卷{}不存在!".format(id)
11 changes: 11 additions & 0 deletions hinghwa-dict-backend/utils/generate_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from rewards.products.models.product import Product
from rewards.orders.models.order import Order
from word.models import List
from quiz.models import Paper


def generate_transaction_id():
Expand Down Expand Up @@ -53,3 +54,13 @@ def generate_list_id():
else:
new_id = 1
return f"CD{new_id:06d}"


def generate_paper_id():
last_paper = Paper.objects.order_by("-id").first()
if last_paper:
last_id = int(last_paper.id[2:])
new_id = last_id + 1
else:
new_id = 1
return f"SJ{new_id:06d}"

0 comments on commit 33d55c9

Please sign in to comment.