blob: f025b257154a51afb3ab3769cd59974ed99fa743 [file] [log] [blame]
Georg Brandl24420152008-05-26 16:32:26 +00001:mod:`http.server` --- HTTP servers
2===================================
3
4.. module:: http.server
5 :synopsis: HTTP server and request handlers.
6
7
8.. index::
9 pair: WWW; server
10 pair: HTTP; protocol
11 single: URL
12 single: httpd
13
14This module defines classes for implementing HTTP servers (Web servers).
15
16One class, :class:`HTTPServer`, is a :class:`socketserver.TCPServer` subclass.
17It creates and listens at the HTTP socket, dispatching the requests to a
18handler. Code to create and run the server looks like this::
19
20 def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
21 server_address = ('', 8000)
22 httpd = server_class(server_address, handler_class)
23 httpd.serve_forever()
24
25
26.. class:: HTTPServer(server_address, RequestHandlerClass)
27
28 This class builds on the :class:`TCPServer` class by storing the server
29 address as instance variables named :attr:`server_name` and
30 :attr:`server_port`. The server is accessible by the handler, typically
31 through the handler's :attr:`server` instance variable.
32
33
34The :class:`HTTPServer` must be given a *RequestHandlerClass* on instantiation,
35of which this module provides three different variants:
36
37.. class:: BaseHTTPRequestHandler(request, client_address, server)
38
39 This class is used to handle the HTTP requests that arrive at the server. By
40 itself, it cannot respond to any actual HTTP requests; it must be subclassed
41 to handle each request method (e.g. GET or POST).
42 :class:`BaseHTTPRequestHandler` provides a number of class and instance
43 variables, and methods for use by subclasses.
44
45 The handler will parse the request and the headers, then call a method
46 specific to the request type. The method name is constructed from the
47 request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
48 method will be called with no arguments. All of the relevant information is
49 stored in instance variables of the handler. Subclasses should not need to
50 override or extend the :meth:`__init__` method.
51
52 :class:`BaseHTTPRequestHandler` has the following instance variables:
53
54 .. attribute:: client_address
55
56 Contains a tuple of the form ``(host, port)`` referring to the client's
57 address.
58
59 .. attribute:: command
60
61 Contains the command (request type). For example, ``'GET'``.
62
63 .. attribute:: path
64
65 Contains the request path.
66
67 .. attribute:: request_version
68
69 Contains the version string from the request. For example, ``'HTTP/1.0'``.
70
71 .. attribute:: headers
72
73 Holds an instance of the class specified by the :attr:`MessageClass` class
74 variable. This instance parses and manages the headers in the HTTP
75 request.
76
77 .. attribute:: rfile
78
79 Contains an input stream, positioned at the start of the optional input
80 data.
81
82 .. attribute:: wfile
83
84 Contains the output stream for writing a response back to the
85 client. Proper adherence to the HTTP protocol must be used when writing to
86 this stream.
87
88 :class:`BaseHTTPRequestHandler` has the following class variables:
89
90 .. attribute:: server_version
91
92 Specifies the server software version. You may want to override this. The
93 format is multiple whitespace-separated strings, where each string is of
94 the form name[/version]. For example, ``'BaseHTTP/0.2'``.
95
96 .. attribute:: sys_version
97
98 Contains the Python system version, in a form usable by the
99 :attr:`version_string` method and the :attr:`server_version` class
100 variable. For example, ``'Python/1.4'``.
101
102 .. attribute:: error_message_format
103
104 Specifies a format string for building an error response to the client. It
105 uses parenthesized, keyed format specifiers, so the format operand must be
106 a dictionary. The *code* key should be an integer, specifying the numeric
107 HTTP error code value. *message* should be a string containing a
108 (detailed) error message of what occurred, and *explain* should be an
109 explanation of the error code number. Default *message* and *explain*
110 values can found in the *responses* class variable.
111
112 .. attribute:: error_content_type
113
114 Specifies the Content-Type HTTP header of error responses sent to the
115 client. The default value is ``'text/html'``.
116
117 .. attribute:: protocol_version
118
119 This specifies the HTTP protocol version used in responses. If set to
120 ``'HTTP/1.1'``, the server will permit HTTP persistent connections;
121 however, your server *must* then include an accurate ``Content-Length``
122 header (using :meth:`send_header`) in all of its responses to clients.
123 For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
124
125 .. attribute:: MessageClass
126
Georg Brandl83e9f4c2008-06-12 18:52:31 +0000127 Specifies an :class:`email.message.Message`\ -like class to parse HTTP
128 headers. Typically, this is not overridden, and it defaults to
129 :class:`http.client.HTTPMessage`.
Georg Brandl24420152008-05-26 16:32:26 +0000130
131 .. attribute:: responses
132
133 This variable contains a mapping of error code integers to two-element tuples
134 containing a short and long message. For example, ``{code: (shortmessage,
135 longmessage)}``. The *shortmessage* is usually used as the *message* key in an
136 error response, and *longmessage* as the *explain* key (see the
137 :attr:`error_message_format` class variable).
138
139 A :class:`BaseHTTPRequestHandler` instance has the following methods:
140
141 .. method:: handle()
142
143 Calls :meth:`handle_one_request` once (or, if persistent connections are
144 enabled, multiple times) to handle incoming HTTP requests. You should
145 never need to override it; instead, implement appropriate :meth:`do_\*`
146 methods.
147
148 .. method:: handle_one_request()
149
150 This method will parse and dispatch the request to the appropriate
151 :meth:`do_\*` method. You should never need to override it.
152
153 .. method:: send_error(code[, message])
154
155 Sends and logs a complete error reply to the client. The numeric *code*
156 specifies the HTTP error code, with *message* as optional, more specific text. A
157 complete set of headers is sent, followed by text composed using the
158 :attr:`error_message_format` class variable.
159
160 .. method:: send_response(code[, message])
161
162 Sends a response header and logs the accepted request. The HTTP response
163 line is sent, followed by *Server* and *Date* headers. The values for
164 these two headers are picked up from the :meth:`version_string` and
165 :meth:`date_time_string` methods, respectively.
166
167 .. method:: send_header(keyword, value)
168
169 Writes a specific HTTP header to the output stream. *keyword* should
170 specify the header keyword, with *value* specifying its value.
171
172 .. method:: end_headers()
173
174 Sends a blank line, indicating the end of the HTTP headers in the
175 response.
176
177 .. method:: log_request([code[, size]])
178
179 Logs an accepted (successful) request. *code* should specify the numeric
180 HTTP code associated with the response. If a size of the response is
181 available, then it should be passed as the *size* parameter.
182
183 .. method:: log_error(...)
184
185 Logs an error when a request cannot be fulfilled. By default, it passes
186 the message to :meth:`log_message`, so it takes the same arguments
187 (*format* and additional values).
188
189
190 .. method:: log_message(format, ...)
191
192 Logs an arbitrary message to ``sys.stderr``. This is typically overridden
193 to create custom error logging mechanisms. The *format* argument is a
194 standard printf-style format string, where the additional arguments to
195 :meth:`log_message` are applied as inputs to the formatting. The client
196 address and current date and time are prefixed to every message logged.
197
198 .. method:: version_string()
199
200 Returns the server software's version string. This is a combination of the
201 :attr:`server_version` and :attr:`sys_version` class variables.
202
203 .. method:: date_time_string([timestamp])
204
205 Returns the date and time given by *timestamp* (which must be in the
206 format returned by :func:`time.time`), formatted for a message header. If
207 *timestamp* is omitted, it uses the current date and time.
208
209 The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
210
211 .. method:: log_date_time_string()
212
213 Returns the current date and time, formatted for logging.
214
215 .. method:: address_string()
216
217 Returns the client address, formatted for logging. A name lookup is
218 performed on the client's IP address.
219
220
221.. class:: SimpleHTTPRequestHandler(request, client_address, server)
222
223 This class serves files from the current directory and below, directly
224 mapping the directory structure to HTTP requests.
225
226 A lot of the work, such as parsing the request, is done by the base class
227 :class:`BaseHTTPRequestHandler`. This class implements the :func:`do_GET`
228 and :func:`do_HEAD` functions.
229
230 The following are defined as class-level attributes of
231 :class:`SimpleHTTPRequestHandler`:
232
233 .. attribute:: server_version
234
235 This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
236 defined at the module level.
237
238 .. attribute:: extensions_map
239
240 A dictionary mapping suffixes into MIME types. The default is
241 signified by an empty string, and is considered to be
242 ``application/octet-stream``. The mapping is used case-insensitively,
243 and so should contain only lower-cased keys.
244
245 The :class:`SimpleHTTPRequestHandler` class defines the following methods:
246
247 .. method:: do_HEAD()
248
249 This method serves the ``'HEAD'`` request type: it sends the headers it
250 would send for the equivalent ``GET`` request. See the :meth:`do_GET`
251 method for a more complete explanation of the possible headers.
252
253 .. method:: do_GET()
254
255 The request is mapped to a local file by interpreting the request as a
256 path relative to the current working directory.
257
258 If the request was mapped to a directory, the directory is checked for a
259 file named ``index.html`` or ``index.htm`` (in that order). If found, the
260 file's contents are returned; otherwise a directory listing is generated
261 by calling the :meth:`list_directory` method. This method uses
262 :func:`os.listdir` to scan the directory, and returns a ``404`` error
263 response if the :func:`listdir` fails.
264
265 If the request was mapped to a file, it is opened and the contents are
266 returned. Any :exc:`IOError` exception in opening the requested file is
267 mapped to a ``404``, ``'File not found'`` error. Otherwise, the content
268 type is guessed by calling the :meth:`guess_type` method, which in turn
269 uses the *extensions_map* variable.
270
271 A ``'Content-type:'`` header with the guessed content type is output,
272 followed by a ``'Content-Length:'`` header with the file's size and a
273 ``'Last-Modified:'`` header with the file's modification time.
274
275 Then follows a blank line signifying the end of the headers, and then the
276 contents of the file are output. If the file's MIME type starts with
277 ``text/`` the file is opened in text mode; otherwise binary mode is used.
278
279 For example usage, see the implementation of the :func:`test` function.
280
281
282.. class:: CGIHTTPRequestHandler(request, client_address, server)
283
284 This class is used to serve either files or output of CGI scripts from the
285 current directory and below. Note that mapping HTTP hierarchic structure to
286 local directory structure is exactly as in :class:`SimpleHTTPRequestHandler`.
287
288 .. note::
289
290 CGI scripts run by the :class:`CGIHTTPRequestHandler` class cannot execute
291 redirects (HTTP code 302), because code 200 (script output follows) is
292 sent prior to execution of the CGI script. This pre-empts the status
293 code.
294
295 The class will however, run the CGI script, instead of serving it as a file,
296 if it guesses it to be a CGI script. Only directory-based CGI are used ---
297 the other common server configuration is to treat special extensions as
298 denoting CGI scripts.
299
300 The :func:`do_GET` and :func:`do_HEAD` functions are modified to run CGI scripts
301 and serve the output, instead of serving files, if the request leads to
302 somewhere below the ``cgi_directories`` path.
303
304 The :class:`CGIHTTPRequestHandler` defines the following data member:
305
306 .. attribute:: cgi_directories
307
308 This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
309 treat as containing CGI scripts.
310
311 The :class:`CGIHTTPRequestHandler` defines the following method:
312
313 .. method:: do_POST()
314
315 This method serves the ``'POST'`` request type, only allowed for CGI
316 scripts. Error 501, "Can only POST to CGI scripts", is output when trying
317 to POST to a non-CGI url.
318
319 Note that CGI scripts will be run with UID of user nobody, for security
320 reasons. Problems with the CGI script will be translated to error 403.