source: python/trunk/Doc/library/basehttpserver.rst

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

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