This commit was manufactured by cvs2svn to create tag 'cnrisync'.
[python/dscho.git] / Lib / SimpleHTTPServer.py
blobdd3107abc6faf1bad7172896c0e17d00e84c9d7a
1 """Simple HTTP Server.
3 This module builds on BaseHTTPServer by implementing the standard GET
4 and HEAD requests in a fairly straightforward manner.
6 """
9 __version__ = "0.3"
12 import os
13 import pwd
14 import sys
15 import time
16 import socket
17 import string
18 import posixpath
19 import SocketServer
20 import BaseHTTPServer
23 def nobody_uid():
24 """Internal routine to get nobody's uid"""
25 try:
26 nobody = pwd.getpwnam('nobody')[2]
27 except pwd.error:
28 nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
29 return nobody
31 nobody = nobody_uid()
34 class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
36 """Simple HTTP request handler with GET and HEAD commands.
38 This serves files from the current directory and any of its
39 subdirectories. It assumes that all files are plain text files
40 unless they have the extension ".html" in which case it assumes
41 they are HTML files.
43 The GET and HEAD requests are identical except that the HEAD
44 request omits the actual contents of the file.
46 """
48 server_version = "SimpleHTTP/" + __version__
50 def do_GET(self):
51 """Serve a GET request."""
52 f = self.send_head()
53 if f:
54 self.copyfile(f, self.wfile)
55 f.close()
57 def do_HEAD(self):
58 """Serve a HEAD request."""
59 f = self.send_head()
60 if f:
61 f.close()
63 def send_head(self):
64 """Common code for GET and HEAD commands.
66 This sends the response code and MIME headers.
68 Return value is either a file object (which has to be copied
69 to the outputfile by the caller unless the command was HEAD,
70 and must be closed by the caller under all circumstances), or
71 None, in which case the caller has nothing further to do.
73 """
74 path = self.translate_path(self.path)
75 if os.path.isdir(path):
76 self.send_error(403, "Directory listing not supported")
77 return None
78 try:
79 f = open(path)
80 except IOError:
81 self.send_error(404, "File not found")
82 return None
83 self.send_response(200)
84 self.send_header("Content-type", self.guess_type(path))
85 self.end_headers()
86 return f
88 def translate_path(self, path):
89 """Translate a /-separated PATH to the local filename syntax.
91 Components that mean special things to the local file system
92 (e.g. drive or directory names) are ignored. (XXX They should
93 probably be diagnosed.)
95 """
96 path = posixpath.normpath(path)
97 words = string.splitfields(path, '/')
98 words = filter(None, words)
99 path = os.getcwd()
100 for word in words:
101 drive, word = os.path.splitdrive(word)
102 head, word = os.path.split(word)
103 if word in (os.curdir, os.pardir): continue
104 path = os.path.join(path, word)
105 return path
107 def copyfile(self, source, outputfile):
108 """Copy all data between two file objects.
110 The SOURCE argument is a file object open for reading
111 (or anything with a read() method) and the DESTINATION
112 argument is a file object open for writing (or
113 anything with a write() method).
115 The only reason for overriding this would be to change
116 the block size or perhaps to replace newlines by CRLF
117 -- note however that this the default server uses this
118 to copy binary data as well.
122 BLOCKSIZE = 8192
123 while 1:
124 data = source.read(BLOCKSIZE)
125 if not data: break
126 outputfile.write(data)
128 def guess_type(self, path):
129 """Guess the type of a file.
131 Argument is a PATH (a filename).
133 Return value is a string of the form type/subtype,
134 usable for a MIME Content-type header.
136 The default implementation looks the file's extension
137 up in the table self.extensions_map, using text/plain
138 as a default; however it would be permissible (if
139 slow) to look inside the data to make a better guess.
143 base, ext = posixpath.splitext(path)
144 if self.extensions_map.has_key(ext):
145 return self.extensions_map[ext]
146 ext = string.lower(ext)
147 if self.extensions_map.has_key(ext):
148 return self.extensions_map[ext]
149 else:
150 return self.extensions_map['']
152 extensions_map = {
153 '': 'text/plain', # Default, *must* be present
154 '.html': 'text/html',
155 '.htm': 'text/html',
156 '.gif': 'image/gif',
157 '.jpg': 'image/jpeg',
158 '.jpeg': 'image/jpeg',
162 def test(HandlerClass = SimpleHTTPRequestHandler,
163 ServerClass = SocketServer.TCPServer):
164 BaseHTTPServer.test(HandlerClass, ServerClass)
167 if __name__ == '__main__':
168 test()