Advertisement
elvanderb

Simple HTTP Server able serv zip files

Aug 15th, 2019 (edited)
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import argparse
  2. import html
  3. import http.server
  4. import mimetypes
  5. import socketserver
  6. import zipfile
  7. # wait until zipfile is fixed... https://bugs.python.org/issue40564
  8. import zipp
  9.  
  10. from os.path import basename, dirname
  11. from urllib.parse import urlparse, unquote
  12.  
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument("archive")
  15. parser.add_argument("port", type=int, default=8888, nargs='?')
  16. parser.add_argument("address", default="127.0.0.1", nargs='?')
  17. parser.add_argument("root", default='', nargs='?')
  18. args = parser.parse_args()
  19.  
  20. archive = zipfile.ZipFile(args.archive)
  21.  
  22. class ZipHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
  23.     def do_GET(s):
  24.         suffix = unquote(urlparse(s.path).path.strip('/'))
  25.         path = zipp.Path(archive, args.root) / suffix
  26.         if path.is_dir():
  27.             dir_path = path
  28.             path = path / 'index.html'
  29.         else:
  30.             dir_path = None
  31.         if path.is_file():
  32.             s.send_response(200)
  33.             s.send_header("Content-type", mimetypes.guess_type(path.name)[0])
  34.             s.end_headers()
  35.             s.wfile.write(path.read_bytes())
  36.         elif dir_path is not None:
  37.             s.send_response(200)
  38.             s.send_header("Content-type", "text/html")
  39.             s.end_headers()
  40.             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())
  41.             s.wfile.write((f"<html><head><title>autogenerated dirlisting</title></head><body><h1>autogenerated dirlisting</h1><ul>{html_dirlist}</ul></body></html>").encode('UTF8'))
  42.         else:
  43.             s.send_response(404)
  44.             s.send_header("Content-type", "text/html")
  45.             s.end_headers()
  46.             s.wfile.write((f"<html><head></head><body><h1>404: {html.escape(suffix)} not found</h1></body></html>").encode('UTF8'))
  47.  
  48.  
  49. socketserver.TCPServer.allow_reuse_address = True
  50. with socketserver.TCPServer((args.address, args.port), ZipHTTPRequestHandler) as httpd:
  51.     httpd.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement