import mariadb as mdb
import json
import os
from test_list import TestList
from question_list import QuestionList
from response_option_list import ResponseOptionList
from httputils import escape_html
def readfile(path):
if os.path.exists(path):
return open(path).read()
class View:
def __init__(self, query_args, connector_data = {}):
self.args = query_args
self.connector_data = connector_data
self.db_connection = None
self.supported_modes = {
"test-list": self.render_test_list,
"create-test": self.render_create_test,
"view-test": self.render_view_test,
"create-question": self.render_create_question,
"edit-question": self.render_edit_question,
"view-question": self.render_view_question,
"create-response-option": self.render_create_response_option,
}
def get_db_connection(self):
if not self.db_connection:
args = {"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password": "",
"database": "test_holder"}
settings = json.loads(readfile("cgi/db-settings.json"))
args.update(settings)
args.update(self.connector_data)
self.db_connection = mdb.connect(**args)
return self.db_connection
def format_page(self, header, subheader, content):
base_layout = readfile("html/base_layout.html")
base_layout = base_layout.replace("%HEADER%", header)
base_layout = base_layout.replace("%SUBHEADER%", subheader)
base_layout = base_layout.replace("%CONTENT%", content)
return base_layout
def render_page(self):
dbc = self.get_db_connection()
cur = dbc.cursor()
if 'mode' in self.args:
mode = self.args['mode']
else:
mode = "test-list"
if mode not in self.supported_modes:
header = f"
No such view mode: {mode}
"
subheader = f'Повернутися на головну сторінку'
content = ""
else:
header, subheader, content = self.supported_modes[mode](cur)
dbc.close()
return self.format_page(header, subheader, content)
def render_test_list(self, cur):
cur.execute("SELECT id FROM test;")
test_amount = len(list(cur))
header = f'
Всього тестів: {test_amount}
'
subheader = f' Створити новий тест'
content = TestList(cur).render()
return header, subheader, content
def render_create_test(self, cur):
header = f"
Створити новий тест
"
subheader = "Введіть властивості нового тесту нижче"
content = f''''''
return header, subheader, content
def render_view_test(self, cur):
cur.execute(f"SELECT name FROM test WHERE id = {self.args['id']};")
test_name = next(iter(cur), [None])[0]
if not test_name:
header = f"
"
subheader = "Відредагуйте властивості запитання нижче"
content = f''''''
return header, subheader, content
def render_view_question(self, cur):
cur.execute(f"SELECT title FROM question WHERE id = {self.args['id']};")
question_name = next(iter(cur), [None])[0]
if not question_name:
header = f"