diff options
| author | Gustav Sörnäs <gusso230@student.liu.se> | 2020-11-20 15:18:04 +0100 |
|---|---|---|
| committer | Gustav Sörnäs <gusso230@student.liu.se> | 2020-11-20 15:18:04 +0100 |
| commit | 4332e67fdc6aac0ba08379e3526c798454bf6fe0 (patch) | |
| tree | 2d2ceff53ab7d4a9444e414e4ab45f458f61d895 | |
| parent | 2b32ef6886f5df2f43c406ac7373af4b3551fd6b (diff) | |
| download | tdde25-4332e67fdc6aac0ba08379e3526c798454bf6fe0.tar.gz | |
highlight traceback with pygments if available
Install pygments via pip if you want to use the highlighter.
| -rw-r--r-- | lib.py | 25 |
1 files changed, 21 insertions, 4 deletions
@@ -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 "<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. @@ -19,8 +37,7 @@ def find_get(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(" ", " ")) + 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"<code>{tb}</code>" + 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 """ |
