home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / SimpleHTTPServer.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  6.6 KB  |  207 lines

  1. """Simple HTTP Server.
  2.  
  3. This module builds on BaseHTTPServer by implementing the standard GET
  4. and HEAD requests in a fairly straightforward manner.
  5.  
  6. """
  7.  
  8.  
  9. __version__ = "0.6"
  10.  
  11. __all__ = ["SimpleHTTPRequestHandler"]
  12.  
  13. import os
  14. import posixpath
  15. import BaseHTTPServer
  16. import urllib
  17. import urlparse
  18. import cgi
  19. import shutil
  20. import mimetypes
  21. from StringIO import StringIO
  22.  
  23.  
  24. class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  25.  
  26.     """Simple HTTP request handler with GET and HEAD commands.
  27.  
  28.     This serves files from the current directory and any of its
  29.     subdirectories.  The MIME type for files is determined by
  30.     calling the .guess_type() method.
  31.  
  32.     The GET and HEAD requests are identical except that the HEAD
  33.     request omits the actual contents of the file.
  34.  
  35.     """
  36.  
  37.     server_version = "SimpleHTTP/" + __version__
  38.  
  39.     def do_GET(self):
  40.         """Serve a GET request."""
  41.         f = self.send_head()
  42.         if f:
  43.             self.copyfile(f, self.wfile)
  44.             f.close()
  45.  
  46.     def do_HEAD(self):
  47.         """Serve a HEAD request."""
  48.         f = self.send_head()
  49.         if f:
  50.             f.close()
  51.  
  52.     def send_head(self):
  53.         """Common code for GET and HEAD commands.
  54.  
  55.         This sends the response code and MIME headers.
  56.  
  57.         Return value is either a file object (which has to be copied
  58.         to the outputfile by the caller unless the command was HEAD,
  59.         and must be closed by the caller under all circumstances), or
  60.         None, in which case the caller has nothing further to do.
  61.  
  62.         """
  63.         path = self.translate_path(self.path)
  64.         f = None
  65.         if os.path.isdir(path):
  66.             for index in "index.html", "index.htm":
  67.                 index = os.path.join(path, index)
  68.                 if os.path.exists(index):
  69.                     path = index
  70.                     break
  71.             else:
  72.                 return self.list_directory(path)
  73.         ctype = self.guess_type(path)
  74.         try:
  75.             # Always read in binary mode. Opening files in text mode may cause
  76.             # newline translations, making the actual size of the content
  77.             # transmitted *less* than the content-length!
  78.             f = open(path, 'rb')
  79.         except IOError:
  80.             self.send_error(404, "File not found")
  81.             return None
  82.         self.send_response(200)
  83.         self.send_header("Content-type", ctype)
  84.         self.send_header("Content-Length", str(os.fstat(f.fileno())[6]))
  85.         self.end_headers()
  86.         return f
  87.  
  88.     def list_directory(self, path):
  89.         """Helper to produce a directory listing (absent index.html).
  90.  
  91.         Return value is either a file object, or None (indicating an
  92.         error).  In either case, the headers are sent, making the
  93.         interface the same as for send_head().
  94.  
  95.         """
  96.         try:
  97.             list = os.listdir(path)
  98.         except os.error:
  99.             self.send_error(404, "No permission to list directory")
  100.             return None
  101.         list.sort(key=lambda a: a.lower())
  102.         f = StringIO()
  103.         displaypath = cgi.escape(urllib.unquote(self.path))
  104.         f.write("<title>Directory listing for %s</title>\n" % displaypath)
  105.         f.write("<h2>Directory listing for %s</h2>\n" % displaypath)
  106.         f.write("<hr>\n<ul>\n")
  107.         for name in list:
  108.             fullname = os.path.join(path, name)
  109.             displayname = linkname = name
  110.             # Append / for directories or @ for symbolic links
  111.             if os.path.isdir(fullname):
  112.                 displayname = name + "/"
  113.                 linkname = name + "/"
  114.             if os.path.islink(fullname):
  115.                 displayname = name + "@"
  116.                 # Note: a link to a directory displays with @ and links with /
  117.             f.write('<li><a href="%s">%s</a>\n'
  118.                     % (urllib.quote(linkname), cgi.escape(displayname)))
  119.         f.write("</ul>\n<hr>\n")
  120.         length = f.tell()
  121.         f.seek(0)
  122.         self.send_response(200)
  123.         self.send_header("Content-type", "text/html")
  124.         self.send_header("Content-Length", str(length))
  125.         self.end_headers()
  126.         return f
  127.  
  128.     def translate_path(self, path):
  129.         """Translate a /-separated PATH to the local filename syntax.
  130.  
  131.         Components that mean special things to the local file system
  132.         (e.g. drive or directory names) are ignored.  (XXX They should
  133.         probably be diagnosed.)
  134.  
  135.         """
  136.         # abandon query parameters
  137.         path = urlparse.urlparse(path)[2]
  138.         path = posixpath.normpath(urllib.unquote(path))
  139.         words = path.split('/')
  140.         words = filter(None, words)
  141.         path = os.getcwd()
  142.         for word in words:
  143.             drive, word = os.path.splitdrive(word)
  144.             head, word = os.path.split(word)
  145.             if word in (os.curdir, os.pardir): continue
  146.             path = os.path.join(path, word)
  147.         return path
  148.  
  149.     def copyfile(self, source, outputfile):
  150.         """Copy all data between two file objects.
  151.  
  152.         The SOURCE argument is a file object open for reading
  153.         (or anything with a read() method) and the DESTINATION
  154.         argument is a file object open for writing (or
  155.         anything with a write() method).
  156.  
  157.         The only reason for overriding this would be to change
  158.         the block size or perhaps to replace newlines by CRLF
  159.         -- note however that this the default server uses this
  160.         to copy binary data as well.
  161.  
  162.         """
  163.         shutil.copyfileobj(source, outputfile)
  164.  
  165.     def guess_type(self, path):
  166.         """Guess the type of a file.
  167.  
  168.         Argument is a PATH (a filename).
  169.  
  170.         Return value is a string of the form type/subtype,
  171.         usable for a MIME Content-type header.
  172.  
  173.         The default implementation looks the file's extension
  174.         up in the table self.extensions_map, using application/octet-stream
  175.         as a default; however it would be permissible (if
  176.         slow) to look inside the data to make a better guess.
  177.  
  178.         """
  179.  
  180.         base, ext = posixpath.splitext(path)
  181.         if ext in self.extensions_map:
  182.             return self.extensions_map[ext]
  183.         ext = ext.lower()
  184.         if ext in self.extensions_map:
  185.             return self.extensions_map[ext]
  186.         else:
  187.             return self.extensions_map['']
  188.     
  189.     if not mimetypes.inited:
  190.         mimetypes.init() # try to read system mime.types
  191.     extensions_map = mimetypes.types_map.copy()
  192.     extensions_map.update({
  193.         '': 'application/octet-stream', # Default
  194.         '.py': 'text/plain',
  195.         '.c': 'text/plain',
  196.         '.h': 'text/plain',
  197.         })
  198.  
  199.  
  200. def test(HandlerClass = SimpleHTTPRequestHandler,
  201.          ServerClass = BaseHTTPServer.HTTPServer):
  202.     BaseHTTPServer.test(HandlerClass, ServerClass)
  203.  
  204.  
  205. if __name__ == '__main__':
  206.     test()
  207.