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