Update page 'Day 8 - homework - Sloejtes'
@@ -0,0 +1,51 @@
|
||||

|
||||
|
||||
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)
|
||||
|
||||
```
|
||||
Reference in New Issue
Block a user