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