From 5fe71ea7b9d9a5d2dc6e8e5ce5b9193629eed74d Mon Sep 17 00:00:00 2001 From: Terry Truong Date: Mon, 11 Jul 2022 01:54:08 +1000 Subject: Make backend dev server script serve the image files Previously, image files in backend/data/img were moved to, or symlinked from, public/. This needed to be changed before each build, otherwise vite would end up copying gigabytes of images. --- backend/server.py | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) (limited to 'backend/server.py') diff --git a/backend/server.py b/backend/server.py index a00ab7f..5e0b80f 100755 --- a/backend/server.py +++ b/backend/server.py @@ -1,18 +1,38 @@ #!/usr/bin/python3 -import sys -from wsgiref.simple_server import make_server +import sys, os +from wsgiref import simple_server, util +import mimetypes from tilo import application usageInfo = f""" Usage: {sys.argv[0]} -Runs a basic dev server that serves a WSGI script +Runs a basic dev server that serves a WSGI script and image files """ if len(sys.argv) > 1: print(usageInfo, file=sys.stderr) sys.exit(1) -with make_server('', 8000, application) as httpd: +def wrappingApp(environ, start_response): + urlPath = environ["PATH_INFO"] + if urlPath.startswith("/data/"): + # Run WSGI script + return application(environ, start_response) + elif urlPath.startswith("/tolData/img/"): + # Serve image file + imgPath = os.path.join(os.getcwd(), urlPath[1:]) + if os.path.exists(imgPath): + imgType = mimetypes.guess_type(imgPath)[0] + start_response("200 OK", [("Content-type", imgType)]) + return util.FileWrapper(open(imgPath, "rb")) + else: + start_response("404 Not Found", [("Content-type", "text/plain")]) + return [b"No image found"] + else: + start_response("404 Not Found", [("Content-type", "text/plain")]) + return [b"Unrecognised path"] + +with simple_server.make_server('', 8000, wrappingApp) as httpd: print("Serving HTTP on port 8000...") httpd.serve_forever() -- cgit v1.2.3