~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to python-3.5.2-docs-html/_sources/library/http.server.txt

  • Committer: Dave Kuhlman
  • Date: 2017-04-15 16:24:56 UTC
  • Revision ID: dkuhlman@davekuhlman.org-20170415162456-iav9vozzg4iwqwv3
Updated docs

Show diffs side-by-side

added added

removed removed

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