add new webserver infrastructure

This commit is contained in:
Jakob Ketterl
2019-05-03 22:59:24 +02:00
parent 4e30fd57c0
commit bd8e665198
4 changed files with 111 additions and 27 deletions

43
owrx/controllers.py Normal file
View File

@ -0,0 +1,43 @@
import mimetypes
class Controller(object):
def __init__(self, handler, matches):
self.handler = handler
self.matches = matches
def send_response(self, content, code = 200, content_type = "text/html"):
self.handler.send_response(code)
if content_type is not None:
self.handler.send_header("Content-Type", content_type)
self.handler.end_headers()
if (type(content) == str):
content = content.encode()
self.handler.wfile.write(content)
def serve_file(self, file):
try:
f = open('htdocs/' + file, 'rb')
data = f.read()
f.close()
(content_type, encoding) = mimetypes.MimeTypes().guess_type(file)
self.send_response(data, content_type = content_type)
except FileNotFoundError:
self.send_response("file not found", code = 404)
def render_template(self, template, **variables):
f = open('htdocs/' + template)
data = f.read()
f.close()
self.send_response(data)
class StatusController(Controller):
def handle_request(self):
self.send_response("you have reached the status page!")
class IndexController(Controller):
def handle_request(self):
self.render_template("index.wrx")
class AssetsController(Controller):
def handle_request(self):
filename = self.matches.group(1)
self.serve_file(filename)

35
owrx/http.py Normal file
View File

@ -0,0 +1,35 @@
from owrx.controllers import StatusController, IndexController, AssetsController
from http.server import BaseHTTPRequestHandler
import re
class RequestHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
self.router = Router()
super().__init__(request, client_address, server)
def do_GET(self):
self.router.route(self)
class Router(object):
mappings = [
{"route": "/", "controller": IndexController},
{"route": "/status", "controller": StatusController},
{"regex": "/static/(.+)", "controller": AssetsController}
]
def find_controller(self, path):
for m in Router.mappings:
if "route" in m:
if m["route"] == path:
return (m["controller"], None)
if "regex" in m:
regex = re.compile(m["regex"])
matches = regex.match(path)
if matches:
return (m["controller"], matches)
def route(self, handler):
res = self.find_controller(handler.path)
#print("path: {0}, controller: {1}, matches: {2}".format(handler.path, controller, matches))
if res is not None:
(controller, matches) = res
controller(handler, matches).handle_request()
else:
handler.send_error(404, "Not Found", "The page you requested could not be found.")