From 30879149f544a6cb1ebbeb3c27c467c479d0d448 Mon Sep 17 00:00:00 2001 From: jullinator Date: Fri, 17 Aug 2018 23:56:49 +0200 Subject: first draft --- lib.py | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 lib.py (limited to 'lib.py') diff --git a/lib.py b/lib.py new file mode 100644 index 0000000..66d2ccd --- /dev/null +++ b/lib.py @@ -0,0 +1,78 @@ +import os +import io +import re + + +posts = {} +gets = {} + +def find_get(path): + try: + return gets[path]() + except KeyError: + return "404" + + +def find_post(path, request): + try: + return posts[path](request) + except KeyError: + return "404" + +def get_relative_path(): + return os.path.dirname(os.path.abspath(__file__)) + + +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. """ + dir_path = get_relative_path() + file_path = os.path.join(dir_path, relative_file_path) + with open(file_path) as file: + html_content = file.read() + html_content = inject_external_files(html_content) + return html_content + +def inject_external_files(html_content): + """ Replaces {{ 'file_path' }} with the file content of that + file path. Useful for seperation of javascript and css files.""" + + pattern = r'{{([^<]+)}}' + external_files = re.findall(pattern, html_content) + new_html_content = html_content + for match in external_files: + external_file_path = match.replace(' ', '') + external_file = open(os.path.join(get_relative_path(), external_file_path)) + file_content = external_file.read() + external_file.close() + + if match.find('.css') != -1: + file_content = '' + elif match.find('.js') != -1: + file_content = '' + + to_be_replaced = '{{' + match + '}}' + new_html_content = new_html_content.replace(to_be_replaced, file_content) + return new_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. """ + + def decorator(handler_function): + posts[route] = handler_function + return handler_function + + return decorator + +def get(route = '/'): + """ A decorator that takes in the route path as argument, and then + puts the get handler in the dictionary, with the route as a key. """ + + def decorator(handler_function): + gets[route] = handler_function + return handler_function + + return decorator \ No newline at end of file -- cgit v1.2.1