/Lib/SimpleHTTPServer.py

http://unladen-swallow.googlecode.com/ · Python · 218 lines · 118 code · 21 blank · 79 comment · 20 complexity · a921195b9bfe76a4e71328cb2d1a0c3d MD5 · raw file

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