SimpleHTTPServer.py 6.8 KB

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