snto

Swedish National Test Organizer
git clone https://noxz.tech/git/snto.git
snto

commit: 1893326e2e091d17516dc7caf80f8864b65969ce
parent: 3417e539dfa27b6462f986960d2a853ef5cd3ae7
author: Chris Noxz <chris@noxz.tech>
date:   Tue, 5 Dec 2023 19:34:07 +0100
load images using GET instead of using data:image
Mserve.py62+++++++++++++++-----
1 file changed, 48 insertions(+), 14 deletions(-)
diff --git a/serve.py b/serve.py
@@ -52,10 +52,15 @@ html_default_task       = """
 		<h2>{tags}</h2>
 	</div>
 	<a href="{link}">
-		<img src="data:image/png;base64,{image}"/>
+		<img src="{image}"/>
 	</a>
 </div>
 """
+html_image              = """
+<div class="image">
+	<img src="{image}"/>
+</div>
+"""
 html_task               = """
 <div id="head" class="task">
 	<div class="task-head">
@@ -244,7 +249,7 @@ class DataManager:
 				ORDER BY idx
 				""", (task.id, ))
 			for row in cursor.fetchall():
-				task.append_image(row[3])
+				task.append_image(row[0])
 			cursor.close()
 		except sqlite3.Error as e:
 			print("Failed to read data:", e)
@@ -300,11 +305,36 @@ class DataManager:
 			if connection:
 				connection.close()
 
+	def select_image(imageid):
+		connection = None
+		image = None
+		try:
+			connection = sqlite3.connect(db_file)
+			cursor = connection.cursor()
+			cursor.execute("""
+				SELECT image
+				FROM image
+				WHERE id = ?
+				""", (imageid, ))
+			row = cursor.fetchone()
+			image = row[0] if row else None
+			cursor.close()
+
+		except sqlite3.Error as e:
+			print("Failed to read data:", e)
+		finally:
+			if connection:
+				connection.close()
+		return image
+
 
 class WebServer(BaseHTTPRequestHandler):
 	def do_HEADERS(self):
 		self.send_response(200)
-		self.send_header("Content-type", "text/html")
+		if self.path.startswith("/image"):
+			self.send_header("Content-type", "image/png")
+		else:
+			self.send_header("Content-type", "text/html")
 		self.end_headers()
 
 	def do_GET(self):
@@ -312,8 +342,8 @@ class WebServer(BaseHTTPRequestHandler):
 		self.wfile.write(bytes(html_body.format(
 			title = html_title,
 			style = css,
-			content = self.task_page()
-			          if self.path.startswith("/task")
+			content =      self.task_page()    if self.path.startswith("/task")
+			          else self.render_image() if self.path.startswith("/image")
 			          else self.default_page()
 		), "utf-8"))
 
@@ -357,11 +387,11 @@ class WebServer(BaseHTTPRequestHandler):
 		html = ""
 		for task in tasks:
 			html += html_default_task.format(
-				course = task.course,
+				course   = task.course,
 				semester = task.semester,
-				tags = ", ".join(task.tags),
-				link = "/task?id={taskid}".format(taskid = task.id),
-				image = base64.b64encode(task.images[0]).decode("ascii")
+				tags     = ", ".join(task.tags),
+				link     = "/task?id={taskid}".format(taskid = task.id),
+				image    = "/image?id={imageid}".format(imageid = task.images[0])
 			)
 		return html
 
@@ -395,13 +425,17 @@ class WebServer(BaseHTTPRequestHandler):
 			course      = task.course,
 			semester    = task.semester,
 			tags        = ", ".join(task.tags),
-			images      = "".join("""
-				<div class="image">
-					<img src="data:image/png;base64,%s"/>
-				</div>
-			""" % base64.b64encode(image).decode("ascii") for image in task.images)
+			images      = "".join(html_image.format(
+			                image = "/image?id=%s" % image
+			              ) for image in task.images)
 		) if task else "Error: task does not exist"
 
+	def render_image(self):
+		qs_raw      = parse_qs(urlparse(self.path).query)
+		image       = DataManager.select_image(qs_raw["id"][0] if "id" in qs_raw.keys() else "")
+
+		self.wfile.write(image if image else b"")
+
 
 if __name__ == "__main__":
 	webServer = HTTPServer((hostName, serverPort), WebServer)