test-platform/server/cgi/view.py

78 lines
2.5 KiB
Python
Raw Normal View History

2024-05-25 19:18:26 +03:00
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'<h2>Всього тестів: {test_amount}</h2>'
subheader = f'<input placeholder="Шукати тести"><br><a class="generic-button" href="?mode=create-test">Створити тест</a>'
content = TestList(cur).render()
elif mode == "create-test":
header = f"<h2>Створити новий тест"
subheader = "<i>Введіть властивості нового тесту нижче</i>"
content = f'''<form action="/create-test.py">
<label for="name">Назва тесту:</label><br>
<input type="text" name="name" placeholder="Введіть назву..." required>
<input type="submit" value="Створити">
</form>'''
else:
header = f"<h2>No such view mode: {mode}</h2>"
subheader = f'<a href="/index.py">Повернутися на головну сторінку</a>'
content = ""
dbc.close()
return self.format_page(header, subheader, content)