ui.wsgi: Add a preliminary WSGI/HTML user interface
[quizzer.git] / quizzer / ui / __init__.py
1 # Copyright (C) 2013 W. Trevor King <wking@tremily.us>
2 #
3 # This file is part of quizzer.
4 #
5 # quizzer is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # quizzer is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # quizzer.  If not, see <http://www.gnu.org/licenses/>.
16
17 import importlib as _importlib
18
19 from .. import answerdb as _answerdb
20
21
22 INTERFACES = ['cli', 'wsgi']
23
24
25 class UserInterface (object):
26     "Give a quiz over a generic user interface"
27     def __init__(self, quiz=None, answers=None, stack=None):
28         self.quiz = quiz
29         if answers is None:
30             answers = _answerdb.AnswerDatabase()
31         self.answers = answers
32         if stack is None:
33             stack = self.answers.get_never_correctly_answered(
34                 questions=quiz.leaf_questions())
35         self.stack = stack
36
37     def run(self):
38         raise NotImplementedError()
39
40     def get_question(self):
41         if self.stack:
42             return self.stack.pop(0)
43
44     def process_answer(self, question, answer, **kwargs):
45         correct,details = question.check(answer=answer, **kwargs)
46         self.answers.add(question=question, answer=answer, correct=correct)
47         if not correct:
48             self.stack.insert(0, question)
49             for qid in reversed(question.dependencies):
50                 self.stack.insert(0, self.quiz.get(id=qid))
51         return (correct, details)
52
53
54 def get_ui(name):
55     """Get the UserInterface subclass from a UI submodule
56
57     >>> get_ui('cli')
58     <class 'quizzer.ui.cli.CommandLineInterface'>
59     """
60     module = _importlib.import_module('{}.{}'.format(__name__, name))
61     for name in dir(module):
62         obj = getattr(module, name)
63         try:
64             subclass = issubclass(obj, UserInterface)
65         except TypeError as e:  # obj is not a class
66             continue
67         if subclass:
68             return obj
69     raise ValueError(name)