You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SimpleHTTPServer.py 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. from StringIO import StringIO
  15. class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  16. """Simple HTTP request handler with GET and HEAD commands.
  17. This serves files from the current directory and any of its
  18. subdirectories. It assumes that all files are plain text files
  19. unless they have the extension ".html" in which case it assumes
  20. they are HTML files.
  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. if ctype.startswith('text/'):
  56. mode = 'r'
  57. else:
  58. mode = 'rb'
  59. try:
  60. f = open(path, mode)
  61. except IOError:
  62. self.send_error(404, "File not found")
  63. return None
  64. self.send_response(200)
  65. self.send_header("Content-type", ctype)
  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(lambda a, b: cmp(a.lower(), b.lower()))
  80. f = StringIO()
  81. f.write("<title>Directory listing for %s</title>\n" % self.path)
  82. f.write("<h2>Directory listing for %s</h2>\n" % self.path)
  83. f.write("<hr>\n<ul>\n")
  84. for name in list:
  85. fullname = os.path.join(path, name)
  86. displayname = linkname = name = cgi.escape(name)
  87. # Append / for directories or @ for symbolic links
  88. if os.path.isdir(fullname):
  89. displayname = name + "/"
  90. linkname = name + "/"
  91. if os.path.islink(fullname):
  92. displayname = name + "@"
  93. # Note: a link to a directory displays with @ and links with /
  94. f.write('<li><a href="%s">%s</a>\n' % (linkname, displayname))
  95. f.write("</ul>\n<hr>\n")
  96. f.seek(0)
  97. self.send_response(200)
  98. self.send_header("Content-type", "text/html")
  99. self.end_headers()
  100. return f
  101. def translate_path(self, path):
  102. """Translate a /-separated PATH to the local filename syntax.
  103. Components that mean special things to the local file system
  104. (e.g. drive or directory names) are ignored. (XXX They should
  105. probably be diagnosed.)
  106. """
  107. path = posixpath.normpath(urllib.unquote(path))
  108. words = path.split('/')
  109. words = filter(None, words)
  110. path = os.getcwd()
  111. for word in words:
  112. drive, word = os.path.splitdrive(word)
  113. head, word = os.path.split(word)
  114. if word in (os.curdir, os.pardir): continue
  115. path = os.path.join(path, word)
  116. return path
  117. def copyfile(self, source, outputfile):
  118. """Copy all data between two file objects.
  119. The SOURCE argument is a file object open for reading
  120. (or anything with a read() method) and the DESTINATION
  121. argument is a file object open for writing (or
  122. anything with a write() method).
  123. The only reason for overriding this would be to change
  124. the block size or perhaps to replace newlines by CRLF
  125. -- note however that this the default server uses this
  126. to copy binary data as well.
  127. """
  128. shutil.copyfileobj(source, outputfile)
  129. def guess_type(self, path):
  130. """Guess the type of a file.
  131. Argument is a PATH (a filename).
  132. Return value is a string of the form type/subtype,
  133. usable for a MIME Content-type header.
  134. The default implementation looks the file's extension
  135. up in the table self.extensions_map, using text/plain
  136. as a default; however it would be permissible (if
  137. slow) to look inside the data to make a better guess.
  138. """
  139. base, ext = posixpath.splitext(path)
  140. if self.extensions_map.has_key(ext):
  141. return self.extensions_map[ext]
  142. ext = ext.lower()
  143. if self.extensions_map.has_key(ext):
  144. return self.extensions_map[ext]
  145. else:
  146. return self.extensions_map['']
  147. extensions_map = mimetypes.types_map.copy()
  148. extensions_map.update({
  149. '': 'application/octet-stream', # Default
  150. '.py': 'text/plain',
  151. '.c': 'text/plain',
  152. '.h': 'text/plain',
  153. })
  154. def test(HandlerClass = SimpleHTTPRequestHandler,
  155. ServerClass = BaseHTTPServer.HTTPServer):
  156. BaseHTTPServer.test(HandlerClass, ServerClass)
  157. if __name__ == '__main__':
  158. test()