diff options
Diffstat (limited to 'Lib/dos-8x3/simpleht.py')
-rwxr-xr-x | Lib/dos-8x3/simpleht.py | 58 |
1 files changed, 53 insertions, 5 deletions
diff --git a/Lib/dos-8x3/simpleht.py b/Lib/dos-8x3/simpleht.py index a4517dc..7125413 100755 --- a/Lib/dos-8x3/simpleht.py +++ b/Lib/dos-8x3/simpleht.py @@ -6,7 +6,7 @@ and HEAD requests in a fairly straightforward manner. """ -__version__ = "0.3" +__version__ = "0.4" import os @@ -14,6 +14,8 @@ import string import posixpath import BaseHTTPServer import urllib +import cgi +from StringIO import StringIO class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): @@ -57,16 +59,62 @@ class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """ path = self.translate_path(self.path) + f = None if os.path.isdir(path): - self.send_error(403, "Directory listing not supported") - return None + for index in "index.html", "index.htm": + index = os.path.join(path, index) + if os.path.exists(index): + path = index + break + else: + return self.list_directory(path) + ctype = self.guess_type(path) + if ctype.startswith('text/'): + mode = 'r' + else: + mode = 'rb' try: - f = open(path, 'rb') + f = open(path, mode) except IOError: self.send_error(404, "File not found") return None self.send_response(200) - self.send_header("Content-type", self.guess_type(path)) + self.send_header("Content-type", ctype) + self.end_headers() + return f + + 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 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("<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 + os.sep + 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.seek(0) + self.send_response(200) + self.send_header("Content-type", "text/html") self.end_headers() return f |