From 2b32ef6886f5df2f43c406ac7373af4b3551fd6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Fri, 20 Nov 2020 14:56:20 +0100 Subject: tracebacks in server code Output both to the console and the response body. Return correct status codes. --- lib.py | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/lib.py b/lib.py index 3b19daa..e95265f 100644 --- a/lib.py +++ b/lib.py @@ -1,5 +1,7 @@ import os import re +import sys +import traceback from http.server import HTTPServer, BaseHTTPRequestHandler posts = {} @@ -10,22 +12,29 @@ def find_get(path): """ [Internal] - Used by the Handler class to try and find the correct handler for a GET request. """ + if path not in gets: + return 404, "" try: - return gets[path]() - except Exception as e: - print(type(e), e) - return "404" + return 200, gets[path]() + except Exception: + tb = traceback.format_exc() + print(tb, file=sys.stderr) + return 500, "\n{}\n".format(tb.replace("\n", "
\n") + .replace(" ", " ")) def find_post(path, request): """ [Internal] - Used by the Handler class to try and find the correct handler for a POST request. """ + if path not in posts: + return 404, "" try: - return posts[path](request) - except Exception as e: - print(type(e), e) - return "404" + return 200, posts[path](request) + except Exception: + tb = traceback.format_exc() + print(tb, file=sys.stderr) + return 500, f"{tb}" def get_relative_path(): @@ -106,21 +115,14 @@ class Handler(BaseHTTPRequestHandler): different requests made to our server. """ - def _set_headers(self): - """ Sets the headers for a response. This is to tell the browser - the status of the request that was sent. '200' means that everything - went fine. - """ - self.send_response(200) - self.send_header("Content-type", "text/html") - self.end_headers() - def do_GET(self): """ Tries to find the handler for this GET request. The handler can return either `bytes` or `str`. """ - self._set_headers() - res = find_get(self.path) + status, res = find_get(self.path) + self.send_response(status) + self.send_header("Content-type", "text/html") + self.end_headers() if hasattr(res, 'encode'): self.wfile.write(res.encode()) else: @@ -131,11 +133,11 @@ class Handler(BaseHTTPRequestHandler): will get the 'body' of the request as the argument. The body is a `str`, formatted in JSON. """ - self.send_response(200) - self.end_headers() content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) - res = find_post(self.path, body.decode('utf-8')) + status, res = find_post(self.path, body.decode('utf-8')) + self.send_response(status) + self.end_headers() self.wfile.write(res.encode()) -- cgit v1.2.1 From 4332e67fdc6aac0ba08379e3526c798454bf6fe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Fri, 20 Nov 2020 15:18:04 +0100 Subject: highlight traceback with pygments if available Install pygments via pip if you want to use the highlighter. --- lib.py | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/lib.py b/lib.py index e95265f..2ceb51d 100644 --- a/lib.py +++ b/lib.py @@ -4,10 +4,28 @@ import sys import traceback from http.server import HTTPServer, BaseHTTPRequestHandler +try: + from pygments import highlight + from pygments.lexers import PythonLexer + from pygments.formatters import HtmlFormatter + have_pygment = True +except ModuleNotFoundError: + have_pygment = False + posts = {} gets = {} +def format_py(code): + if have_pygment: + formatter = HtmlFormatter() + formatter.noclasses = True # inline styles + return highlight(code, PythonLexer(), formatter) + else: + return "{}".format(code).replace("\n", "\n
") \ + .replace(" ", " ") + + def find_get(path): """ [Internal] - Used by the Handler class to try and find the correct handler for a GET request. @@ -19,8 +37,7 @@ def find_get(path): except Exception: tb = traceback.format_exc() print(tb, file=sys.stderr) - return 500, "\n{}\n".format(tb.replace("\n", "
\n") - .replace(" ", " ")) + return 500, format_py(tb) def find_post(path, request): @@ -34,7 +51,7 @@ def find_post(path, request): except Exception: tb = traceback.format_exc() print(tb, file=sys.stderr) - return 500, f"{tb}" + return 500, "" def get_relative_path(): @@ -59,7 +76,7 @@ def read_html(relative_file_path): def inject_external_files(html_content): """ [Internal] - Replaces {{ 'file_path' }} with the file content of that file - path. Useful for seperation of javascript and css files. + pat. Useful for seperation of javascript and css files. Uses regex to capture the pattern. Here is a link to see how it works: https://regex101.com/r/v917NK/2 """ -- cgit v1.2.1