diff options
| author | Gustav Sörnäs <gusso230@student.liu.se> | 2020-11-20 14:56:20 +0100 |
|---|---|---|
| committer | Gustav Sörnäs <gusso230@student.liu.se> | 2020-11-20 14:56:20 +0100 |
| commit | 2b32ef6886f5df2f43c406ac7373af4b3551fd6b (patch) | |
| tree | 29a3243fb0974503a8623f228061f2909f4afbda | |
| parent | 10e3d6874745283b545d3b8029a3e5e184932c5d (diff) | |
| download | tdde25-2b32ef6886f5df2f43c406ac7373af4b3551fd6b.tar.gz | |
tracebacks in server code
Output both to the console and the response body.
Return correct status codes.
| -rw-r--r-- | lib.py | 46 |
1 files changed, 24 insertions, 22 deletions
@@ -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, "<code>\n{}\n</code>".format(tb.replace("\n", "<br>\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"<code>{tb}</code>" 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()) |
