From d14bd2151f597ec3b8a7e9382d4a482b74628678 Mon Sep 17 00:00:00 2001 From: "xuanyi.wang" Date: Fri, 14 Apr 2023 00:58:25 +0200 Subject: [PATCH] Update page 'Day 8 - homework - Sloejtes' --- Day 8 - homework - Sloejtes.md | 51 ++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Day 8 - homework - Sloejtes.md diff --git a/Day 8 - homework - Sloejtes.md b/Day 8 - homework - Sloejtes.md new file mode 100644 index 0000000..f385873 --- /dev/null +++ b/Day 8 - homework - Sloejtes.md @@ -0,0 +1,51 @@ +![Original](https://gogs.gtsplab.com:5432/j/python-bootcamp/raw/Branch_Sloetjes/Original.png) + +An example of replacing the httpserver.py file with Gunicorn: + +``` +import os +from urllib.parse import urlparse + +class JPEGRequestHandler: + def __init__(self, app): + self.app = app + + def __call__(self, environ, start_response): + url = urlparse(environ['REQUEST_URI']) + path = url.path + + if path.endswith('.jpg'): + file_path = path[1:] + + if os.path.isfile(file_path): + with open(file_path, 'rb') as file: + response_body = file.read() + status = '200 OK' + headers = [('Content-type', 'image/jpeg'), + ('Content-Length', str(len(response_body)))] + + start_response(status, headers) + return [response_body] + else: + status = '404 Not Found' + headers = [('Content-type', 'text/plain'), + ('Content-Length', '0')] + + start_response(status, headers) + return [] + else: + status = '403 Forbidden' + headers = [('Content-type', 'text/plain'), + ('Content-Length', '0')] + + start_response(status, headers) + return [] + +if __name__ == '__main__': + from werkzeug.serving import run_simple + from werkzeug.middleware.dispatcher import DispatcherMiddleware + + app = DispatcherMiddleware(JPEGRequestHandler(app), {'/': app}) + run_simple('0.0.0.0', 8000, app, use_reloader=True) + +``` \ No newline at end of file