ยปCore Development>Code coverage>Lib/SimpleHTTPServer.py

Python code coverage for Lib/SimpleHTTPServer.py

#countcontent
1n/a"""Simple HTTP Server.
2n/a
3n/aThis module builds on BaseHTTPServer by implementing the standard GET
4n/aand HEAD requests in a fairly straightforward manner.
5n/a
61"""
7n/a
8n/a
91__version__ = "0.6"
10n/a
111__all__ = ["SimpleHTTPRequestHandler"]
12n/a
131import os
141import posixpath
151import BaseHTTPServer
161import urllib
171import cgi
181import shutil
191import mimetypes
201try:
211 from cStringIO import StringIO
220except ImportError:
230 from StringIO import StringIO
24n/a
25n/a
262class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
27n/a
28n/a """Simple HTTP request handler with GET and HEAD commands.
29n/a
30n/a This serves files from the current directory and any of its
31n/a subdirectories. The MIME type for files is determined by
32n/a calling the .guess_type() method.
33n/a
34n/a The GET and HEAD requests are identical except that the HEAD
35n/a request omits the actual contents of the file.
36n/a
371 """
38n/a
391 server_version = "SimpleHTTP/" + __version__
40n/a
411 def do_GET(self):
42n/a """Serve a GET request."""
4312 f = self.send_head()
4412 if f:
454 self.copyfile(f, self.wfile)
464 f.close()
47n/a
481 def do_HEAD(self):
49n/a """Serve a HEAD request."""
501 f = self.send_head()
511 if f:
521 f.close()
53n/a
541 def send_head(self):
55n/a """Common code for GET and HEAD commands.
56n/a
57n/a This sends the response code and MIME headers.
58n/a
59n/a Return value is either a file object (which has to be copied
60n/a to the outputfile by the caller unless the command was HEAD,
61n/a and must be closed by the caller under all circumstances), or
62n/a None, in which case the caller has nothing further to do.
63n/a
64n/a """
659 path = self.translate_path(self.path)
669 f = None
679 if os.path.isdir(path):
684 if not self.path.endswith('/'):
69n/a # redirect browser - doing basically what apache does
701 self.send_response(301)
711 self.send_header("Location", self.path + "/")
721 self.end_headers()
731 return None
747 for index in "index.html", "index.htm":
755 index = os.path.join(path, index)
765 if os.path.exists(index):
771 path = index
781 break
79n/a else:
802 return self.list_directory(path)
816 ctype = self.guess_type(path)
826 try:
83n/a # Always read in binary mode. Opening files in text mode may cause
84n/a # newline translations, making the actual size of the content
85n/a # transmitted *less* than the content-length!
866 f = open(path, 'rb')
872 except IOError:
882 self.send_error(404, "File not found")
892 return None
904 self.send_response(200)
914 self.send_header("Content-type", ctype)
924 fs = os.fstat(f.fileno())
934 self.send_header("Content-Length", str(fs[6]))
944 self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
954 self.end_headers()
964 return f
97n/a
981 def list_directory(self, path):
99n/a """Helper to produce a directory listing (absent index.html).
100n/a
101n/a Return value is either a file object, or None (indicating an
102n/a error). In either case, the headers are sent, making the
103n/a interface the same as for send_head().
104n/a
105n/a """
1062 try:
1072 list = os.listdir(path)
1081 except os.error:
1091 self.send_error(404, "No permission to list directory")
1101 return None
1112 list.sort(key=lambda a: a.lower())
1121 f = StringIO()
1131 displaypath = cgi.escape(urllib.unquote(self.path))
1141 f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
1151 f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
1161 f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
1171 f.write("<hr>\n<ul>\n")
1182 for name in list:
1191 fullname = os.path.join(path, name)
1201 displayname = linkname = name
121n/a # Append / for directories or @ for symbolic links
1221 if os.path.isdir(fullname):
1230 displayname = name + "/"
1240 linkname = name + "/"
1251 if os.path.islink(fullname):
1260 displayname = name + "@"
127n/a # Note: a link to a directory displays with @ and links with /
1281 f.write('<li><a href="%s">%s</a>\n'
1291 % (urllib.quote(linkname), cgi.escape(displayname)))
1301 f.write("</ul>\n<hr>\n</body>\n</html>\n")
1311 length = f.tell()
1321 f.seek(0)
1331 self.send_response(200)
1341 self.send_header("Content-type", "text/html")
1351 self.send_header("Content-Length", str(length))
1361 self.end_headers()
1371 return f
138n/a
1391 def translate_path(self, path):
140n/a """Translate a /-separated PATH to the local filename syntax.
141n/a
142n/a Components that mean special things to the local file system
143n/a (e.g. drive or directory names) are ignored. (XXX They should
144n/a probably be diagnosed.)
145n/a
146n/a """
147n/a # abandon query parameters
14822 path = path.split('?',1)[0]
14922 path = path.split('#',1)[0]
15022 path = posixpath.normpath(urllib.unquote(path))
15122 words = path.split('/')
15222 words = filter(None, words)
15322 path = os.getcwd()
15451 for word in words:
15529 drive, word = os.path.splitdrive(word)
15629 head, word = os.path.split(word)
15729 if word in (os.curdir, os.pardir): continue
15825 path = os.path.join(path, word)
15922 return path
160n/a
1611 def copyfile(self, source, outputfile):
162n/a """Copy all data between two file objects.
163n/a
164n/a The SOURCE argument is a file object open for reading
165n/a (or anything with a read() method) and the DESTINATION
166n/a argument is a file object open for writing (or
167n/a anything with a write() method).
168n/a
169n/a The only reason for overriding this would be to change
170n/a the block size or perhaps to replace newlines by CRLF
171n/a -- note however that this the default server uses this
172n/a to copy binary data as well.
173n/a
174n/a """
1754 shutil.copyfileobj(source, outputfile)
176n/a
1771 def guess_type(self, path):
178n/a """Guess the type of a file.
179n/a
180n/a Argument is a PATH (a filename).
181n/a
182n/a Return value is a string of the form type/subtype,
183n/a usable for a MIME Content-type header.
184n/a
185n/a The default implementation looks the file's extension
186n/a up in the table self.extensions_map, using application/octet-stream
187n/a as a default; however it would be permissible (if
188n/a slow) to look inside the data to make a better guess.
189n/a
190n/a """
191n/a
1926 base, ext = posixpath.splitext(path)
1936 if ext in self.extensions_map:
1945 return self.extensions_map[ext]
1951 ext = ext.lower()
1961 if ext in self.extensions_map:
1970 return self.extensions_map[ext]
198n/a else:
1991 return self.extensions_map['']
200n/a
2011 if not mimetypes.inited:
2021 mimetypes.init() # try to read system mime.types
2031 extensions_map = mimetypes.types_map.copy()
2041 extensions_map.update({
2051 '': 'application/octet-stream', # Default
2061 '.py': 'text/plain',
2071 '.c': 'text/plain',
2081 '.h': 'text/plain',
209n/a })
210n/a
211n/a
2121def test(HandlerClass = SimpleHTTPRequestHandler,
2131 ServerClass = BaseHTTPServer.HTTPServer):
2140 BaseHTTPServer.test(HandlerClass, ServerClass)
215n/a
216n/a
2171if __name__ == '__main__':
2180 test()