1
:mod:`http.server` --- HTTP servers
2
===================================
4
.. module:: http.server
5
:synopsis: HTTP server and request handlers.
7
**Source code:** :source:`Lib/http/server.py`
17
This module defines classes for implementing HTTP servers (Web servers).
19
One class, :class:`HTTPServer`, is a :class:`socketserver.TCPServer` subclass.
20
It creates and listens at the HTTP socket, dispatching the requests to a
21
handler. Code to create and run the server looks like this::
23
def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
24
server_address = ('', 8000)
25
httpd = server_class(server_address, handler_class)
29
.. class:: HTTPServer(server_address, RequestHandlerClass)
31
This class builds on the :class:`~socketserver.TCPServer` class by storing
32
the server address as instance variables named :attr:`server_name` and
33
:attr:`server_port`. The server is accessible by the handler, typically
34
through the handler's :attr:`server` instance variable.
37
The :class:`HTTPServer` must be given a *RequestHandlerClass* on instantiation,
38
of which this module provides three different variants:
40
.. class:: BaseHTTPRequestHandler(request, client_address, server)
42
This class is used to handle the HTTP requests that arrive at the server. By
43
itself, it cannot respond to any actual HTTP requests; it must be subclassed
44
to handle each request method (e.g. GET or POST).
45
:class:`BaseHTTPRequestHandler` provides a number of class and instance
46
variables, and methods for use by subclasses.
48
The handler will parse the request and the headers, then call a method
49
specific to the request type. The method name is constructed from the
50
request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
51
method will be called with no arguments. All of the relevant information is
52
stored in instance variables of the handler. Subclasses should not need to
53
override or extend the :meth:`__init__` method.
55
:class:`BaseHTTPRequestHandler` has the following instance variables:
57
.. attribute:: client_address
59
Contains a tuple of the form ``(host, port)`` referring to the client's
64
Contains the server instance.
66
.. attribute:: close_connection
68
Boolean that should be set before :meth:`handle_one_request` returns,
69
indicating if another request may be expected, or if the connection should
72
.. attribute:: requestline
74
Contains the string representation of the HTTP request line. The
75
terminating CRLF is stripped. This attribute should be set by
76
:meth:`handle_one_request`. If no valid request line was processed, it
77
should be set to the empty string.
79
.. attribute:: command
81
Contains the command (request type). For example, ``'GET'``.
85
Contains the request path.
87
.. attribute:: request_version
89
Contains the version string from the request. For example, ``'HTTP/1.0'``.
91
.. attribute:: headers
93
Holds an instance of the class specified by the :attr:`MessageClass` class
94
variable. This instance parses and manages the headers in the HTTP
95
request. The :func:`~http.client.parse_headers` function from
96
:mod:`http.client` is used to parse the headers and it requires that the
97
HTTP request provide a valid :rfc:`2822` style header.
101
Contains an input stream, positioned at the start of the optional input
106
Contains the output stream for writing a response back to the
107
client. Proper adherence to the HTTP protocol must be used when writing to
110
:class:`BaseHTTPRequestHandler` has the following attributes:
112
.. attribute:: server_version
114
Specifies the server software version. You may want to override this. The
115
format is multiple whitespace-separated strings, where each string is of
116
the form name[/version]. For example, ``'BaseHTTP/0.2'``.
118
.. attribute:: sys_version
120
Contains the Python system version, in a form usable by the
121
:attr:`version_string` method and the :attr:`server_version` class
122
variable. For example, ``'Python/1.4'``.
124
.. attribute:: error_message_format
126
Specifies a format string that should be used by :meth:`send_error` method
127
for building an error response to the client. The string is filled by
128
default with variables from :attr:`responses` based on the status code
129
that passed to :meth:`send_error`.
131
.. attribute:: error_content_type
133
Specifies the Content-Type HTTP header of error responses sent to the
134
client. The default value is ``'text/html'``.
136
.. attribute:: protocol_version
138
This specifies the HTTP protocol version used in responses. If set to
139
``'HTTP/1.1'``, the server will permit HTTP persistent connections;
140
however, your server *must* then include an accurate ``Content-Length``
141
header (using :meth:`send_header`) in all of its responses to clients.
142
For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
144
.. attribute:: MessageClass
146
Specifies an :class:`email.message.Message`\ -like class to parse HTTP
147
headers. Typically, this is not overridden, and it defaults to
148
:class:`http.client.HTTPMessage`.
150
.. attribute:: responses
152
This attribute contains a mapping of error code integers to two-element tuples
153
containing a short and long message. For example, ``{code: (shortmessage,
154
longmessage)}``. The *shortmessage* is usually used as the *message* key in an
155
error response, and *longmessage* as the *explain* key. It is used by
156
:meth:`send_response_only` and :meth:`send_error` methods.
158
A :class:`BaseHTTPRequestHandler` instance has the following methods:
162
Calls :meth:`handle_one_request` once (or, if persistent connections are
163
enabled, multiple times) to handle incoming HTTP requests. You should
164
never need to override it; instead, implement appropriate :meth:`do_\*`
167
.. method:: handle_one_request()
169
This method will parse and dispatch the request to the appropriate
170
:meth:`do_\*` method. You should never need to override it.
172
.. method:: handle_expect_100()
174
When a HTTP/1.1 compliant server receives an ``Expect: 100-continue``
175
request header it responds back with a ``100 Continue`` followed by ``200
177
This method can be overridden to raise an error if the server does not
178
want the client to continue. For e.g. server can chose to send ``417
179
Expectation Failed`` as a response header and ``return False``.
181
.. versionadded:: 3.2
183
.. method:: send_error(code, message=None, explain=None)
185
Sends and logs a complete error reply to the client. The numeric *code*
186
specifies the HTTP error code, with *message* as an optional, short, human
187
readable description of the error. The *explain* argument can be used to
188
provide more detailed information about the error; it will be formatted
189
using the :attr:`error_message_format` attribute and emitted, after
190
a complete set of headers, as the response body. The :attr:`responses`
191
attribute holds the default values for *message* and *explain* that
192
will be used if no value is provided; for unknown codes the default value
193
for both is the string ``???``. The body will be empty if the method is
194
HEAD or the response code is one of the following: ``1xx``,
195
``204 No Content``, ``205 Reset Content``, ``304 Not Modified``.
197
.. versionchanged:: 3.4
198
The error response includes a Content-Length header.
199
Added the *explain* argument.
201
.. method:: send_response(code, message=None)
203
Adds a response header to the headers buffer and logs the accepted
204
request. The HTTP response line is written to the internal buffer,
205
followed by *Server* and *Date* headers. The values for these two headers
206
are picked up from the :meth:`version_string` and
207
:meth:`date_time_string` methods, respectively. If the server does not
208
intend to send any other headers using the :meth:`send_header` method,
209
then :meth:`send_response` should be followed by an :meth:`end_headers`
212
.. versionchanged:: 3.3
213
Headers are stored to an internal buffer and :meth:`end_headers`
214
needs to be called explicitly.
216
.. method:: send_header(keyword, value)
218
Adds the HTTP header to an internal buffer which will be written to the
219
output stream when either :meth:`end_headers` or :meth:`flush_headers` is
220
invoked. *keyword* should specify the header keyword, with *value*
221
specifying its value. Note that, after the send_header calls are done,
222
:meth:`end_headers` MUST BE called in order to complete the operation.
224
.. versionchanged:: 3.2
225
Headers are stored in an internal buffer.
227
.. method:: send_response_only(code, message=None)
229
Sends the response header only, used for the purposes when ``100
230
Continue`` response is sent by the server to the client. The headers not
231
buffered and sent directly the output stream.If the *message* is not
232
specified, the HTTP message corresponding the response *code* is sent.
234
.. versionadded:: 3.2
236
.. method:: end_headers()
239
(indicating the end of the HTTP headers in the response)
240
to the headers buffer and calls :meth:`flush_headers()`.
242
.. versionchanged:: 3.2
243
The buffered headers are written to the output stream.
245
.. method:: flush_headers()
247
Finally send the headers to the output stream and flush the internal
250
.. versionadded:: 3.3
252
.. method:: log_request(code='-', size='-')
254
Logs an accepted (successful) request. *code* should specify the numeric
255
HTTP code associated with the response. If a size of the response is
256
available, then it should be passed as the *size* parameter.
258
.. method:: log_error(...)
260
Logs an error when a request cannot be fulfilled. By default, it passes
261
the message to :meth:`log_message`, so it takes the same arguments
262
(*format* and additional values).
265
.. method:: log_message(format, ...)
267
Logs an arbitrary message to ``sys.stderr``. This is typically overridden
268
to create custom error logging mechanisms. The *format* argument is a
269
standard printf-style format string, where the additional arguments to
270
:meth:`log_message` are applied as inputs to the formatting. The client
271
ip address and current date and time are prefixed to every message logged.
273
.. method:: version_string()
275
Returns the server software's version string. This is a combination of the
276
:attr:`server_version` and :attr:`sys_version` attributes.
278
.. method:: date_time_string(timestamp=None)
280
Returns the date and time given by *timestamp* (which must be ``None`` or in
281
the format returned by :func:`time.time`), formatted for a message
282
header. If *timestamp* is omitted, it uses the current date and time.
284
The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
286
.. method:: log_date_time_string()
288
Returns the current date and time, formatted for logging.
290
.. method:: address_string()
292
Returns the client address.
294
.. versionchanged:: 3.3
295
Previously, a name lookup was performed. To avoid name resolution
296
delays, it now always returns the IP address.
299
.. class:: SimpleHTTPRequestHandler(request, client_address, server)
301
This class serves files from the current directory and below, directly
302
mapping the directory structure to HTTP requests.
304
A lot of the work, such as parsing the request, is done by the base class
305
:class:`BaseHTTPRequestHandler`. This class implements the :func:`do_GET`
306
and :func:`do_HEAD` functions.
308
The following are defined as class-level attributes of
309
:class:`SimpleHTTPRequestHandler`:
311
.. attribute:: server_version
313
This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
314
defined at the module level.
316
.. attribute:: extensions_map
318
A dictionary mapping suffixes into MIME types. The default is
319
signified by an empty string, and is considered to be
320
``application/octet-stream``. The mapping is used case-insensitively,
321
and so should contain only lower-cased keys.
323
The :class:`SimpleHTTPRequestHandler` class defines the following methods:
325
.. method:: do_HEAD()
327
This method serves the ``'HEAD'`` request type: it sends the headers it
328
would send for the equivalent ``GET`` request. See the :meth:`do_GET`
329
method for a more complete explanation of the possible headers.
333
The request is mapped to a local file by interpreting the request as a
334
path relative to the current working directory.
336
If the request was mapped to a directory, the directory is checked for a
337
file named ``index.html`` or ``index.htm`` (in that order). If found, the
338
file's contents are returned; otherwise a directory listing is generated
339
by calling the :meth:`list_directory` method. This method uses
340
:func:`os.listdir` to scan the directory, and returns a ``404`` error
341
response if the :func:`~os.listdir` fails.
343
If the request was mapped to a file, it is opened and the contents are
344
returned. Any :exc:`OSError` exception in opening the requested file is
345
mapped to a ``404``, ``'File not found'`` error. Otherwise, the content
346
type is guessed by calling the :meth:`guess_type` method, which in turn
347
uses the *extensions_map* variable.
349
A ``'Content-type:'`` header with the guessed content type is output,
350
followed by a ``'Content-Length:'`` header with the file's size and a
351
``'Last-Modified:'`` header with the file's modification time.
353
Then follows a blank line signifying the end of the headers, and then the
354
contents of the file are output. If the file's MIME type starts with
355
``text/`` the file is opened in text mode; otherwise binary mode is used.
357
For example usage, see the implementation of the :func:`test` function
358
invocation in the :mod:`http.server` module.
361
The :class:`SimpleHTTPRequestHandler` class can be used in the following
362
manner in order to create a very basic webserver serving files relative to
363
the current directory::
370
Handler = http.server.SimpleHTTPRequestHandler
372
httpd = socketserver.TCPServer(("", PORT), Handler)
374
print("serving at port", PORT)
375
httpd.serve_forever()
379
:mod:`http.server` can also be invoked directly using the :option:`-m`
380
switch of the interpreter with a ``port number`` argument. Similar to
381
the previous example, this serves files relative to the current directory::
383
python -m http.server 8000
385
By default, server binds itself to all interfaces. The option ``-b/--bind``
386
specifies a specific address to which it should bind. For example, the
387
following command causes the server to bind to localhost only::
389
python -m http.server 8000 --bind 127.0.0.1
391
.. versionadded:: 3.4
392
``--bind`` argument was introduced.
395
.. class:: CGIHTTPRequestHandler(request, client_address, server)
397
This class is used to serve either files or output of CGI scripts from the
398
current directory and below. Note that mapping HTTP hierarchic structure to
399
local directory structure is exactly as in :class:`SimpleHTTPRequestHandler`.
403
CGI scripts run by the :class:`CGIHTTPRequestHandler` class cannot execute
404
redirects (HTTP code 302), because code 200 (script output follows) is
405
sent prior to execution of the CGI script. This pre-empts the status
408
The class will however, run the CGI script, instead of serving it as a file,
409
if it guesses it to be a CGI script. Only directory-based CGI are used ---
410
the other common server configuration is to treat special extensions as
411
denoting CGI scripts.
413
The :func:`do_GET` and :func:`do_HEAD` functions are modified to run CGI scripts
414
and serve the output, instead of serving files, if the request leads to
415
somewhere below the ``cgi_directories`` path.
417
The :class:`CGIHTTPRequestHandler` defines the following data member:
419
.. attribute:: cgi_directories
421
This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
422
treat as containing CGI scripts.
424
The :class:`CGIHTTPRequestHandler` defines the following method:
426
.. method:: do_POST()
428
This method serves the ``'POST'`` request type, only allowed for CGI
429
scripts. Error 501, "Can only POST to CGI scripts", is output when trying
430
to POST to a non-CGI url.
432
Note that CGI scripts will be run with UID of user nobody, for security
433
reasons. Problems with the CGI script will be translated to error 403.
435
:class:`CGIHTTPRequestHandler` can be enabled in the command line by passing
436
the ``--cgi`` option::
438
python -m http.server --cgi 8000