diff options
| author | UltraQbik <no1skill@yandex.ru> | 2024-08-27 02:03:45 +0300 |
|---|---|---|
| committer | UltraQbik <no1skill@yandex.ru> | 2024-08-27 02:03:45 +0300 |
| commit | 59cf36f6c568f0cbec319929460f769211b74430 (patch) | |
| tree | 982b61a03cfb9959d49f53da68c647588bfc1fbe | |
| parent | 817b9b5131f665390e8340941817169b0615f441 (diff) | |
| download | httpy-59cf36f6c568f0cbec319929460f769211b74430.tar.gz httpy-59cf36f6c568f0cbec319929460f769211b74430.zip | |
Update to work with new path map
| -rw-r--r-- | .gitignore | 2 | ||||
| -rw-r--r-- | main.py | 37 | ||||
| -rw-r--r-- | src/config.py | 19 | ||||
| -rw-r--r-- | src/file_man.py | 14 |
4 files changed, 44 insertions, 28 deletions
diff --git a/.gitignore b/.gitignore index bf503f9..30a88c1 100644 --- a/.gitignore +++ b/.gitignore @@ -165,3 +165,5 @@ cython_debug/ /www/yes.txt /www/images/ /compress/ +/fullchain.pem +/privkey.pem diff --git a/main.py b/main.py index 88674af..c350238 100644 --- a/main.py +++ b/main.py @@ -8,6 +8,8 @@ import time import socket import signal import threading +import traceback + from src import APIv1 from src.config import * from src.request import * @@ -30,17 +32,23 @@ class HTTPServer: *, port: int, enable_ssl: bool = True, - path_map: dict[str, dict] | None = None + path_map: dict[str, dict] | None = None, + key_pair: tuple[str, str] | None = None ): + """ + :param port: binding port + :param enable_ssl: use https + :param path_map: path map + :param key_pair: fullchain.pem + privkey.pem + """ + # Sockets sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if enable_ssl: # SSL context context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.check_hostname = False - context.load_cert_chain( - certfile=r"C:\Certbot\live\qubane.ddns.net\fullchain.pem", # use your own path here - keyfile=r"C:\Certbot\live\qubane.ddns.net\privkey.pem") # here too + context.load_cert_chain(certfile=key_pair[0], keyfile=key_pair[1]) self.sock: usocket = context.wrap_socket(sock, server_side=True) else: self.sock: usocket = sock @@ -107,8 +115,8 @@ class HTTPServer: pass except OSError as e: print(f"Request dropped due to: {e}") - except Exception as e: - print(e) + except Exception: + print("Ignoring exception:\n", traceback.format_exc()) # Remove self from thread list and close the connection self.client_threads.remove(threading.current_thread()) @@ -141,6 +149,8 @@ class HTTPServer: # send message client.sendall(message) for packet in response.get_data_stream(): + if packet is None: + break client.sendall(packet) # check for stop event @@ -154,10 +164,9 @@ class HTTPServer: split_path = request.path.split("/", maxsplit=16)[1:] if request.path in self.path_map: # assume browser - filepath = self.path_map[request.path]["path"] - filedata = self.fetch_file(filepath) - headers = self.fetch_file_headers(filepath) - response = Response(b'', STATUS_CODE_OK, data_stream=filedata, headers=headers) + filedata = self.fetch_file(request.path) + headers = self.fetch_file_headers(request.path) + response = Response(b'', STATUS_CODE_OK, headers, data_stream=filedata) return response elif len(split_path) >= 2 and split_path[0] in API_VERSIONS: # assume script @@ -231,14 +240,14 @@ class HTTPServer: """ if path in self.path_map: - filepath = self.path_map[path]["path"] - with open(filepath, "rb") as file: - yield file.read(BUFFER_LENGTH) + with open(self.path_map[path]["path"], "rb") as file: + while (msg := file.read(BUFFER_LENGTH)): + yield msg yield None def main(): - server = HTTPServer(port=13700, enable_ssl=False) + server = HTTPServer(port=13700, key_pair=("fullchain.pem", "privkey.pem"), enable_ssl=False) server.start() diff --git a/src/config.py b/src/config.py index 5720221..934bafe 100644 --- a/src/config.py +++ b/src/config.py @@ -13,15 +13,16 @@ API_VERSIONS = { # file manager FILE_MAN_VERBOSE = True +FILE_MAN_COMPRESS = True # do compress all files FILE_MAN_PATH_MAP = { # external - "/": {"path": "www/index.html"}, - "/about": {"path": "www/about.html"}, - "/testing": {"path": "www/testing.html"}, - "/projects": {"path": "www/projects.html"}, - "/images/*": {"path": "www/images/*"}, - "/scripts/*": {"path": "www/scripts/*"}, - "/robots.txt": {"path": "www/robots.txt"}, - "/favicon.ico": {"path": "www/favicon.ico"}, - "/css/styles.css": {"path": "www/css/styles.css"}, + "/": {"path": "www/index.html", "compress": True}, + "/about": {"path": "www/about.html", "compress": True}, + "/testing": {"path": "www/testing.html", "compress": True}, + "/projects": {"path": "www/projects.html", "compress": True}, + "/images/*": {"path": "www/images/*", "compress": False}, + "/scripts/*": {"path": "www/scripts/*", "compress": True}, + "/robots.txt": {"path": "www/robots.txt", "compress": False}, + "/favicon.ico": {"path": "www/favicon.ico", "compress": True}, + "/css/styles.css": {"path": "www/css/styles.css", "compress": True}, } diff --git a/src/file_man.py b/src/file_man.py index 58b4015..3371dd2 100644 --- a/src/file_man.py +++ b/src/file_man.py @@ -28,9 +28,13 @@ def generate_path_map() -> dict[str, dict[str, Any]]: keypath = FILE_MAN_PATH_MAP[key]["path"][:-2] for path in list_path(keypath): webpath = f"{key[:-1]}{path.replace(keypath+'/', '')}" - path_map[webpath] = {"path": path} + path_map[webpath] = { + "path": path, + "compress": FILE_MAN_PATH_MAP[key]["compress"]} else: - path_map[key] = {"path": FILE_MAN_PATH_MAP[key]["path"]} + path_map[key] = { + "path": FILE_MAN_PATH_MAP[key]["path"], + "compress": FILE_MAN_PATH_MAP[key]["compress"]} # add headers for val in path_map.values(): @@ -48,13 +52,13 @@ def generate_path_map() -> dict[str, dict[str, Any]]: case ".png": headers["Content-Type"] = "image/png" case ".webp": - headers["Content-Type"] = "image/avif" + headers["Content-Type"] = "image/webp" case ".jpg" | ".jpeg": headers["Content-Type"] = "image/jpeg" case _: headers["Content-Type"] = "*/*" - val["headers"] = headers headers["Content-Length"] = os.path.getsize(val["path"]) + val["headers"] = headers # print list of paths if FILE_MAN_VERBOSE: @@ -81,7 +85,7 @@ def compress_path_map(path_map: dict[str, dict[str, Any]], path_prefix: str = "c os.mkdir(path_prefix) for val in path_map.values(): filepath = f"{path_prefix}/{val["path"]}" - if val["headers"]["Content-Type"].split("/")[0] == "image": # ignore images + if not val["compress"]: continue if not os.path.exists((dirs := os.path.dirname(filepath))): # add missing folders os.makedirs(dirs) |