Skip to content

Instantly share code, notes, and snippets.

@jdp
Created February 10, 2016 06:55
Show Gist options
  • Save jdp/f1eedeb727f2e86642f3 to your computer and use it in GitHub Desktop.
Save jdp/f1eedeb727f2e86642f3 to your computer and use it in GitHub Desktop.
Serve directory listing kinda like a GitHub project page
#!/usr/bin/env python
import cgi
import os
import mistune
from SimpleHTTPServer import SimpleHTTPRequestHandler
from SocketServer import TCPServer
from cStringIO import StringIO
class ReadmeHandler(SimpleHTTPRequestHandler):
def readme(self, path):
try:
with open(os.path.join(path, 'readme.md')) as f:
return mistune.markdown(f.read())
except IOError:
return ""
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().
Also appends the contents of a readme if it exists.
"""
try:
list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None
list.sort(lambda a, b: cmp(a.lower(), b.lower()))
f = StringIO()
f.write('<head><meta charset="UTF-8"></head>')
f.write("<title>Directory listing for %s</title>\n" % self.path)
f.write("<h2>Directory listing for %s</h2>\n" % self.path)
f.write("<hr>\n<ul>\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name = cgi.escape(name)
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
f.write('<li><a href="%s">%s</a>\n' % (linkname, displayname))
f.write("</ul>\n<hr>\n")
f.write(self.readme(path))
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
return f
port = os.environ.get('PORT', 8000)
server = TCPServer(('', port), ReadmeHandler)
if __name__ == '__main__':
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment