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(-) (limited to 'lib.py') 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