Debian Codegraph @

Doc/library/http.server.rst

raw
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
17 This module defines classes for implementing HTTP servers.
18
19
20 .. warning::
21
22 :mod:`http.server` is not recommended for production. It only implements
23 :ref:`basic security checks <http.server-security>`.
24
25 .. include:: ../includes/wasm-notavail.rst
26
27 One class, :class:`HTTPServer`, is a :class:`socketserver.TCPServer` subclass.
28 It creates and listens at the HTTP socket, dispatching the requests to a
29 handler. Code to create and run the server looks like this::
30
31 def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
32 server_address = ('', 8000)
33 httpd = server_class(server_address, handler_class)
34 httpd.serve_forever()
35
36
37 .. class:: HTTPServer(server_address, RequestHandlerClass)
38
39 This class builds on the :class:`~socketserver.TCPServer` class by storing
40 the server address as instance variables named :attr:`server_name` and
41 :attr:`server_port`. The server is accessible by the handler, typically
42 through the handler's :attr:`~socketserver.BaseRequestHandler.server`
43 instance variable.
44
45 .. attribute:: server_name
46
47 The HTTP server's fully qualified domain name.
48
49 .. attribute:: server_port
50
51 The HTTP server's port number obtained from *server_address*.
52
53
54 .. class:: ThreadingHTTPServer(server_address, RequestHandlerClass)
55
56 This class is identical to HTTPServer but uses threads to handle
57 requests by using the :class:`~socketserver.ThreadingMixIn`. This
58 is useful to handle web browsers pre-opening sockets, on which
59 :class:`HTTPServer` would wait indefinitely.
60
61 .. versionadded:: 3.7
62
63
64 The :class:`HTTPServer` and :class:`ThreadingHTTPServer` must be given
65 a *RequestHandlerClass* on instantiation, of which this module
66 provides three different variants:
67
68 .. class:: BaseHTTPRequestHandler(request, client_address, server)
69
70 This class is used to handle the HTTP requests that arrive at the server. By
71 itself, it cannot respond to any actual HTTP requests; it must be subclassed
72 to handle each request method (for example, ``'GET'`` or ``'POST'``).
73 :class:`BaseHTTPRequestHandler` provides a number of class and instance
74 variables, and methods for use by subclasses.
75
76 The handler will parse the request and the headers, then call a method
77 specific to the request type. The method name is constructed from the
78 request. For example, for the request method ``SPAM``, the :meth:`!do_SPAM`
79 method will be called with no arguments. All of the relevant information is
80 stored in instance variables of the handler. Subclasses should not need to
81 override or extend the :meth:`!__init__` method.
82
83 :class:`BaseHTTPRequestHandler` has the following instance variables:
84
85 .. attribute:: client_address
86
87 Contains a tuple of the form ``(host, port)`` referring to the client's
88 address.
89
90 .. attribute:: server
91
92 Contains the server instance.
93
94 .. attribute:: close_connection
95
96 Boolean that should be set before :meth:`handle_one_request` returns,
97 indicating if another request may be expected, or if the connection should
98 be shut down.
99
100 .. attribute:: requestline
101
102 Contains the string representation of the HTTP request line. The
103 terminating CRLF is stripped. This attribute should be set by
104 :meth:`handle_one_request`. If no valid request line was processed, it
105 should be set to the empty string.
106
107 .. attribute:: command
108
109 Contains the command (request type). For example, ``'GET'``.
110
111 .. attribute:: path
112
113 Contains the request path. If the query component of the URL is present,
114 then ``path`` includes the query. Using the terminology of :rfc:`3986`,
115 ``path`` here includes ``hier-part`` and the ``query``.
116
117 .. attribute:: request_version
118
119 Contains the version string from the request. For example, ``'HTTP/1.0'``.
120
121 .. attribute:: headers
122
123 Holds an instance of the class specified by the :attr:`MessageClass` class
124 variable. This instance parses and manages the headers in the HTTP
125 request. The :func:`~http.client.parse_headers` function from
126 :mod:`http.client` is used to parse the headers and it requires that the
127 HTTP request provide a valid :rfc:`5322` style header.
128
129 .. attribute:: rfile
130
131 An :class:`io.BufferedIOBase` input stream, ready to read from
132 the start of the optional input data.
133
134 .. attribute:: wfile
135
136 Contains the output stream for writing a response back to the
137 client. Proper adherence to the HTTP protocol must be used when writing to
138 this stream in order to achieve successful interoperation with HTTP
139 clients.
140
141 .. versionchanged:: 3.6
142 This is an :class:`io.BufferedIOBase` stream.
143
144 :class:`BaseHTTPRequestHandler` has the following attributes:
145
146 .. attribute:: server_version
147
148 Specifies the server software version. You may want to override this. The
149 format is multiple whitespace-separated strings, where each string is of
150 the form name[/version]. For example, ``'BaseHTTP/0.2'``.
151
152 .. attribute:: sys_version
153
154 Contains the Python system version, in a form usable by the
155 :attr:`version_string` method and the :attr:`server_version` class
156 variable. For example, ``'Python/1.4'``.
157
158 .. attribute:: error_message_format
159
160 Specifies a format string that should be used by :meth:`send_error` method
161 for building an error response to the client. The string is filled by
162 default with variables from :attr:`responses` based on the status code
163 passed to :meth:`send_error`.
164
165 .. attribute:: error_content_type
166
167 Specifies the Content-Type HTTP header of error responses sent to the
168 client. The default value is ``'text/html'``.
169
170 .. attribute:: protocol_version
171
172 Specifies the HTTP version to which the server is conformant. It is sent
173 in responses to let the client know the server's communication
174 capabilities for future requests. If set to
175 ``'HTTP/1.1'``, the server will permit HTTP persistent connections;
176 however, your server *must* then include an accurate ``Content-Length``
177 header (using :meth:`send_header`) in all of its responses to clients.
178 For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
179
180 .. attribute:: MessageClass
181
182 Specifies an :class:`email.message.Message`\ -like class to parse HTTP
183 headers. Typically, this is not overridden, and it defaults to
184 :class:`http.client.HTTPMessage`.
185
186 .. attribute:: responses
187
188 This attribute contains a mapping of error code integers to two-element tuples
189 containing a short and long message. For example, ``{code: (shortmessage,
190 longmessage)}``. The *shortmessage* is usually used as the *message* key in an
191 error response, and *longmessage* as the *explain* key. It is used by
192 :meth:`send_response_only` and :meth:`send_error` methods.
193
194 A :class:`BaseHTTPRequestHandler` instance has the following methods:
195
196 .. method:: handle()
197
198 Calls :meth:`handle_one_request` once (or, if persistent connections are
199 enabled, multiple times) to handle incoming HTTP requests. You should
200 never need to override it; instead, implement appropriate :meth:`!do_\*`
201 methods.
202
203 .. method:: handle_one_request()
204
205 This method will parse and dispatch the request to the appropriate
206 :meth:`!do_\*` method. You should never need to override it.
207
208 .. method:: handle_expect_100()
209
210 When an HTTP/1.1 conformant server receives an ``Expect: 100-continue``
211 request header it responds with a ``100 Continue`` followed by ``200 OK``
212 headers.
213 This method can be overridden to raise an error if the server does not
214 want the client to continue. For example, the server can choose to send ``417
215 Expectation Failed`` as a response header and ``return False``.
216
217 .. versionadded:: 3.2
218
219 .. method:: send_error(code, message=None, explain=None)
220
221 Sends and logs a complete error reply to the client. The numeric *code*
222 specifies the HTTP error code, with *message* as an optional, short, human
223 readable description of the error. The *explain* argument can be used to
224 provide more detailed information about the error; it will be formatted
225 using the :attr:`error_message_format` attribute and emitted, after
226 a complete set of headers, as the response body. The :attr:`responses`
227 attribute holds the default values for *message* and *explain* that
228 will be used if no value is provided; for unknown codes the default value
229 for both is the string ``???``. The body will be empty if the method is
230 HEAD or the response code is one of the following: :samp:`1{xx}`,
231 ``204 No Content``, ``205 Reset Content``, ``304 Not Modified``.
232
233 .. versionchanged:: 3.4
234 The error response includes a Content-Length header.
235 Added the *explain* argument.
236
237 .. method:: send_response(code, message=None)
238
239 Adds a response header to the headers buffer and logs the accepted
240 request. The HTTP response line is written to the internal buffer,
241 followed by *Server* and *Date* headers. The values for these two headers
242 are picked up from the :meth:`version_string` and
243 :meth:`date_time_string` methods, respectively. If the server does not
244 intend to send any other headers using the :meth:`send_header` method,
245 then :meth:`send_response` should be followed by an :meth:`end_headers`
246 call.
247
248 .. versionchanged:: 3.3
249 Headers are stored to an internal buffer and :meth:`end_headers`
250 needs to be called explicitly.
251
252 .. method:: send_header(keyword, value)
253
254 Adds the HTTP header to an internal buffer which will be written to the
255 output stream when either :meth:`end_headers` or :meth:`flush_headers` is
256 invoked. *keyword* should specify the header keyword, with *value*
257 specifying its value. Note that, after the send_header calls are done,
258 :meth:`end_headers` MUST BE called in order to complete the operation.
259
260 This method does not reject input containing CRLF sequences.
261
262 .. versionchanged:: 3.2
263 Headers are stored in an internal buffer.
264
265 .. method:: send_response_only(code, message=None)
266
267 Sends the response header only, used for the purposes when ``100
268 Continue`` response is sent by the server to the client. The headers are
269 not buffered and sent directly the output stream. If the *message* is not
270 specified, the HTTP message corresponding the response *code* is sent.
271
272 This method does not reject *message* containing CRLF sequences.
273
274 .. versionadded:: 3.2
275
276 .. method:: end_headers()
277
278 Adds a blank line
279 (indicating the end of the HTTP headers in the response)
280 to the headers buffer and calls :meth:`flush_headers`.
281
282 .. versionchanged:: 3.2
283 The buffered headers are written to the output stream.
284
285 .. method:: flush_headers()
286
287 Finally send the headers to the output stream and flush the internal
288 headers buffer.
289
290 .. versionadded:: 3.3
291
292 .. method:: log_request(code='-', size='-')
293
294 Logs an accepted (successful) request. *code* should specify the numeric
295 HTTP code associated with the response. If a size of the response is
296 available, then it should be passed as the *size* parameter.
297
298 .. method:: log_error(...)
299
300 Logs an error when a request cannot be fulfilled. By default, it passes
301 the message to :meth:`log_message`, so it takes the same arguments
302 (*format* and additional values).
303
304
305 .. method:: log_message(format, ...)
306
307 Logs an arbitrary message to ``sys.stderr``. This is typically overridden
308 to create custom error logging mechanisms. The *format* argument is a
309 standard printf-style format string, where the additional arguments to
310 :meth:`log_message` are applied as inputs to the formatting. The client
311 IP address and current date and time are prefixed to every message logged.
312
313 .. method:: version_string()
314
315 Returns the server software's version string. This is a combination of the
316 :attr:`server_version` and :attr:`sys_version` attributes.
317
318 .. method:: date_time_string(timestamp=None)
319
320 Returns the date and time given by *timestamp* (which must be ``None`` or in
321 the format returned by :func:`time.time`), formatted for a message
322 header. If *timestamp* is omitted, it uses the current date and time.
323
324 The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
325
326 .. method:: log_date_time_string()
327
328 Returns the current date and time, formatted for logging.
329
330 .. method:: address_string()
331
332 Returns the client address.
333
334 .. versionchanged:: 3.3
335 Previously, a name lookup was performed. To avoid name resolution
336 delays, it now always returns the IP address.
337
338
339 .. class:: SimpleHTTPRequestHandler(request, client_address, server, directory=None)
340
341 This class serves files from the directory *directory* and below,
342 or the current directory if *directory* is not provided, directly
343 mapping the directory structure to HTTP requests.
344
345 .. versionchanged:: 3.7
346 Added the *directory* parameter.
347
348 .. versionchanged:: 3.9
349 The *directory* parameter accepts a :term:`path-like object`.
350
351 A lot of the work, such as parsing the request, is done by the base class
352 :class:`BaseHTTPRequestHandler`. This class implements the :func:`do_GET`
353 and :func:`do_HEAD` functions.
354
355 The following are defined as class-level attributes of
356 :class:`SimpleHTTPRequestHandler`:
357
358 .. attribute:: server_version
359
360 This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
361 defined at the module level.
362
363 .. attribute:: index_pages
364
365 Specifies the filenames that are treated as directory index pages.
366
367 Defaults to ``("index.html", "index.htm")``.
368
369 .. versionadded:: 3.12
370
371 .. attribute:: extensions_map
372
373 A dictionary mapping suffixes into MIME types, contains custom overrides
374 for the default system mappings. The mapping is used case-insensitively,
375 and so should contain only lower-cased keys.
376
377 .. versionchanged:: 3.9
378 This dictionary is no longer filled with the default system mappings,
379 but only contains overrides.
380
381 The :class:`SimpleHTTPRequestHandler` class defines the following methods:
382
383 .. method:: do_HEAD()
384
385 This method serves the ``'HEAD'`` request type: it sends the headers it
386 would send for the equivalent ``GET`` request. See the :meth:`do_GET`
387 method for a more complete explanation of the possible headers.
388
389 .. method:: do_GET()
390
391 The request is mapped to a local file by interpreting the request as a
392 path relative to the current working directory.
393
394 If the request was mapped to a directory, the directory is checked for
395 an index page as specified by :attr:`index_pages`. If found, the
396 file's contents are returned; otherwise a directory listing is generated
397 by calling the :meth:`list_directory` method. This method uses
398 :func:`os.listdir` to scan the directory, and returns a ``404`` error
399 response if the :func:`~os.listdir` fails.
400
401 If the request was mapped to a file, it is opened. Any :exc:`OSError`
402 exception in opening the requested file is mapped to a ``404``,
403 ``'File not found'`` error. If there was an ``'If-Modified-Since'``
404 header in the request, and the file was not modified after this time,
405 a ``304``, ``'Not Modified'`` response is sent. Otherwise, the content
406 type is guessed by calling the :meth:`guess_type` method, which in turn
407 uses the *extensions_map* variable, and the file contents are returned.
408
409 A ``'Content-type:'`` header with the guessed content type is output,
410 followed by a ``'Content-Length:'`` header with the file's size and a
411 ``'Last-Modified:'`` header with the file's modification time.
412
413 Then follows a blank line signifying the end of the headers, and then the
414 contents of the file are output.
415
416 For example usage, see the implementation of the ``test`` function
417 in :source:`Lib/http/server.py`.
418
419 .. versionchanged:: 3.7
420 Support of the ``'If-Modified-Since'`` header.
421
422 .. method:: list_directory(path)
423
424 Helper to list the contents of *path* when no index page is present.
425
426 This returns either a :term:`file-like object` (which must be closed
427 by the caller) or ``None`` to indicate an error, in which case the
428 caller has nothing further to do. In either case, the headers are sent.
429
430 .. method:: guess_type(path)
431
432 Guess the type of the file at the given *path*.
433
434 This returns a string of the form ``type/subtype``, usable for
435 a MIME Content-type header.
436
437 The default implementation looks the file's extension up in
438 :attr:`extensions_map`, falling back to
439 :func:`mimetypes.guess_file_type` and then to
440 ``'application/octet-stream'``.
441
442 .. versionchanged:: 3.13
443 Add :func:`mimetypes.guess_file_type` as a fallback.
444
445
446 The :class:`SimpleHTTPRequestHandler` class can be used to create a very basic
447 webserver serving files relative to the current directory as follows::
448
449 import http.server
450 import socketserver
451
452 PORT = 8000
453
454 Handler = http.server.SimpleHTTPRequestHandler
455
456 with socketserver.TCPServer(("", PORT), Handler) as httpd:
457 print("serving at port", PORT)
458 httpd.serve_forever()
459
460
461 :class:`SimpleHTTPRequestHandler` can also be subclassed to enhance behavior,
462 such as using different index file names by overriding the class attribute
463 :attr:`~SimpleHTTPRequestHandler.index_pages`.
464
465
466 .. class:: CGIHTTPRequestHandler(request, client_address, server)
467
468 This class is used to serve either files or output of CGI scripts from the
469 current directory and below. Note that mapping HTTP hierarchic structure to
470 local directory structure is exactly as in :class:`SimpleHTTPRequestHandler`.
471
472 .. note::
473
474 CGI scripts run by the :class:`CGIHTTPRequestHandler` class cannot execute
475 redirects (HTTP code 302), because code 200 (script output follows) is
476 sent prior to execution of the CGI script. This pre-empts the status
477 code.
478
479 The class will however, run the CGI script, instead of serving it as a file,
480 if it guesses it to be a CGI script. Only directory-based CGI are used ---
481 the other common server configuration is to treat special extensions as
482 denoting CGI scripts.
483
484 The :func:`~SimpleHTTPRequestHandler.do_GET` and
485 :func:`~SimpleHTTPRequestHandler.do_HEAD` functions
486 are modified to run CGI scripts
487 and serve the output, instead of serving files, if the request leads to
488 somewhere below the ``cgi_directories`` path.
489
490 The :class:`CGIHTTPRequestHandler` defines the following data member:
491
492 .. attribute:: cgi_directories
493
494 This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
495 treat as containing CGI scripts.
496
497 The :class:`CGIHTTPRequestHandler` defines the following method:
498
499 .. method:: do_POST()
500
501 This method serves the ``'POST'`` request type, only allowed for CGI
502 scripts. Error 501, "Can only POST to CGI scripts", is output when trying
503 to POST to a non-CGI url.
504
505 Note that CGI scripts will be run with UID of user nobody, for security
506 reasons. Problems with the CGI script will be translated to error 403.
507
508 .. deprecated-removed:: 3.13 3.15
509
510 :class:`CGIHTTPRequestHandler` is being removed in 3.15. CGI has not
511 been considered a good way to do things for well over a decade. This code
512 has been unmaintained for a while now and sees very little practical use.
513 Retaining it could lead to further :ref:`security considerations
514 <http.server-security>`.
515
516
517 .. _http-server-cli:
518
519 Command-line interface
520 ----------------------
521
522 :mod:`http.server` can also be invoked directly using the :option:`-m`
523 switch of the interpreter. The following example illustrates how to serve
524 files relative to the current directory:
525
526 .. code-block:: bash
527
528 python -m http.server [OPTIONS] [port]
529
530 The following options are accepted:
531
532 .. program:: http.server
533
534 .. option:: port
535
536 The server listens to port 8000 by default. The default can be overridden
537 by passing the desired port number as an argument:
538
539 .. code-block:: bash
540
541 python -m http.server 9000
542
543 .. option:: -b, --bind <address>
544
545 Specifies a specific address to which it should bind. Both IPv4 and IPv6
546 addresses are supported. By default, the server binds itself to all
547 interfaces. For example, the following command causes the server to bind
548 to localhost only:
549
550 .. code-block:: bash
551
552 python -m http.server --bind 127.0.0.1
553
554 .. versionadded:: 3.4
555
556 .. versionchanged:: 3.8
557 Support IPv6 in the ``--bind`` option.
558
559 .. option:: -d, --directory <dir>
560
561 Specifies a directory to which it should serve the files. By default,
562 the server uses the current directory. For example, the following command
563 uses a specific directory:
564
565 .. code-block:: bash
566
567 python -m http.server --directory /tmp/
568
569 .. versionadded:: 3.7
570
571 .. option:: -p, --protocol <version>
572
573 Specifies the HTTP version to which the server is conformant. By default,
574 the server is conformant to HTTP/1.0. For example, the following command
575 runs an HTTP/1.1 conformant server:
576
577 .. code-block:: bash
578
579 python -m http.server --protocol HTTP/1.1
580
581 .. versionadded:: 3.11
582
583 .. option:: --cgi
584
585 :class:`CGIHTTPRequestHandler` can be enabled in the command line by passing
586 the ``--cgi`` option:
587
588 .. code-block:: bash
589
590 python -m http.server --cgi
591
592 .. deprecated-removed:: 3.13 3.15
593
594 :mod:`http.server` command line ``--cgi`` support is being removed
595 because :class:`CGIHTTPRequestHandler` is being removed.
596
597 .. warning::
598
599 :class:`CGIHTTPRequestHandler` and the ``--cgi`` command-line option
600 are not intended for use by untrusted clients and may be vulnerable
601 to exploitation. Always use within a secure environment.
602
603
604 .. _http.server-security:
605
606 Security considerations
607 -----------------------
608
609 .. index:: pair: http.server; security
610
611 :class:`SimpleHTTPRequestHandler` will follow symbolic links when handling
612 requests which makes it possible for files outside of the specified directory
613 to be served.
614
615 Methods :meth:`BaseHTTPRequestHandler.send_header` and
616 :meth:`BaseHTTPRequestHandler.send_response_only` assume sanitized input
617 and do not perform input validation such as checking for the presence of CRLF
618 sequences. Untrusted input may result in HTTP header injection attacks.
619
620 Earlier versions of Python did not scrub control characters from the
621 log messages emitted to stderr from ``python -m http.server`` or the
622 default :class:`BaseHTTPRequestHandler` ``.log_message``
623 implementation. This could allow remote clients connecting to your
624 server to send nefarious control codes to your terminal.
625
626 .. versionchanged:: 3.12
627 Control characters are scrubbed in stderr logs.