forked from SVIG/python-bootcamp
Homework for web server
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "0593e529",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from urllib.parse import urlparse\n",
|
||||
"\n",
|
||||
"class JPEGRequestHandler:\n",
|
||||
" def __init__(self, app):\n",
|
||||
" self.app = app\n",
|
||||
"\n",
|
||||
" def __call__(self, environ, start_response):\n",
|
||||
" url = urlparse(environ['REQUEST_URI'])\n",
|
||||
" path = url.path\n",
|
||||
"\n",
|
||||
" if path.endswith('.jpg'):\n",
|
||||
" file_path = path[1:]\n",
|
||||
"\n",
|
||||
" if os.path.isfile(file_path):\n",
|
||||
" with open(file_path, 'rb') as file:\n",
|
||||
" response_body = file.read()\n",
|
||||
" status = '200 OK'\n",
|
||||
" headers = [('Content-type', 'image/jpeg'),\n",
|
||||
" ('Content-Length', str(len(response_body)))]\n",
|
||||
"\n",
|
||||
" start_response(status, headers)\n",
|
||||
" return [response_body]\n",
|
||||
" else:\n",
|
||||
" status = '404 Not Found'\n",
|
||||
" headers = [('Content-type', 'text/plain'),\n",
|
||||
" ('Content-Length', '0')]\n",
|
||||
"\n",
|
||||
" start_response(status, headers)\n",
|
||||
" return []\n",
|
||||
" else:\n",
|
||||
" status = '403 Forbidden'\n",
|
||||
" headers = [('Content-type', 'text/plain'),\n",
|
||||
" ('Content-Length', '0')]\n",
|
||||
"\n",
|
||||
" start_response(status, headers)\n",
|
||||
" return []\n",
|
||||
"\n",
|
||||
"if __name__ == '__main__':\n",
|
||||
" from werkzeug.serving import run_simple\n",
|
||||
" from werkzeug.middleware.dispatcher import DispatcherMiddleware\n",
|
||||
"\n",
|
||||
" app = DispatcherMiddleware(JPEGRequestHandler(app), {'/': app})\n",
|
||||
" run_simple('0.0.0.0', 8000, app, use_reloader=True)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.9.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
Reference in New Issue
Block a user