import mariadb as mdb import json import os from test_list import TestList 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 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 == "test-list": cur.execute("SELECT id FROM test;") test_amount = len(list(cur)) header = f'

Всього тестів: {test_amount}

' subheader = f'
Створити тест' content = TestList(cur).render() elif mode == "create-test": header = f"

Створити новий тест" subheader = "Введіть властивості нового тесту нижче" content = f'''

''' else: header = f"

No such view mode: {mode}

" subheader = f'Повернутися на головну сторінку' content = "" dbc.close() return self.format_page(header, subheader, content)