Skip to content

Instantly share code, notes, and snippets.

@ascheglov
Created April 24, 2018 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ascheglov/b8779e52165a10f6920e4f9d99179a9c to your computer and use it in GitHub Desktop.
Save ascheglov/b8779e52165a10f6920e4f9d99179a9c to your computer and use it in GitHub Desktop.
from http.server import SimpleHTTPRequestHandler, HTTPServer
from http import HTTPStatus
import os, urllib, html, io
import re
class Handler(SimpleHTTPRequestHandler):
def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head().
"""
try:
list = os.listdir(path)
except OSError:
self.send_error(
HTTPStatus.NOT_FOUND,
"No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
text = '''<!DOCTYPE html>
<style>
a, img { display: block; }
</style>
'''
text += '<title>{title}</title>'.format(title=path)
for name in list:
fullname = os.path.join(path, name)
if os.path.isdir(fullname):
text += '<a href="{name}/">{name}/</a>'.format(name=name)
elif not re.match(r'.*\.(gif|jpeg|jpg)$', name):
text += '<div>{name}</div>'.format(name=name)
else:
text += '<img src="{name}"/>'.format(name=name)
encoded = text.encode()
f = io.BytesIO()
f.write(encoded)
f.seek(0)
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
return f
httpd = HTTPServer(('localhost', 8080), Handler)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment