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