diff options
author | Guido van Rossum <guido@python.org> | 2000-05-09 14:57:09 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 2000-05-09 14:57:09 (GMT) |
commit | 57af072e5c0dcacf5c7fe3789113c21d223e1258 (patch) | |
tree | c10e2f66f715242fbc5fb4b1ee2dae1e9cb4c2cb /Lib/SimpleHTTPServer.py | |
parent | 18865de7bd91dfcc42f323440aa85e6f36972c72 (diff) | |
download | cpython-57af072e5c0dcacf5c7fe3789113c21d223e1258.zip cpython-57af072e5c0dcacf5c7fe3789113c21d223e1258.tar.gz cpython-57af072e5c0dcacf5c7fe3789113c21d223e1258.tar.bz2 |
Add a simple directory listing function.
Diffstat (limited to 'Lib/SimpleHTTPServer.py')
-rw-r--r-- | Lib/SimpleHTTPServer.py | 47 |
1 files changed, 38 insertions, 9 deletions
diff --git a/Lib/SimpleHTTPServer.py b/Lib/SimpleHTTPServer.py index a4517dc..6def14e 100644 --- a/Lib/SimpleHTTPServer.py +++ b/Lib/SimpleHTTPServer.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): @@ -58,18 +60,45 @@ class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """ path = self.translate_path(self.path) if os.path.isdir(path): - self.send_error(403, "Directory listing not supported") - return None - try: - f = open(path, 'rb') - except IOError: - self.send_error(404, "File not found") - return None + f = self.list_directory(path) + if f is None: + return None + ctype = "text/HTML" + else: + try: + f = open(path, 'rb') + except IOError: + self.send_error(404, "File not found") + return None + ctype = self.guess_type(path) 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): + 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 = name = cgi.escape(name) + if os.path.islink(fullname): + displayname = name + "@" + elif os.path.isdir(fullname): + displayname = name + "/" + name = name + os.sep + f.write('<li><a href="%s">%s</a>\n' % (name, displayname)) + f.write("</ul>\n<hr>\n") + f.seek(0) + return f + def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. |