blob: dd3107abc6faf1bad7172896c0e17d00e84c9d7a [file] [log] [blame]
Guido van Rossum5c971671996-07-22 15:23:25 +00001"""Simple HTTP Server.
2
3This module builds on BaseHTTPServer by implementing the standard GET
4and HEAD requests in a fairly straightforward manner.
5
6"""
7
8
9__version__ = "0.3"
10
11
12import os
13import pwd
14import sys
15import time
16import socket
17import string
18import posixpath
19import SocketServer
20import BaseHTTPServer
21
22
23def 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
30
31nobody = nobody_uid()
32
33
34class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
35
36 """Simple HTTP request handler with GET and HEAD commands.
37
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.
42
43 The GET and HEAD requests are identical except that the HEAD
44 request omits the actual contents of the file.
45
46 """
47
48 server_version = "SimpleHTTP/" + __version__
49
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()
56
57 def do_HEAD(self):
58 """Serve a HEAD request."""
59 f = self.send_head()
60 if f:
61 f.close()
62
63 def send_head(self):
64 """Common code for GET and HEAD commands.
65
66 This sends the response code and MIME headers.
67
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.
72
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
87
88 def translate_path(self, path):
89 """Translate a /-separated PATH to the local filename syntax.
90
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.)
94
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
106
107 def copyfile(self, source, outputfile):
108 """Copy all data between two file objects.
109
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).
114
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.
119
120 """
121
122 BLOCKSIZE = 8192
123 while 1:
124 data = source.read(BLOCKSIZE)
125 if not data: break
126 outputfile.write(data)
127
128 def guess_type(self, path):
129 """Guess the type of a file.
130
131 Argument is a PATH (a filename).
132
133 Return value is a string of the form type/subtype,
134 usable for a MIME Content-type header.
135
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.
140
141 """
142
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['']
151
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',
159 }
160
161
162def test(HandlerClass = SimpleHTTPRequestHandler,
163 ServerClass = SocketServer.TCPServer):
164 BaseHTTPServer.test(HandlerClass, ServerClass)
165
166
167if __name__ == '__main__':
168 test()