SimpleHTTPServer — Simple HTTP request handler¶
SimpleHTTPServer module defines the following class:
SimpleHTTPRequestHandler(request, client_address, server)¶
This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.
The following are defined as class-level attributes of
This will be
"SimpleHTTP/" + __version__, where
__version__is defined at the module level.
A dictionary mapping suffixes into MIME types. The default is signified by an empty string, and is considered to be
application/octet-stream. The mapping is used case-insensitively, and so should contain only lower-cased keys.
SimpleHTTPRequestHandlerclass defines the following methods:
This method serves the
'HEAD'request type: it sends the headers it would send for the equivalent
GETrequest. See the
do_GET()method for a more complete explanation of the possible headers.
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.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
404error response if the
If the request was mapped to a file, it is opened and the contents are returned. Any
IOErrorexception in opening the requested file is mapped to a
'File not found'error. Otherwise, the content type is guessed by calling the
guess_type()method, which in turn uses the extensions_map variable.
'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.
New in version 2.5: The
SimpleHTTPServer module can be used in the following manner in order
to set up a very basic web server serving files relative to the current
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 the interpreter with a
port number argument.
Similar to the previous example, this serves the files relative to the
python -m SimpleHTTPServer 8000
- Base class implementation for Web server and request handler.