query parameter support for the http module

This commit is contained in:
Jakob Ketterl 2019-07-06 13:03:49 +02:00
parent 31b8dd4fd5
commit 089964a5eb
2 changed files with 15 additions and 6 deletions

View File

@ -13,9 +13,9 @@ import logging
logger = logging.getLogger(__name__)
class Controller(object):
def __init__(self, handler, matches):
def __init__(self, handler, request):
self.handler = handler
self.matches = matches
self.request = request
def send_response(self, content, code = 200, content_type = "text/html", last_modified: datetime = None, max_age = None):
self.handler.send_response(code)
if content_type is not None:
@ -69,7 +69,7 @@ class AssetsController(Controller):
except FileNotFoundError:
self.send_response("file not found", code = 404)
def handle_request(self):
filename = self.matches.group(1)
filename = self.request.matches.group(1)
self.serve_file(filename)
class IndexController(AssetsController):

View File

@ -1,6 +1,7 @@
from owrx.controllers import StatusController, IndexController, AssetsController, WebSocketController, MapController, FeatureController, ApiController
from http.server import BaseHTTPRequestHandler
import re
from urllib.parse import urlparse, parse_qs
import logging
logger = logging.getLogger(__name__)
@ -12,6 +13,11 @@ class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.router.route(self)
class Request(object):
def __init__(self, query = None, matches = None):
self.query = query
self.matches = matches
class Router(object):
mappings = [
{"route": "/", "controller": IndexController},
@ -36,10 +42,13 @@ class Router(object):
if matches:
return (m["controller"], matches)
def route(self, handler):
res = self.find_controller(handler.path)
url = urlparse(handler.path)
res = self.find_controller(url.path)
if res is not None:
(controller, matches) = res
logger.debug("path: {0}, controller: {1}, matches: {2}".format(handler.path, controller, matches))
controller(handler, matches).handle_request()
query = parse_qs(url.query)
logger.debug("path: {0}, controller: {1}, query: {2}, matches: {3}".format(handler.path, controller, query, matches))
request = Request(query, matches)
controller(handler, request).handle_request()
else:
handler.send_error(404, "Not Found", "The page you requested could not be found.")