blob: 1c3e20260936cfb4c1b8327c10573aa243803111 [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
Raymond Hettinger469271d2011-01-27 20:38:46 +000014**Source code:** :source:`Lib/http/server.py`
15
16--------------
17
Georg Brandl24420152008-05-26 16:32:26 +000018This module defines classes for implementing HTTP servers (Web servers).
19
20One class, :class:`HTTPServer`, is a :class:`socketserver.TCPServer` subclass.
21It creates and listens at the HTTP socket, dispatching the requests to a
22handler. Code to create and run the server looks like this::
23
24 def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
25 server_address = ('', 8000)
26 httpd = server_class(server_address, handler_class)
27 httpd.serve_forever()
28
29
30.. class:: HTTPServer(server_address, RequestHandlerClass)
31
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030032 This class builds on the :class:`~socketserver.TCPServer` class by storing
33 the server address as instance variables named :attr:`server_name` and
Georg Brandl24420152008-05-26 16:32:26 +000034 :attr:`server_port`. The server is accessible by the handler, typically
35 through the handler's :attr:`server` instance variable.
36
37
38The :class:`HTTPServer` must be given a *RequestHandlerClass* on instantiation,
39of which this module provides three different variants:
40
41.. class:: BaseHTTPRequestHandler(request, client_address, server)
42
43 This class is used to handle the HTTP requests that arrive at the server. By
44 itself, it cannot respond to any actual HTTP requests; it must be subclassed
45 to handle each request method (e.g. GET or POST).
46 :class:`BaseHTTPRequestHandler` provides a number of class and instance
47 variables, and methods for use by subclasses.
48
49 The handler will parse the request and the headers, then call a method
50 specific to the request type. The method name is constructed from the
51 request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
52 method will be called with no arguments. All of the relevant information is
53 stored in instance variables of the handler. Subclasses should not need to
54 override or extend the :meth:`__init__` method.
55
56 :class:`BaseHTTPRequestHandler` has the following instance variables:
57
58 .. attribute:: client_address
59
60 Contains a tuple of the form ``(host, port)`` referring to the client's
61 address.
62
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000063 .. attribute:: server
64
65 Contains the server instance.
66
Benjamin Peterson70e28472015-02-17 21:11:10 -050067 .. attribute:: close_connection
68
69 Boolean that should be set before :meth:`handle_one_request` returns,
70 indicating if another request may be expected, or if the connection should
71 be shut down.
72
73 .. attribute:: requestline
74
75 Contains the string representation of the HTTP request line. The
76 terminating CRLF is stripped. This attribute should be set by
77 :meth:`handle_one_request`. If no valid request line was processed, it
78 should be set to the empty string.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000079
Georg Brandl24420152008-05-26 16:32:26 +000080 .. attribute:: command
81
82 Contains the command (request type). For example, ``'GET'``.
83
84 .. attribute:: path
85
86 Contains the request path.
87
88 .. attribute:: request_version
89
90 Contains the version string from the request. For example, ``'HTTP/1.0'``.
91
92 .. attribute:: headers
93
94 Holds an instance of the class specified by the :attr:`MessageClass` class
95 variable. This instance parses and manages the headers in the HTTP
Senthil Kumarancad2bf22014-04-16 13:56:19 -040096 request. The :func:`~http.client.parse_headers` function from
97 :mod:`http.client` is used to parse the headers and it requires that the
98 HTTP request provide a valid :rfc:`2822` style header.
99
Georg Brandl24420152008-05-26 16:32:26 +0000100
101 .. attribute:: rfile
102
103 Contains an input stream, positioned at the start of the optional input
104 data.
105
106 .. attribute:: wfile
107
108 Contains the output stream for writing a response back to the
109 client. Proper adherence to the HTTP protocol must be used when writing to
110 this stream.
111
112 :class:`BaseHTTPRequestHandler` has the following class variables:
113
114 .. attribute:: server_version
115
116 Specifies the server software version. You may want to override this. The
117 format is multiple whitespace-separated strings, where each string is of
118 the form name[/version]. For example, ``'BaseHTTP/0.2'``.
119
120 .. attribute:: sys_version
121
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'``.
125
126 .. attribute:: error_message_format
127
128 Specifies a format string for building an error response to the client. It
129 uses parenthesized, keyed format specifiers, so the format operand must be
130 a dictionary. The *code* key should be an integer, specifying the numeric
131 HTTP error code value. *message* should be a string containing a
132 (detailed) error message of what occurred, and *explain* should be an
133 explanation of the error code number. Default *message* and *explain*
R David Murraya475a8d2014-01-03 13:03:00 -0500134 values can found in the :attr:`responses` class variable.
Georg Brandl24420152008-05-26 16:32:26 +0000135
136 .. attribute:: error_content_type
137
138 Specifies the Content-Type HTTP header of error responses sent to the
139 client. The default value is ``'text/html'``.
140
141 .. attribute:: protocol_version
142
143 This specifies the HTTP protocol version used in responses. If set to
144 ``'HTTP/1.1'``, the server will permit HTTP persistent connections;
145 however, your server *must* then include an accurate ``Content-Length``
146 header (using :meth:`send_header`) in all of its responses to clients.
147 For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
148
149 .. attribute:: MessageClass
150
Georg Brandl83e9f4c2008-06-12 18:52:31 +0000151 Specifies an :class:`email.message.Message`\ -like class to parse HTTP
152 headers. Typically, this is not overridden, and it defaults to
153 :class:`http.client.HTTPMessage`.
Georg Brandl24420152008-05-26 16:32:26 +0000154
155 .. attribute:: responses
156
157 This variable contains a mapping of error code integers to two-element tuples
158 containing a short and long message. For example, ``{code: (shortmessage,
159 longmessage)}``. The *shortmessage* is usually used as the *message* key in an
160 error response, and *longmessage* as the *explain* key (see the
161 :attr:`error_message_format` class variable).
162
163 A :class:`BaseHTTPRequestHandler` instance has the following methods:
164
165 .. method:: handle()
166
167 Calls :meth:`handle_one_request` once (or, if persistent connections are
168 enabled, multiple times) to handle incoming HTTP requests. You should
169 never need to override it; instead, implement appropriate :meth:`do_\*`
170 methods.
171
172 .. method:: handle_one_request()
173
174 This method will parse and dispatch the request to the appropriate
175 :meth:`do_\*` method. You should never need to override it.
176
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000177 .. method:: handle_expect_100()
178
179 When a HTTP/1.1 compliant server receives a ``Expect: 100-continue``
180 request header it responds back with a ``100 Continue`` followed by ``200
181 OK`` headers.
182 This method can be overridden to raise an error if the server does not
183 want the client to continue. For e.g. server can chose to send ``417
184 Expectation Failed`` as a response header and ``return False``.
185
186 .. versionadded:: 3.2
187
Senthil Kumaran26886442013-03-15 07:53:21 -0700188 .. method:: send_error(code, message=None, explain=None)
Georg Brandl24420152008-05-26 16:32:26 +0000189
190 Sends and logs a complete error reply to the client. The numeric *code*
R David Murraya475a8d2014-01-03 13:03:00 -0500191 specifies the HTTP error code, with *message* as an optional, short, human
192 readable description of the error. The *explain* argument can be used to
193 provide more detailed information about the error; it will be formatted
194 using the :attr:`error_message_format` class variable and emitted, after
195 a complete set of headers, as the response body. The :attr:`responses`
196 class variable holds the default values for *message* and *explain* that
197 will be used if no value is provided; for unknown codes the default value
198 for both is the string ``???``.
Georg Brandl24420152008-05-26 16:32:26 +0000199
Senthil Kumaran52d27202012-10-10 23:16:21 -0700200 .. versionchanged:: 3.4
201 The error response includes a Content-Length header.
Ezio Melotti2acd2932013-03-16 22:23:30 +0200202 Added the *explain* argument.
Senthil Kumaran26886442013-03-15 07:53:21 -0700203
Senthil Kumaran52d27202012-10-10 23:16:21 -0700204
Georg Brandl036490d2009-05-17 13:00:36 +0000205 .. method:: send_response(code, message=None)
Georg Brandl24420152008-05-26 16:32:26 +0000206
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800207 Adds a response header to the headers buffer and logs the accepted
Senthil Kumarancc995282011-05-11 16:04:28 +0800208 request. The HTTP response line is written to the internal buffer,
209 followed by *Server* and *Date* headers. The values for these two headers
210 are picked up from the :meth:`version_string` and
211 :meth:`date_time_string` methods, respectively. If the server does not
212 intend to send any other headers using the :meth:`send_header` method,
Ezio Melottie9c7d6c2011-05-12 01:10:57 +0300213 then :meth:`send_response` should be followed by a :meth:`end_headers`
214 call.
Senthil Kumarancc995282011-05-11 16:04:28 +0800215
Ezio Melottie9c7d6c2011-05-12 01:10:57 +0300216 .. versionchanged:: 3.3
217 Headers are stored to an internal buffer and :meth:`end_headers`
218 needs to be called explicitly.
Senthil Kumarancc995282011-05-11 16:04:28 +0800219
Georg Brandl24420152008-05-26 16:32:26 +0000220
221 .. method:: send_header(keyword, value)
222
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800223 Adds the HTTP header to an internal buffer which will be written to the
Senthil Kumaran6ea17a82011-05-11 11:45:48 +0800224 output stream when either :meth:`end_headers` or :meth:`flush_headers` is
225 invoked. *keyword* should specify the header keyword, with *value*
226 specifying its value. Note that, after the send_header calls are done,
227 :meth:`end_headers` MUST BE called in order to complete the operation.
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000228
Georg Brandl61063cc2012-06-24 22:48:30 +0200229 .. versionchanged:: 3.2
230 Headers are stored in an internal buffer.
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000231
Georg Brandl24420152008-05-26 16:32:26 +0000232
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000233 .. method:: send_response_only(code, message=None)
234
Donald Stufft8b852f12014-05-20 12:58:38 -0400235 Sends the response header only, used for the purposes when ``100
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000236 Continue`` response is sent by the server to the client. The headers not
237 buffered and sent directly the output stream.If the *message* is not
238 specified, the HTTP message corresponding the response *code* is sent.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000239
240 .. versionadded:: 3.2
241
Georg Brandl24420152008-05-26 16:32:26 +0000242 .. method:: end_headers()
243
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800244 Adds a blank line
245 (indicating the end of the HTTP headers in the response)
Ezio Melottie9c7d6c2011-05-12 01:10:57 +0300246 to the headers buffer and calls :meth:`flush_headers()`.
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000247
Ezio Melottie9c7d6c2011-05-12 01:10:57 +0300248 .. versionchanged:: 3.2
249 The buffered headers are written to the output stream.
Georg Brandl24420152008-05-26 16:32:26 +0000250
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800251 .. method:: flush_headers()
252
253 Finally send the headers to the output stream and flush the internal
254 headers buffer.
255
256 .. versionadded:: 3.3
257
Georg Brandl036490d2009-05-17 13:00:36 +0000258 .. method:: log_request(code='-', size='-')
Georg Brandl24420152008-05-26 16:32:26 +0000259
260 Logs an accepted (successful) request. *code* should specify the numeric
261 HTTP code associated with the response. If a size of the response is
262 available, then it should be passed as the *size* parameter.
263
264 .. method:: log_error(...)
265
266 Logs an error when a request cannot be fulfilled. By default, it passes
267 the message to :meth:`log_message`, so it takes the same arguments
268 (*format* and additional values).
269
270
271 .. method:: log_message(format, ...)
272
273 Logs an arbitrary message to ``sys.stderr``. This is typically overridden
274 to create custom error logging mechanisms. The *format* argument is a
275 standard printf-style format string, where the additional arguments to
276 :meth:`log_message` are applied as inputs to the formatting. The client
Senthil Kumarandb727b42012-04-29 13:41:03 +0800277 ip address and current date and time are prefixed to every message logged.
Georg Brandl24420152008-05-26 16:32:26 +0000278
279 .. method:: version_string()
280
281 Returns the server software's version string. This is a combination of the
282 :attr:`server_version` and :attr:`sys_version` class variables.
283
Georg Brandl036490d2009-05-17 13:00:36 +0000284 .. method:: date_time_string(timestamp=None)
Georg Brandl24420152008-05-26 16:32:26 +0000285
Georg Brandl036490d2009-05-17 13:00:36 +0000286 Returns the date and time given by *timestamp* (which must be None or in
287 the format returned by :func:`time.time`), formatted for a message
288 header. If *timestamp* is omitted, it uses the current date and time.
Georg Brandl24420152008-05-26 16:32:26 +0000289
290 The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
291
292 .. method:: log_date_time_string()
293
294 Returns the current date and time, formatted for logging.
295
296 .. method:: address_string()
297
Senthil Kumaran1aacba42012-04-29 12:51:54 +0800298 Returns the client address.
299
300 .. versionchanged:: 3.3
301 Previously, a name lookup was performed. To avoid name resolution
302 delays, it now always returns the IP address.
Georg Brandl24420152008-05-26 16:32:26 +0000303
304
305.. class:: SimpleHTTPRequestHandler(request, client_address, server)
306
307 This class serves files from the current directory and below, directly
308 mapping the directory structure to HTTP requests.
309
310 A lot of the work, such as parsing the request, is done by the base class
311 :class:`BaseHTTPRequestHandler`. This class implements the :func:`do_GET`
312 and :func:`do_HEAD` functions.
313
314 The following are defined as class-level attributes of
315 :class:`SimpleHTTPRequestHandler`:
316
317 .. attribute:: server_version
318
319 This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
320 defined at the module level.
321
322 .. attribute:: extensions_map
323
324 A dictionary mapping suffixes into MIME types. The default is
325 signified by an empty string, and is considered to be
326 ``application/octet-stream``. The mapping is used case-insensitively,
327 and so should contain only lower-cased keys.
328
329 The :class:`SimpleHTTPRequestHandler` class defines the following methods:
330
331 .. method:: do_HEAD()
332
333 This method serves the ``'HEAD'`` request type: it sends the headers it
334 would send for the equivalent ``GET`` request. See the :meth:`do_GET`
335 method for a more complete explanation of the possible headers.
336
337 .. method:: do_GET()
338
339 The request is mapped to a local file by interpreting the request as a
340 path relative to the current working directory.
341
342 If the request was mapped to a directory, the directory is checked for a
343 file named ``index.html`` or ``index.htm`` (in that order). If found, the
344 file's contents are returned; otherwise a directory listing is generated
345 by calling the :meth:`list_directory` method. This method uses
346 :func:`os.listdir` to scan the directory, and returns a ``404`` error
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300347 response if the :func:`~os.listdir` fails.
Georg Brandl24420152008-05-26 16:32:26 +0000348
349 If the request was mapped to a file, it is opened and the contents are
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200350 returned. Any :exc:`OSError` exception in opening the requested file is
Georg Brandl24420152008-05-26 16:32:26 +0000351 mapped to a ``404``, ``'File not found'`` error. Otherwise, the content
352 type is guessed by calling the :meth:`guess_type` method, which in turn
353 uses the *extensions_map* variable.
354
355 A ``'Content-type:'`` header with the guessed content type is output,
356 followed by a ``'Content-Length:'`` header with the file's size and a
357 ``'Last-Modified:'`` header with the file's modification time.
358
359 Then follows a blank line signifying the end of the headers, and then the
360 contents of the file are output. If the file's MIME type starts with
361 ``text/`` the file is opened in text mode; otherwise binary mode is used.
362
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000363 For example usage, see the implementation of the :func:`test` function
364 invocation in the :mod:`http.server` module.
Georg Brandl24420152008-05-26 16:32:26 +0000365
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000366
Georg Brandl8971f742010-07-02 07:41:51 +0000367The :class:`SimpleHTTPRequestHandler` class can be used in the following
368manner in order to create a very basic webserver serving files relative to
Larry Hastings3732ed22014-03-15 21:13:56 -0700369the current directory::
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000370
Georg Brandl8971f742010-07-02 07:41:51 +0000371 import http.server
372 import socketserver
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000373
Georg Brandl8971f742010-07-02 07:41:51 +0000374 PORT = 8000
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000375
Georg Brandl8971f742010-07-02 07:41:51 +0000376 Handler = http.server.SimpleHTTPRequestHandler
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000377
Georg Brandl8971f742010-07-02 07:41:51 +0000378 httpd = socketserver.TCPServer(("", PORT), Handler)
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000379
Georg Brandl8971f742010-07-02 07:41:51 +0000380 print("serving at port", PORT)
381 httpd.serve_forever()
382
Larry Hastings3732ed22014-03-15 21:13:56 -0700383.. _http-server-cli:
384
Georg Brandlf68798b2010-07-03 10:22:10 +0000385:mod:`http.server` can also be invoked directly using the :option:`-m`
R David Murraye7bade52012-04-11 20:13:25 -0400386switch of the interpreter with a ``port number`` argument. Similar to
Larry Hastings3732ed22014-03-15 21:13:56 -0700387the previous example, this serves files relative to the current directory::
Senthil Kumaran97db43b2010-06-16 16:41:11 +0000388
389 python -m http.server 8000
Georg Brandl24420152008-05-26 16:32:26 +0000390
Larry Hastings3732ed22014-03-15 21:13:56 -0700391By default, server binds itself to all interfaces. The option ``-b/--bind``
392specifies a specific address to which it should bind. For example, the
393following command causes the server to bind to localhost only::
Senthil Kumarandefe7f42013-09-15 09:37:27 -0700394
395 python -m http.server 8000 --bind 127.0.0.1
396
397.. versionadded:: 3.4
398 ``--bind`` argument was introduced.
399
Georg Brandl8971f742010-07-02 07:41:51 +0000400
Georg Brandl24420152008-05-26 16:32:26 +0000401.. class:: CGIHTTPRequestHandler(request, client_address, server)
402
403 This class is used to serve either files or output of CGI scripts from the
404 current directory and below. Note that mapping HTTP hierarchic structure to
405 local directory structure is exactly as in :class:`SimpleHTTPRequestHandler`.
406
407 .. note::
408
409 CGI scripts run by the :class:`CGIHTTPRequestHandler` class cannot execute
410 redirects (HTTP code 302), because code 200 (script output follows) is
411 sent prior to execution of the CGI script. This pre-empts the status
412 code.
413
414 The class will however, run the CGI script, instead of serving it as a file,
415 if it guesses it to be a CGI script. Only directory-based CGI are used ---
416 the other common server configuration is to treat special extensions as
417 denoting CGI scripts.
418
419 The :func:`do_GET` and :func:`do_HEAD` functions are modified to run CGI scripts
420 and serve the output, instead of serving files, if the request leads to
421 somewhere below the ``cgi_directories`` path.
422
423 The :class:`CGIHTTPRequestHandler` defines the following data member:
424
425 .. attribute:: cgi_directories
426
427 This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
428 treat as containing CGI scripts.
429
430 The :class:`CGIHTTPRequestHandler` defines the following method:
431
432 .. method:: do_POST()
433
434 This method serves the ``'POST'`` request type, only allowed for CGI
435 scripts. Error 501, "Can only POST to CGI scripts", is output when trying
436 to POST to a non-CGI url.
437
438 Note that CGI scripts will be run with UID of user nobody, for security
439 reasons. Problems with the CGI script will be translated to error 403.
Senthil Kumaran1251faf2012-06-03 16:15:54 +0800440
441:class:`CGIHTTPRequestHandler` can be enabled in the command line by passing
Larry Hastings3732ed22014-03-15 21:13:56 -0700442the ``--cgi`` option::
Senthil Kumaran1251faf2012-06-03 16:15:54 +0800443
444 python -m http.server --cgi 8000
445