Issue #5170: Fixed regression caused when fixing #5768.
[python.git] / Doc / library / basehttpserver.rst
blob4662b4f9a1443bc3291e17a06640c7ea673f642d
1 :mod:`BaseHTTPServer` --- Basic HTTP server
2 ===========================================
4 .. module:: BaseHTTPServer
5    :synopsis: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer).
7 .. note::
8    The :mod:`BaseHTTPServer` module has been merged into :mod:`http.server` in
9    Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
10    converting your sources to 3.0.
13 .. index::
14    pair: WWW; server
15    pair: HTTP; protocol
16    single: URL
17    single: httpd
18    module: SimpleHTTPServer
19    module: CGIHTTPServer
21 This module defines two classes for implementing HTTP servers (Web servers).
22 Usually, this module isn't used directly, but is used as a basis for building
23 functioning Web servers. See the :mod:`SimpleHTTPServer` and
24 :mod:`CGIHTTPServer` modules.
26 The first class, :class:`HTTPServer`, is a :class:`SocketServer.TCPServer`
27 subclass, and therefore implements the :class:`SocketServer.BaseServer`
28 interface.  It creates and listens at the HTTP socket, dispatching the requests
29 to a handler.  Code to create and run the server looks like this::
31    def run(server_class=BaseHTTPServer.HTTPServer,
32            handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
33        server_address = ('', 8000)
34        httpd = server_class(server_address, handler_class)
35        httpd.serve_forever()
38 .. class:: HTTPServer(server_address, RequestHandlerClass)
40    This class builds on the :class:`TCPServer` class by storing the server
41    address as instance variables named :attr:`server_name` and
42    :attr:`server_port`. The server is accessible by the handler, typically
43    through the handler's :attr:`server` instance variable.
46 .. class:: BaseHTTPRequestHandler(request, client_address, server)
48    This class is used to handle the HTTP requests that arrive at the server. By
49    itself, it cannot respond to any actual HTTP requests; it must be subclassed
50    to handle each request method (e.g. GET or
51    POST). :class:`BaseHTTPRequestHandler` provides a number of class and
52    instance variables, and methods for use by subclasses.
54    The handler will parse the request and the headers, then call a method
55    specific to the request type. The method name is constructed from the
56    request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
57    method will be called with no arguments. All of the relevant information is
58    stored in instance variables of the handler.  Subclasses should not need to
59    override or extend the :meth:`__init__` method.
61    :class:`BaseHTTPRequestHandler` has the following instance variables:
64    .. attribute:: client_address
66       Contains a tuple of the form ``(host, port)`` referring to the client's
67       address.
70    .. attribute:: server
72       Contains the server instance.
75    .. attribute:: command
77       Contains the command (request type). For example, ``'GET'``.
80    .. attribute:: path
82       Contains the request path.
85    .. attribute:: request_version
87       Contains the version string from the request. For example, ``'HTTP/1.0'``.
90    .. attribute:: headers
92       Holds an instance of the class specified by the :attr:`MessageClass` class
93       variable. This instance parses and manages the headers in the HTTP
94       request.
97    .. attribute:: rfile
99       Contains an input stream, positioned at the start of the optional input
100       data.
103    .. attribute:: wfile
105       Contains the output stream for writing a response back to the
106       client. Proper adherence to the HTTP protocol must be used when writing to
107       this stream.
110    :class:`BaseHTTPRequestHandler` has the following class variables:
113    .. attribute:: server_version
115       Specifies the server software version.  You may want to override this. The
116       format is multiple whitespace-separated strings, where each string is of
117       the form name[/version]. For example, ``'BaseHTTP/0.2'``.
120    .. attribute:: sys_version
122       Contains the Python system version, in a form usable by the
123       :attr:`version_string` method and the :attr:`server_version` class
124       variable. For example, ``'Python/1.4'``.
127    .. attribute:: error_message_format
129       Specifies a format string for building an error response to the client. It
130       uses parenthesized, keyed format specifiers, so the format operand must be
131       a dictionary. The *code* key should be an integer, specifying the numeric
132       HTTP error code value. *message* should be a string containing a
133       (detailed) error message of what occurred, and *explain* should be an
134       explanation of the error code number. Default *message* and *explain*
135       values can found in the *responses* class variable.
138    .. attribute:: error_content_type
140       Specifies the Content-Type HTTP header of error responses sent to the
141       client.  The default value is ``'text/html'``.
143       .. versionadded:: 2.6
144          Previously, the content type was always ``'text/html'``.
147    .. attribute:: protocol_version
149       This specifies the HTTP protocol version used in responses.  If set to
150       ``'HTTP/1.1'``, the server will permit HTTP persistent connections;
151       however, your server *must* then include an accurate ``Content-Length``
152       header (using :meth:`send_header`) in all of its responses to clients.
153       For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
156    .. attribute:: MessageClass
158       .. index:: single: Message (in module mimetools)
160       Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers.
161       Typically, this is not overridden, and it defaults to
162       :class:`mimetools.Message`.
165    .. attribute:: responses
167       This variable contains a mapping of error code integers to two-element tuples
168       containing a short and long message. For example, ``{code: (shortmessage,
169       longmessage)}``. The *shortmessage* is usually used as the *message* key in an
170       error response, and *longmessage* as the *explain* key (see the
171       :attr:`error_message_format` class variable).
174    A :class:`BaseHTTPRequestHandler` instance has the following methods:
177    .. method:: handle()
179       Calls :meth:`handle_one_request` once (or, if persistent connections are
180       enabled, multiple times) to handle incoming HTTP requests. You should
181       never need to override it; instead, implement appropriate :meth:`do_\*`
182       methods.
185    .. method:: handle_one_request()
187       This method will parse and dispatch the request to the appropriate
188       :meth:`do_\*` method.  You should never need to override it.
191    .. method:: send_error(code[, message])
193       Sends and logs a complete error reply to the client. The numeric *code*
194       specifies the HTTP error code, with *message* as optional, more specific text. A
195       complete set of headers is sent, followed by text composed using the
196       :attr:`error_message_format` class variable.
199    .. method:: send_response(code[, message])
201       Sends a response header and logs the accepted request. The HTTP response
202       line is sent, followed by *Server* and *Date* headers. The values for
203       these two headers are picked up from the :meth:`version_string` and
204       :meth:`date_time_string` methods, respectively.
207    .. method:: send_header(keyword, value)
209       Writes a specific HTTP header to the output stream. *keyword* should
210       specify the header keyword, with *value* specifying its value.
213    .. method:: end_headers()
215       Sends a blank line, indicating the end of the HTTP headers in the
216       response.
219    .. method:: log_request([code[, size]])
221       Logs an accepted (successful) request. *code* should specify the numeric
222       HTTP code associated with the response. If a size of the response is
223       available, then it should be passed as the *size* parameter.
226    .. method:: log_error(...)
228       Logs an error when a request cannot be fulfilled. By default, it passes
229       the message to :meth:`log_message`, so it takes the same arguments
230       (*format* and additional values).
233    .. method:: log_message(format, ...)
235       Logs an arbitrary message to ``sys.stderr``. This is typically overridden
236       to create custom error logging mechanisms. The *format* argument is a
237       standard printf-style format string, where the additional arguments to
238       :meth:`log_message` are applied as inputs to the formatting. The client
239       address and current date and time are prefixed to every message logged.
242    .. method:: version_string()
244       Returns the server software's version string. This is a combination of the
245       :attr:`server_version` and :attr:`sys_version` class variables.
248    .. method:: date_time_string([timestamp])
250       Returns the date and time given by *timestamp* (which must be in the
251       format returned by :func:`time.time`), formatted for a message header. If
252       *timestamp* is omitted, it uses the current date and time.
254       The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
256       .. versionadded:: 2.5
257          The *timestamp* parameter.
260    .. method:: log_date_time_string()
262       Returns the current date and time, formatted for logging.
265    .. method:: address_string()
267       Returns the client address, formatted for logging. A name lookup is
268       performed on the client's IP address.
271 More examples
272 -------------
274 To create a server that doesn't run forever, but until some condition is
275 fulfilled::
277    def run_while_true(server_class=BaseHTTPServer.HTTPServer,
278                       handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
279        """
280        This assumes that keep_running() is a function of no arguments which
281        is tested initially and after each request.  If its return value
282        is true, the server continues.
283        """
284        server_address = ('', 8000)
285        httpd = server_class(server_address, handler_class)
286        while keep_running():
287            httpd.handle_request()
290 .. seealso::
292    Module :mod:`CGIHTTPServer`
293       Extended request handler that supports CGI scripts.
295    Module :mod:`SimpleHTTPServer`
296       Basic request handler that limits response to files actually under the
297       document root.