Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import argparse
- import html
- import http.server
- import mimetypes
- import socketserver
- import zipfile
- # wait until zipfile is fixed... https://bugs.python.org/issue40564
- import zipp
- from os.path import basename, dirname
- from urllib.parse import urlparse, unquote
- parser = argparse.ArgumentParser()
- parser.add_argument("archive")
- parser.add_argument("port", type=int, default=8888, nargs='?')
- parser.add_argument("address", default="127.0.0.1", nargs='?')
- parser.add_argument("root", default='', nargs='?')
- args = parser.parse_args()
- archive = zipfile.ZipFile(args.archive)
- class ZipHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
- def do_GET(s):
- suffix = unquote(urlparse(s.path).path.strip('/'))
- path = zipp.Path(archive, args.root) / suffix
- if path.is_dir():
- dir_path = path
- path = path / 'index.html'
- else:
- dir_path = None
- if path.is_file():
- s.send_response(200)
- s.send_header("Content-type", mimetypes.guess_type(path.name)[0])
- s.end_headers()
- s.wfile.write(path.read_bytes())
- elif dir_path is not None:
- s.send_response(200)
- s.send_header("Content-type", "text/html")
- s.end_headers()
- html_dirlist = ''.join(f'<li><a href="{"/" + html.escape(suffix) if suffix else ""}/{html.escape(file.name)}">{html.escape(file.name)}</a></li>' for file in dir_path.iterdir())
- s.wfile.write((f"<html><head><title>autogenerated dirlisting</title></head><body><h1>autogenerated dirlisting</h1><ul>{html_dirlist}</ul></body></html>").encode('UTF8'))
- else:
- s.send_response(404)
- s.send_header("Content-type", "text/html")
- s.end_headers()
- s.wfile.write((f"<html><head></head><body><h1>404: {html.escape(suffix)} not found</h1></body></html>").encode('UTF8'))
- socketserver.TCPServer.allow_reuse_address = True
- with socketserver.TCPServer((args.address, args.port), ZipHTTPRequestHandler) as httpd:
- httpd.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement