2022-07-26 10:07:31 +00:00
|
|
|
from typing import List
|
|
|
|
|
|
|
|
import ujson
|
|
|
|
|
2022-08-05 11:14:29 +00:00
|
|
|
from .cache import QuizCache
|
2022-08-23 09:17:54 +00:00
|
|
|
from .models import Question, Answer
|
2022-08-05 11:14:29 +00:00
|
|
|
from .repositories import QuizRepository
|
2022-07-26 10:07:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
class QuizService:
|
|
|
|
def __init__(self, repository: QuizRepository, cache: QuizCache):
|
|
|
|
self._repository = repository
|
|
|
|
self._cache = cache
|
|
|
|
|
2022-08-23 09:17:54 +00:00
|
|
|
async def get_quiz_form_database(self) -> List[Question]:
|
2022-07-26 10:07:31 +00:00
|
|
|
"""从数据库获取问题列表
|
2022-08-23 09:17:54 +00:00
|
|
|
:return: Question List
|
2022-07-26 10:07:31 +00:00
|
|
|
"""
|
2022-08-23 09:17:54 +00:00
|
|
|
temp: list = []
|
2022-07-26 10:07:31 +00:00
|
|
|
question_list = await self._repository.get_question_list()
|
|
|
|
for question in question_list:
|
2022-08-23 09:17:54 +00:00
|
|
|
question_id = question.id
|
|
|
|
answers = await self._repository.get_answers_form_question_id(question_id)
|
2022-07-26 10:07:31 +00:00
|
|
|
question.answers = answers
|
2022-08-23 09:17:54 +00:00
|
|
|
data = Question.de_database_data(question)
|
|
|
|
data.answers = [Answer.de_database_data(a) for a in answers]
|
|
|
|
temp.append(data)
|
|
|
|
return temp
|
2022-07-26 10:07:31 +00:00
|
|
|
|
|
|
|
async def save_quiz(self, data: Question):
|
2022-08-23 09:17:54 +00:00
|
|
|
await self._repository.get_question_by_text(data.text)
|
2022-07-26 10:07:31 +00:00
|
|
|
for answers in data.answers:
|
2022-08-23 09:17:54 +00:00
|
|
|
await self._repository.add_answer(answers.to_database_data())
|
2022-07-26 10:07:31 +00:00
|
|
|
|
|
|
|
async def refresh_quiz(self) -> int:
|
2022-08-23 09:17:54 +00:00
|
|
|
question_list = await self.get_quiz_form_database()
|
2022-07-26 10:07:31 +00:00
|
|
|
await self._cache.del_all_question()
|
|
|
|
question_count = await self._cache.add_question(question_list)
|
|
|
|
await self._cache.del_all_answer()
|
|
|
|
for question in question_list:
|
|
|
|
await self._cache.add_answer(question.answers)
|
|
|
|
return question_count
|
|
|
|
|
|
|
|
async def get_question_id_list(self) -> List[int]:
|
|
|
|
return [int(question_id) for question_id in await self._cache.get_all_question_id_list()]
|
|
|
|
|
|
|
|
async def get_answer(self, answer_id: int):
|
|
|
|
data = await self._cache.get_one_answer(answer_id)
|
|
|
|
return ujson.loads(data)
|
|
|
|
|
|
|
|
async def get_question(self, question_id: int) -> Question:
|
|
|
|
return await self._cache.get_one_question(question_id)
|