diff options
Diffstat (limited to 'lib.py')
| -rw-r--r-- | lib.py | 77 |
1 files changed, 48 insertions, 29 deletions
@@ -1,31 +1,57 @@ import os import re +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 "<code>{}</code>".format(code).replace("\n", "\n<br>") \ + .replace(" ", " ") + + 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, format_py(tb) 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, "" def get_relative_path(): @@ -35,7 +61,7 @@ def get_relative_path(): def read_html(relative_file_path): """ Reads the html file on the file location provided and injects any external files (marked with {{file_path}} ) - that may be present. Returns the html content as a string. + that may be present. Returns the html content as a string. Example: >>> html_string = read_html('templates/index.html') @@ -49,8 +75,8 @@ 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. + """ [Internal] - Replaces {{ 'file_path' }} with the file content of that file + 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 """ @@ -76,8 +102,8 @@ def inject_external_files(html_content): def post(route='/'): """ A decorator that takes in the route path as argument, and then - puts the post handler in the dictionary, with the route as a key. - The handler will receive one `str` argument called 'body', + puts the post handler in the dictionary, with the route as a key. + The handler will receive one `str` argument called 'body', where the body of the post request will exist. """ def decorator(handler_function): @@ -106,21 +132,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`. + 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 +150,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()) @@ -143,4 +162,4 @@ def run_server(port=8314): server_address = ('127.0.0.1', port) # Should make the port a command line argument server = HTTPServer(server_address, Handler) print('Starting server on http://{}:{}.'.format(*server_address)) - server.serve_forever() + server.serve_forever()
\ No newline at end of file |
