20.18.BaseHTTPServer — Basic HTTP server

Note

TheBaseHTTPServer module has been merged intohttp.server inPython 3. The2to3 tool will automatically adapt imports whenconverting your sources to Python 3.

Source code:Lib/BaseHTTPServer.py


This module defines two classes for implementing HTTP servers (Web servers).Usually, this module isn’t used directly, but is used as a basis for buildingfunctioning Web servers. See theSimpleHTTPServer andCGIHTTPServer modules.

The first class,HTTPServer, is aSocketServer.TCPServersubclass, and therefore implements theSocketServer.BaseServerinterface. It creates and listens at the HTTP socket, dispatching the requeststo a handler. Code to create and run the server looks like this:

defrun(server_class=BaseHTTPServer.HTTPServer,handler_class=BaseHTTPServer.BaseHTTPRequestHandler):server_address=('',8000)httpd=server_class(server_address,handler_class)httpd.serve_forever()
classBaseHTTPServer.HTTPServer(server_address,RequestHandlerClass)

This class builds on theTCPServer class by storing the serveraddress as instance variables namedserver_name andserver_port. The server is accessible by the handler, typicallythrough the handler’sserver instance variable.

classBaseHTTPServer.BaseHTTPRequestHandler(request,client_address,server)

This class is used to handle the HTTP requests that arrive at the server. Byitself, it cannot respond to any actual HTTP requests; it must be subclassedto handle each request method (e.g. GET orPOST).BaseHTTPRequestHandler provides a number of class andinstance variables, and methods for use by subclasses.

The handler will parse the request and the headers, then call a methodspecific to the request type. The method name is constructed from therequest. For example, for the request methodSPAM, thedo_SPAM()method will be called with no arguments. All of the relevant information isstored in instance variables of the handler. Subclasses should not need tooverride or extend the__init__() method.

BaseHTTPRequestHandler has the following instance variables:

client_address

Contains a tuple of the form(host,port) referring to the client’saddress.

server

Contains the server instance.

command

Contains the command (request type). For example,'GET'.

path

Contains the request path.

request_version

Contains the version string from the request. For example,'HTTP/1.0'.

headers

Holds an instance of the class specified by theMessageClass classvariable. This instance parses and manages the headers in the HTTPrequest.

rfile

Contains an input stream, positioned at the start of the optional inputdata.

wfile

Contains the output stream for writing a response back to theclient. Proper adherence to the HTTP protocol must be used when writing tothis stream.

BaseHTTPRequestHandler has the following class variables:

server_version

Specifies the server software version. You may want to override this. Theformat is multiple whitespace-separated strings, where each string is ofthe form name[/version]. For example,'BaseHTTP/0.2'.

sys_version

Contains the Python system version, in a form usable by theversion_string method and theserver_version classvariable. For example,'Python/1.4'.

error_message_format

Specifies a format string for building an error response to the client. Ituses parenthesized, keyed format specifiers, so the format operand must bea dictionary. Thecode key should be an integer, specifying the numericHTTP error code value.message should be a string containing a(detailed) error message of what occurred, andexplain should be anexplanation of the error code number. Defaultmessage andexplainvalues can found in theresponses class variable.

error_content_type

Specifies the Content-Type HTTP header of error responses sent to theclient. The default value is'text/html'.

New in version 2.6:Previously, the content type was always'text/html'.

protocol_version

This specifies the HTTP protocol version used in responses. If set to'HTTP/1.1', the server will permit HTTP persistent connections;however, your servermust then include an accurateContent-Lengthheader (usingsend_header()) in all of its responses to clients.For backwards compatibility, the setting defaults to'HTTP/1.0'.

MessageClass

Specifies arfc822.Message-like class to parse HTTP headers.Typically, this is not overridden, and it defaults tomimetools.Message.

responses

This variable contains a mapping of error code integers to two-element tuplescontaining a short and long message. For example,{code:(shortmessage,longmessage)}. Theshortmessage is usually used as themessage key in anerror response, andlongmessage as theexplain key (see theerror_message_format class variable).

ABaseHTTPRequestHandler instance has the following methods:

handle()

Callshandle_one_request() once (or, if persistent connections areenabled, multiple times) to handle incoming HTTP requests. You shouldnever need to override it; instead, implement appropriatedo_*()methods.

handle_one_request()

This method will parse and dispatch the request to the appropriatedo_*() method. You should never need to override it.

send_error(code[,message])

Sends and logs a complete error reply to the client. The numericcodespecifies the HTTP error code, withmessage as optional, more specific text. Acomplete set of headers is sent, followed by text composed using theerror_message_format class variable. The body will be emptyif the method is HEAD or the response code is one of the following:1xx,204NoContent,205ResetContent,304NotModified.

send_response(code[,message])

Sends a response header and logs the accepted request. The HTTP responseline is sent, followed byServer andDate headers. The values forthese two headers are picked up from theversion_string() anddate_time_string() methods, respectively.

send_header(keyword,value)

Writes a specific HTTP header to the output stream.keyword shouldspecify the header keyword, withvalue specifying its value.

end_headers()

Sends a blank line, indicating the end of the HTTP headers in theresponse.

log_request([code[,size]])

Logs an accepted (successful) request.code should specify the numericHTTP code associated with the response. If a size of the response isavailable, then it should be passed as thesize parameter.

log_error(...)

Logs an error when a request cannot be fulfilled. By default, it passesthe message tolog_message(), so it takes the same arguments(format and additional values).

log_message(format,...)

Logs an arbitrary message tosys.stderr. This is typically overriddento create custom error logging mechanisms. Theformat argument is astandard printf-style format string, where the additional arguments tolog_message() are applied as inputs to the formatting. The clientip address and current date and time are prefixed to every message logged.

version_string()

Returns the server software’s version string. This is a combination of theserver_version andsys_version class variables.

date_time_string([timestamp])

Returns the date and time given bytimestamp (which must be in theformat returned bytime.time()), formatted for a message header. Iftimestamp is omitted, it uses the current date and time.

The result looks like'Sun,06Nov199408:49:37GMT'.

New in version 2.5:Thetimestamp parameter.

log_date_time_string()

Returns the current date and time, formatted for logging.

address_string()

Returns the client address, formatted for logging. A name lookup isperformed on the client’s IP address.

20.18.1.More examples

To create a server that doesn’t run forever, but until some condition isfulfilled:

defrun_while_true(server_class=BaseHTTPServer.HTTPServer,handler_class=BaseHTTPServer.BaseHTTPRequestHandler):"""    This assumes that keep_running() is a function of no arguments which    is tested initially and after each request.  If its return value    is true, the server continues.    """server_address=('',8000)httpd=server_class(server_address,handler_class)whilekeep_running():httpd.handle_request()

See also

ModuleCGIHTTPServer

Extended request handler that supports CGI scripts.

ModuleSimpleHTTPServer

Basic request handler that limits response to files actually under thedocument root.