Note
The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
The SimpleHTTPServer module defines a single class, SimpleHTTPRequestHandler, which is interface-compatible with BaseHTTPServer.BaseHTTPRequestHandler.
The SimpleHTTPServer module defines the following class:
This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.
A lot of the work, such as parsing the request, is done by the base class BaseHTTPServer.BaseHTTPRequestHandler. This class implements the do_GET() and do_HEAD() functions.
The following are defined as class-level attributes of SimpleHTTPRequestHandler:
This will be "SimpleHTTP/" + __version__, where __version__ is defined at the module level.
The SimpleHTTPRequestHandler class defines the following methods:
The request is mapped to a local file by interpreting the request as a path relative to the current working directory.
If the request was mapped to a directory, the directory is checked for a file named index.html or index.htm (in that order). If found, the file’s contents are returned; otherwise a directory listing is generated by calling the list_directory() method. This method uses os.listdir() to scan the directory, and returns a 404 error response if the listdir() fails.
If the request was mapped to a file, it is opened and the contents are returned. Any IOError exception in opening the requested file is mapped to a 404, 'File not found' error. Otherwise, the content type is guessed by calling the guess_type() method, which in turn uses the extensions_map variable.
A 'Content-type:' header with the guessed content type is output, followed by a 'Content-Length:' header with the file’s size and a 'Last-Modified:' header with the file’s modification time.
Then follows a blank line signifying the end of the headers, and then the contents of the file are output. If the file’s MIME type starts with text/ the file is opened in text mode; otherwise binary mode is used.
The test() function in the SimpleHTTPServer module is an example which creates a server using the SimpleHTTPRequestHandler as the Handler.
New in version 2.5: The 'Last-Modified' header.
The SimpleHTTPServer module can be used the following manner in order to set up a very basic web server serving files relative to the current directory.:
import SimpleHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
SimpleHTTPServer module can also be invoked directly using the -m switch of interpreter with a port number argument. Similar to previous example, this serves the files relative to the current directory.:
python -m SimpleHTTPServer 8000
See also