[Python-checkins] CVS: python/dist/src/Lib SimpleHTTPServer.py,1.8,1.9

Guido van Rossum python-dev@python.org
Tue, 9 May 2000 10:57:12 -0400 (EDT)


Update of /projects/cvsroot/python/dist/src/Lib
In directory eric:/projects/python/develop/guido/src/Lib

Modified Files:
	SimpleHTTPServer.py 
Log Message:
Add a simple directory listing function.


Index: SimpleHTTPServer.py
===================================================================
RCS file: /projects/cvsroot/python/dist/src/Lib/SimpleHTTPServer.py,v
retrieving revision 1.8
retrieving revision 1.9
diff -C2 -r1.8 -r1.9
*** SimpleHTTPServer.py	1999/11/16 19:04:32	1.8
--- SimpleHTTPServer.py	2000/05/09 14:57:09	1.9
***************
*** 7,11 ****
  
  
! __version__ = "0.3"
  
  
--- 7,11 ----
  
  
! __version__ = "0.4"
  
  
***************
*** 15,18 ****
--- 15,20 ----
  import BaseHTTPServer
  import urllib
+ import cgi
+ from StringIO import StringIO
  
  
***************
*** 59,72 ****
          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
          self.send_response(200)
!         self.send_header("Content-type", self.guess_type(path))
          self.end_headers()
          return f
  
--- 61,101 ----
          path = self.translate_path(self.path)
          if os.path.isdir(path):
!             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", 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