• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`http.server` --- HTTP servers
2===================================
3
4.. module:: http.server
5   :synopsis: HTTP server and request handlers.
6
7**Source code:** :source:`Lib/http/server.py`
8
9.. index::
10   pair: WWW; server
11   pair: HTTP; protocol
12   single: URL
13   single: httpd
14
15--------------
16
17This module defines classes for implementing HTTP servers (Web servers).
18
19
20.. warning::
21
22    :mod:`http.server` is not recommended for production. It only implements
23    basic security checks.
24
25One class, :class:`HTTPServer`, is a :class:`socketserver.TCPServer` subclass.
26It creates and listens at the HTTP socket, dispatching the requests to a
27handler.  Code to create and run the server looks like this::
28
29   def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
30       server_address = ('', 8000)
31       httpd = server_class(server_address, handler_class)
32       httpd.serve_forever()
33
34
35.. class:: HTTPServer(server_address, RequestHandlerClass)
36
37   This class builds on the :class:`~socketserver.TCPServer` class by storing
38   the server address as instance variables named :attr:`server_name` and
39   :attr:`server_port`. The server is accessible by the handler, typically
40   through the handler's :attr:`server` instance variable.
41
42.. class:: ThreadingHTTPServer(server_address, RequestHandlerClass)
43
44   This class is identical to HTTPServer but uses threads to handle
45   requests by using the :class:`~socketserver.ThreadingMixIn`. This
46   is useful to handle web browsers pre-opening sockets, on which
47   :class:`HTTPServer` would wait indefinitely.
48
49   .. versionadded:: 3.7
50
51
52The :class:`HTTPServer` and :class:`ThreadingHTTPServer` must be given
53a *RequestHandlerClass* on instantiation, of which this module
54provides three different variants:
55
56.. class:: BaseHTTPRequestHandler(request, client_address, server)
57
58   This class is used to handle the HTTP requests that arrive at the server.  By
59   itself, it cannot respond to any actual HTTP requests; it must be subclassed
60   to handle each request method (e.g. GET or POST).
61   :class:`BaseHTTPRequestHandler` provides a number of class and instance
62   variables, and methods for use by subclasses.
63
64   The handler will parse the request and the headers, then call a method
65   specific to the request type. The method name is constructed from the
66   request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
67   method will be called with no arguments. All of the relevant information is
68   stored in instance variables of the handler.  Subclasses should not need to
69   override or extend the :meth:`__init__` method.
70
71   :class:`BaseHTTPRequestHandler` has the following instance variables:
72
73   .. attribute:: client_address
74
75      Contains a tuple of the form ``(host, port)`` referring to the client's
76      address.
77
78   .. attribute:: server
79
80      Contains the server instance.
81
82   .. attribute:: close_connection
83
84      Boolean that should be set before :meth:`handle_one_request` returns,
85      indicating if another request may be expected, or if the connection should
86      be shut down.
87
88   .. attribute:: requestline
89
90      Contains the string representation of the HTTP request line. The
91      terminating CRLF is stripped. This attribute should be set by
92      :meth:`handle_one_request`. If no valid request line was processed, it
93      should be set to the empty string.
94
95   .. attribute:: command
96
97      Contains the command (request type). For example, ``'GET'``.
98
99   .. attribute:: path
100
101      Contains the request path.
102
103   .. attribute:: request_version
104
105      Contains the version string from the request. For example, ``'HTTP/1.0'``.
106
107   .. attribute:: headers
108
109      Holds an instance of the class specified by the :attr:`MessageClass` class
110      variable. This instance parses and manages the headers in the HTTP
111      request. The :func:`~http.client.parse_headers` function from
112      :mod:`http.client` is used to parse the headers and it requires that the
113      HTTP request provide a valid :rfc:`2822` style header.
114
115   .. attribute:: rfile
116
117      An :class:`io.BufferedIOBase` input stream, ready to read from
118      the start of the optional input data.
119
120   .. attribute:: wfile
121
122      Contains the output stream for writing a response back to the
123      client. Proper adherence to the HTTP protocol must be used when writing to
124      this stream in order to achieve successful interoperation with HTTP
125      clients.
126
127      .. versionchanged:: 3.6
128         This is an :class:`io.BufferedIOBase` stream.
129
130   :class:`BaseHTTPRequestHandler` has the following attributes:
131
132   .. attribute:: server_version
133
134      Specifies the server software version.  You may want to override this. The
135      format is multiple whitespace-separated strings, where each string is of
136      the form name[/version]. For example, ``'BaseHTTP/0.2'``.
137
138   .. attribute:: sys_version
139
140      Contains the Python system version, in a form usable by the
141      :attr:`version_string` method and the :attr:`server_version` class
142      variable. For example, ``'Python/1.4'``.
143
144   .. attribute:: error_message_format
145
146      Specifies a format string that should be used by :meth:`send_error` method
147      for building an error response to the client. The string is filled by
148      default with variables from :attr:`responses` based on the status code
149      that passed to :meth:`send_error`.
150
151   .. attribute:: error_content_type
152
153      Specifies the Content-Type HTTP header of error responses sent to the
154      client.  The default value is ``'text/html'``.
155
156   .. attribute:: protocol_version
157
158      This specifies the HTTP protocol version used in responses.  If set to
159      ``'HTTP/1.1'``, the server will permit HTTP persistent connections;
160      however, your server *must* then include an accurate ``Content-Length``
161      header (using :meth:`send_header`) in all of its responses to clients.
162      For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
163
164   .. attribute:: MessageClass
165
166      Specifies an :class:`email.message.Message`\ -like class to parse HTTP
167      headers.  Typically, this is not overridden, and it defaults to
168      :class:`http.client.HTTPMessage`.
169
170   .. attribute:: responses
171
172      This attribute contains a mapping of error code integers to two-element tuples
173      containing a short and long message. For example, ``{code: (shortmessage,
174      longmessage)}``. The *shortmessage* is usually used as the *message* key in an
175      error response, and *longmessage* as the *explain* key.  It is used by
176      :meth:`send_response_only` and :meth:`send_error` methods.
177
178   A :class:`BaseHTTPRequestHandler` instance has the following methods:
179
180   .. method:: handle()
181
182      Calls :meth:`handle_one_request` once (or, if persistent connections are
183      enabled, multiple times) to handle incoming HTTP requests. You should
184      never need to override it; instead, implement appropriate :meth:`do_\*`
185      methods.
186
187   .. method:: handle_one_request()
188
189      This method will parse and dispatch the request to the appropriate
190      :meth:`do_\*` method.  You should never need to override it.
191
192   .. method:: handle_expect_100()
193
194      When a HTTP/1.1 compliant server receives an ``Expect: 100-continue``
195      request header it responds back with a ``100 Continue`` followed by ``200
196      OK`` headers.
197      This method can be overridden to raise an error if the server does not
198      want the client to continue.  For e.g. server can chose to send ``417
199      Expectation Failed`` as a response header and ``return False``.
200
201      .. versionadded:: 3.2
202
203   .. method:: send_error(code, message=None, explain=None)
204
205      Sends and logs a complete error reply to the client. The numeric *code*
206      specifies the HTTP error code, with *message* as an optional, short, human
207      readable description of the error.  The *explain* argument can be used to
208      provide more detailed information about the error; it will be formatted
209      using the :attr:`error_message_format` attribute and emitted, after
210      a complete set of headers, as the response body.  The :attr:`responses`
211      attribute holds the default values for *message* and *explain* that
212      will be used if no value is provided; for unknown codes the default value
213      for both is the string ``???``. The body will be empty if the method is
214      HEAD or the response code is one of the following: ``1xx``,
215      ``204 No Content``, ``205 Reset Content``, ``304 Not Modified``.
216
217      .. versionchanged:: 3.4
218         The error response includes a Content-Length header.
219         Added the *explain* argument.
220
221   .. method:: send_response(code, message=None)
222
223      Adds a response header to the headers buffer and logs the accepted
224      request. The HTTP response line is written to the internal buffer,
225      followed by *Server* and *Date* headers. The values for these two headers
226      are picked up from the :meth:`version_string` and
227      :meth:`date_time_string` methods, respectively. If the server does not
228      intend to send any other headers using the :meth:`send_header` method,
229      then :meth:`send_response` should be followed by an :meth:`end_headers`
230      call.
231
232      .. versionchanged:: 3.3
233         Headers are stored to an internal buffer and :meth:`end_headers`
234         needs to be called explicitly.
235
236   .. method:: send_header(keyword, value)
237
238      Adds the HTTP header to an internal buffer which will be written to the
239      output stream when either :meth:`end_headers` or :meth:`flush_headers` is
240      invoked. *keyword* should specify the header keyword, with *value*
241      specifying its value. Note that, after the send_header calls are done,
242      :meth:`end_headers` MUST BE called in order to complete the operation.
243
244      .. versionchanged:: 3.2
245         Headers are stored in an internal buffer.
246
247   .. method:: send_response_only(code, message=None)
248
249      Sends the response header only, used for the purposes when ``100
250      Continue`` response is sent by the server to the client. The headers not
251      buffered and sent directly the output stream.If the *message* is not
252      specified, the HTTP message corresponding the response *code*  is sent.
253
254      .. versionadded:: 3.2
255
256   .. method:: end_headers()
257
258      Adds a blank line
259      (indicating the end of the HTTP headers in the response)
260      to the headers buffer and calls :meth:`flush_headers()`.
261
262      .. versionchanged:: 3.2
263         The buffered headers are written to the output stream.
264
265   .. method:: flush_headers()
266
267      Finally send the headers to the output stream and flush the internal
268      headers buffer.
269
270      .. versionadded:: 3.3
271
272   .. method:: log_request(code='-', size='-')
273
274      Logs an accepted (successful) request. *code* should specify the numeric
275      HTTP code associated with the response. If a size of the response is
276      available, then it should be passed as the *size* parameter.
277
278   .. method:: log_error(...)
279
280      Logs an error when a request cannot be fulfilled. By default, it passes
281      the message to :meth:`log_message`, so it takes the same arguments
282      (*format* and additional values).
283
284
285   .. method:: log_message(format, ...)
286
287      Logs an arbitrary message to ``sys.stderr``. This is typically overridden
288      to create custom error logging mechanisms. The *format* argument is a
289      standard printf-style format string, where the additional arguments to
290      :meth:`log_message` are applied as inputs to the formatting. The client
291      ip address and current date and time are prefixed to every message logged.
292
293   .. method:: version_string()
294
295      Returns the server software's version string. This is a combination of the
296      :attr:`server_version` and :attr:`sys_version` attributes.
297
298   .. method:: date_time_string(timestamp=None)
299
300      Returns the date and time given by *timestamp* (which must be ``None`` or in
301      the format returned by :func:`time.time`), formatted for a message
302      header. If *timestamp* is omitted, it uses the current date and time.
303
304      The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
305
306   .. method:: log_date_time_string()
307
308      Returns the current date and time, formatted for logging.
309
310   .. method:: address_string()
311
312      Returns the client address.
313
314      .. versionchanged:: 3.3
315         Previously, a name lookup was performed. To avoid name resolution
316         delays, it now always returns the IP address.
317
318
319.. class:: SimpleHTTPRequestHandler(request, client_address, server, directory=None)
320
321   This class serves files from the current directory and below, directly
322   mapping the directory structure to HTTP requests.
323
324   A lot of the work, such as parsing the request, is done by the base class
325   :class:`BaseHTTPRequestHandler`.  This class implements the :func:`do_GET`
326   and :func:`do_HEAD` functions.
327
328   The following are defined as class-level attributes of
329   :class:`SimpleHTTPRequestHandler`:
330
331   .. attribute:: server_version
332
333      This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
334      defined at the module level.
335
336   .. attribute:: extensions_map
337
338      A dictionary mapping suffixes into MIME types. The default is
339      signified by an empty string, and is considered to be
340      ``application/octet-stream``. The mapping is used case-insensitively,
341      and so should contain only lower-cased keys.
342
343   .. attribute:: directory
344
345      If not specified, the directory to serve is the current working directory.
346
347   The :class:`SimpleHTTPRequestHandler` class defines the following methods:
348
349   .. method:: do_HEAD()
350
351      This method serves the ``'HEAD'`` request type: it sends the headers it
352      would send for the equivalent ``GET`` request. See the :meth:`do_GET`
353      method for a more complete explanation of the possible headers.
354
355   .. method:: do_GET()
356
357      The request is mapped to a local file by interpreting the request as a
358      path relative to the current working directory.
359
360      If the request was mapped to a directory, the directory is checked for a
361      file named ``index.html`` or ``index.htm`` (in that order). If found, the
362      file's contents are returned; otherwise a directory listing is generated
363      by calling the :meth:`list_directory` method. This method uses
364      :func:`os.listdir` to scan the directory, and returns a ``404`` error
365      response if the :func:`~os.listdir` fails.
366
367      If the request was mapped to a file, it is opened. Any :exc:`OSError`
368      exception in opening the requested file is mapped to a ``404``,
369      ``'File not found'`` error. If there was a ``'If-Modified-Since'``
370      header in the request, and the file was not modified after this time,
371      a ``304``, ``'Not Modified'`` response is sent. Otherwise, the content
372      type is guessed by calling the :meth:`guess_type` method, which in turn
373      uses the *extensions_map* variable, and the file contents are returned.
374
375      A ``'Content-type:'`` header with the guessed content type is output,
376      followed by a ``'Content-Length:'`` header with the file's size and a
377      ``'Last-Modified:'`` header with the file's modification time.
378
379      Then follows a blank line signifying the end of the headers, and then the
380      contents of the file are output. If the file's MIME type starts with
381      ``text/`` the file is opened in text mode; otherwise binary mode is used.
382
383      For example usage, see the implementation of the :func:`test` function
384      invocation in the :mod:`http.server` module.
385
386      .. versionchanged:: 3.7
387         Support of the ``'If-Modified-Since'`` header.
388
389The :class:`SimpleHTTPRequestHandler` class can be used in the following
390manner in order to create a very basic webserver serving files relative to
391the current directory::
392
393   import http.server
394   import socketserver
395
396   PORT = 8000
397
398   Handler = http.server.SimpleHTTPRequestHandler
399
400   with socketserver.TCPServer(("", PORT), Handler) as httpd:
401       print("serving at port", PORT)
402       httpd.serve_forever()
403
404.. _http-server-cli:
405
406:mod:`http.server` can also be invoked directly using the :option:`-m`
407switch of the interpreter with a ``port number`` argument.  Similar to
408the previous example, this serves files relative to the current directory::
409
410        python -m http.server 8000
411
412By default, server binds itself to all interfaces.  The option ``-b/--bind``
413specifies a specific address to which it should bind. Both IPv4 and IPv6
414addresses are supported. For example, the following command causes the server
415to bind to localhost only::
416
417        python -m http.server 8000 --bind 127.0.0.1
418
419.. versionadded:: 3.4
420    ``--bind`` argument was introduced.
421
422.. versionadded:: 3.8
423    ``--bind`` argument enhanced to support IPv6
424
425By default, server uses the current directory. The option ``-d/--directory``
426specifies a directory to which it should serve the files. For example,
427the following command uses a specific directory::
428
429        python -m http.server --directory /tmp/
430
431.. versionadded:: 3.7
432    ``--directory`` specify alternate directory
433
434.. class:: CGIHTTPRequestHandler(request, client_address, server)
435
436   This class is used to serve either files or output of CGI scripts from the
437   current directory and below. Note that mapping HTTP hierarchic structure to
438   local directory structure is exactly as in :class:`SimpleHTTPRequestHandler`.
439
440   .. note::
441
442      CGI scripts run by the :class:`CGIHTTPRequestHandler` class cannot execute
443      redirects (HTTP code 302), because code 200 (script output follows) is
444      sent prior to execution of the CGI script.  This pre-empts the status
445      code.
446
447   The class will however, run the CGI script, instead of serving it as a file,
448   if it guesses it to be a CGI script.  Only directory-based CGI are used ---
449   the other common server configuration is to treat special extensions as
450   denoting CGI scripts.
451
452   The :func:`do_GET` and :func:`do_HEAD` functions are modified to run CGI scripts
453   and serve the output, instead of serving files, if the request leads to
454   somewhere below the ``cgi_directories`` path.
455
456   The :class:`CGIHTTPRequestHandler` defines the following data member:
457
458   .. attribute:: cgi_directories
459
460      This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
461      treat as containing CGI scripts.
462
463   The :class:`CGIHTTPRequestHandler` defines the following method:
464
465   .. method:: do_POST()
466
467      This method serves the ``'POST'`` request type, only allowed for CGI
468      scripts.  Error 501, "Can only POST to CGI scripts", is output when trying
469      to POST to a non-CGI url.
470
471   Note that CGI scripts will be run with UID of user nobody, for security
472   reasons.  Problems with the CGI script will be translated to error 403.
473
474:class:`CGIHTTPRequestHandler` can be enabled in the command line by passing
475the ``--cgi`` option::
476
477        python -m http.server --cgi 8000
478