21.22. "http.server" --- HTTP サーバ
************************************

**ソースコード:** Lib/http/server.py

======================================================================

このモジュールは HTTP (web) サーバを実装するためのクラスを提供していま
す。

警告: "http.server" is not recommended for production. It only
  implements only basic security checks.

クラス "HTTPServer" は "socketserver.TCPServer" のサブクラスです。
"HTTPServer" は HTTP ソケットを生成してリクエスト待ち (listen) を行い
、リクエストをハンドラに渡します。 サーバを作成して動作させるためのコ
ードは以下のようになります:

   def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
       server_address = ('', 8000)
       httpd = server_class(server_address, handler_class)
       httpd.serve_forever()

class http.server.HTTPServer(server_address, RequestHandlerClass)

   このクラスは "TCPServer" クラスの上に構築されており、サーバのアドレ
   スをインスタンス変数 "server_name" および "server_port" に記憶しま
   す。 サーバはハンドラからアクセス可能で、通常ハンドラの "server" イ
   ンスタンス変数からアクセスします。

"HTTPServer" は *RequestHandlerClass* の初期化のときに与えられなければ
ならず、このモジュールはこのクラスの3つの変種を提供しています:

class http.server.BaseHTTPRequestHandler(request, client_address, server)

   このクラスはサーバに到着したリクエストを処理します。 このメソッド自
   体では、実際のリクエストに応答することはできません; (GET や POST の
   ような) 各リクエストメソッドを処理するためにはサブクラス化しなけれ
   ばなりません。 "BaseHTTPRequestHandler" では、サブクラスで使うため
   のクラスやインスタンス変数、メソッド群を数多く提供しています。

   このハンドラはリクエストを解釈し、次いでリクエスト形式ごとに固有の
   メソッドを呼び出します。メソッド名はリクエストの名称から構成されま
   す。例えば、リクエストメソッド "SPAM" に対しては、 "do_SPAM()" メソ
   ッドが引数なしで呼び出されます。リクエストに関連する情報は全て、ハ
   ンドラのインスタンス変数に記憶されています。サブクラスでは
   "__init__()" メソッドを上書きしたり拡張したりする必要はありません。

   "BaseHTTPRequestHandler" は以下のインスタンス変数を持っています:

   client_address

      HTTP クライアントのアドレスを参照している、"(host, port)" の形式
      をとるタプルが入っています。

   server

      server インスタンスが入っています。

   close_connection

      "handle_one_request()" が返る前に設定すべき真偽値で、別のリクエ
      ストが期待されているかどうか、もしくはコネクションを切断すべきか
      どうかを指し示しています。

   requestline

      HTTP リクエスト行の文字列表現を保持しています。 末尾の CRLF は除
      去されています。 この属性は "handle_one_request()" によって設定
      されるべきです。 妥当なリクエスト行が1行も処理されなかった場合は
      、空文字列に設定されるべきです。

   command

      HTTP 命令 (リクエスト形式) が入っています。例えば "'GET'" です。

   path

      リクエストされたパスが入っています。

   request_version

      リクエストのバージョン文字列が入っています。例えば "'HTTP/1.0'"
      です。

   headers

      "MessageClass" クラス変数で指定されたクラスのインスタンスを保持
      しています。 このインスタンスは HTTP リクエストのヘッダを解釈し
      、管理しています。 "http.client" の "parse_headers()" 関数がヘッ
      ダを解釈するために使われ、 HTTP リクエストが妥当な **RFC 2822**
      スタイルのヘッダを提供することを要求します。

   rfile

      An "io.BufferedIOBase" input stream, ready to read from the
      start of the optional input data.

   wfile

      Contains the output stream for writing a response back to the
      client. Proper adherence to the HTTP protocol must be used when
      writing to this stream in order to achieve successful
      interoperation with HTTP clients.

      バージョン 3.6 で変更: This is an "io.BufferedIOBase" stream.

   "BaseHTTPRequestHandler" は以下の属性を持っています:

   server_version

      サーバのソフトウェアバージョンを指定します。この値は上書きする必
      要が生じるかもしれません。書式は複数の文字列を空白で分割したもの
      で、各文字列はソフトウェア名[/バージョン] の形式をとります。例え
      ば、"'BaseHTTP/0.2'" です。

   sys_version

      Python 処理系のバージョンが, "version_string" メソッドや
      "server_version" クラス変数で利用可能な形式で入っています。例え
      ば "'Python/1.4'" です。

   error_message_format

      Specifies a format string that should be used by "send_error()"
      method for building an error response to the client. The string
      is filled by default with variables from "responses" based on
      the status code that passed to "send_error()".

   error_content_type

      エラーレスポンスをクライアントに送信する時に使う Content-Type
      HTTP ヘッダを指定します。デフォルトでは "'text/html'" です。

   protocol_version

      この値には応答に使われる HTTP プロトコルのバージョンを指定します
      。 "'HTTP/1.1'" に設定されると、サーバは持続的 HTTP 接続を許可し
      ます; しかしその場合、サーバは全てのクライアントに対する応答に、
      正確な値を持つ "Content-Length" ヘッダを ("send_header()" を使っ
      て) 含め *なければなりません* 。以前のバージョンとの互換性を保つ
      ため、標準の設定値は "'HTTP/1.0'" です。

   MessageClass

      HTTP ヘッダを解釈するための "email.message.Message" 類似のクラス
      を指定します。 通常この値が上書きされることはなく、デフォルトの
      "http.client.HTTPMessage" になっています。

   responses

      This attribute contains a mapping of error code integers to two-
      element tuples containing a short and long message. For example,
      "{code: (shortmessage, longmessage)}". The *shortmessage* is
      usually used as the *message* key in an error response, and
      *longmessage* as the *explain* key.  It is used by
      "send_response_only()" and "send_error()" methods.

   "BaseHTTPRequestHandler" インスタンスは以下のメソッドを持っています
   :

   handle()

      "handle_one_request()" を一度だけ (持続的接続が有効になっている
      場合には複数回) 呼び出して、HTTPリクエストを処理します。このメソ
      ッドを上書きする必要はまったくありません; そうする代わりに適切な
      "do_*()" を実装してください。

   handle_one_request()

      このメソッドはリクエストを解釈し、適切な "do_*()" メソッドに転送
      します。このメソッドを上書きする必要はまったくありません。

   handle_expect_100()

      HTTP/1.1 準拠のサーバが "Expect: 100-continue" リクエストヘッダ
      を受け取ったとき、 "100 Continue" を返し、その後に "200 OK" がき
      ます。 このメソッドは、サーバがクライアントに継続を要求しない場
      合、エラーを送出するようにオーバーライドできます。 例えば、サー
      バはレスポンスヘッダとして "417 Expectation Failed" を送る選択を
      し、 "return False" とできます。

      バージョン 3.2 で追加.

   send_error(code, message=None, explain=None)

      Sends and logs a complete error reply to the client. The numeric
      *code* specifies the HTTP error code, with *message* as an
      optional, short, human readable description of the error.  The
      *explain* argument can be used to provide more detailed
      information about the error; it will be formatted using the
      "error_message_format" attribute and emitted, after a complete
      set of headers, as the response body.  The "responses" attribute
      holds the default values for *message* and *explain* that will
      be used if no value is provided; for unknown codes the default
      value for both is the string "???". The body will be empty if
      the method is HEAD or the response code is one of the following:
      "1xx", "204 No Content", "205 Reset Content", "304 Not
      Modified".

      バージョン 3.4 で変更: The error response includes a Content-
      Length header. Added the *explain* argument.

   send_response(code, message=None)

      Adds a response header to the headers buffer and logs the
      accepted request. The HTTP response line is written to the
      internal buffer, followed by *Server* and *Date* headers. The
      values for these two headers are picked up from the
      "version_string()" and "date_time_string()" methods,
      respectively. If the server does not intend to send any other
      headers using the "send_header()" method, then "send_response()"
      should be followed by an "end_headers()" call.

      バージョン 3.3 で変更: Headers are stored to an internal buffer
      and "end_headers()" needs to be called explicitly.

   send_header(keyword, value)

      Adds the HTTP header to an internal buffer which will be written
      to the output stream when either "end_headers()" or
      "flush_headers()" is invoked. *keyword* should specify the
      header keyword, with *value* specifying its value. Note that,
      after the send_header calls are done, "end_headers()" MUST BE
      called in order to complete the operation.

      バージョン 3.2 で変更: ヘッダは内部バッファに保存されます。

   send_response_only(code, message=None)

      Sends the response header only, used for the purposes when "100
      Continue" response is sent by the server to the client. The
      headers not buffered and sent directly the output stream.If the
      *message* is not specified, the HTTP message corresponding the
      response *code*  is sent.

      バージョン 3.2 で追加.

   end_headers()

      Adds a blank line (indicating the end of the HTTP headers in the
      response) to the headers buffer and calls "flush_headers()".

      バージョン 3.2 で変更: バッファされたヘッダは出力ストリームに書
      き出されます。

   flush_headers()

      最終的にヘッダを出力ストリームに送り、内部ヘッダバッファをフラッ
      シュします。

      バージョン 3.3 で追加.

   log_request(code='-', size='-')

      受理された (成功した) リクエストをログに記録します。*code* には
      この応答に関連付けられた HTTP コード番号を指定します。応答メッセ
      ージの大きさを知ることができる場合、*size* パラメタに渡すとよい
      でしょう。

   log_error(...)

      リクエストを遂行できなかった際に、エラーをログに記録します。標準
      では、メッセージを "log_message()" に渡します。従って同じ引数
      (*format* と追加の値) を取ります。

   log_message(format, ...)

      任意のメッセージを "sys.stderr" にログ記録します。このメソッドは
      通常、カスタムのエラーログ記録機構を作成するために上書きされます
      。 *format* 引数は標準の printf 形式の書式文字列で、
      "log_message()" に渡された追加の引数は書式化の入力として適用され
      ます。ログ記録される全てのメッセージには、クライアントの IP アド
      レスおよび現在の日付、時刻が先頭に付けられます。

   version_string()

      サーバーのソフトウェアのバージョンを示す文字列を返します。 その
      文字列は、"server_version" と "sys_version" の属性が含まれます。

   date_time_string(timestamp=None)

      Returns the date and time given by *timestamp* (which must be
      "None" or in the format returned by "time.time()"), formatted
      for a message header. If *timestamp* is omitted, it uses the
      current date and time.

      出力は "'Sun, 06 Nov 1994 08:49:37 GMT'" のようになります。

   log_date_time_string()

      ログ記録向けに書式化された、現在の日付および時刻を返します。

   address_string()

      クライアントのアドレスを返します。

      バージョン 3.3 で変更: Previously, a name lookup was performed.
      To avoid name resolution delays, it now always returns the IP
      address.

class http.server.SimpleHTTPRequestHandler(request, client_address, server)

   このクラスは、現在のディレクトリ以下にあるファイルを、HTTP リクエス
   トにおけるディレクトリ構造に直接対応付けて提供します。

   A lot of the work, such as parsing the request, is done by the base
   class "BaseHTTPRequestHandler".  This class implements the
   "do_GET()" and "do_HEAD()" functions.

   "SimpleHTTPRequestHandler" では以下のメンバ変数を定義しています:

   server_version

      この値は ""SimpleHTTP/" + __version__" になります。"__version__"
      はこのモジュールで定義されている値です。

   extensions_map

      拡張子を MIME 型指定子に対応付ける辞書です。標準の型指定は空文字
      列で表され、この値は "application/octet-stream" と見なされます。
      対応付けは大小文字の区別をするので、小文字のキーのみを入れるべき
      です。

   "SimpleHTTPRequestHandler" では以下のメソッドを定義しています:

   do_HEAD()

      このメソッドは "'HEAD'" 型のリクエスト処理を実行します: すなわち
      、 "GET" リクエストの時に送信されるものと同じヘッダを送信します
      。送信される可能性のあるヘッダについての完全な説明は "do_GET()"
      メソッドを参照してください。

   do_GET()

      リクエストを現在の作業ディレクトリからの相対的なパスとして解釈す
      ることで、リクエストをローカルシステム上のファイルと対応付けます
      。

      If the request was mapped to a directory, the directory is
      checked for a file named "index.html" or "index.htm" (in that
      order). If found, the file's contents are returned; otherwise a
      directory listing is generated by calling the "list_directory()"
      method. This method uses "os.listdir()" to scan the directory,
      and returns a "404" error response if the "listdir()" fails.

      If the request was mapped to a file, it is opened and the
      contents are returned.  Any "OSError" exception in opening the
      requested file is mapped to a "404", "'File not found'" error.
      Otherwise, the content type is guessed by calling the
      "guess_type()" method, which in turn uses the *extensions_map*
      variable.

      出力は "'Content-type:'" と推測されたコンテントタイプで、その後
      にファイルサイズを示す "'Content-Length;'" ヘッダと、ファイルの
      更新日時を示す "'Last-Modified:'" ヘッダが続きます。

      そしてヘッダの終了を示す空白行が続き、さらにその後にファイルの内
      容が続きます。このファイルはコンテントタイプが "text/" で始まっ
      ている場合はテキストモードで、そうでなければバイナリモードで開か
      れます。

      For example usage, see the implementation of the "test()"
      function invocation in the "http.server" module.

The "SimpleHTTPRequestHandler" class can be used in the following
manner in order to create a very basic webserver serving files
relative to the current directory:

   import http.server
   import socketserver

   PORT = 8000

   Handler = http.server.SimpleHTTPRequestHandler

   with socketserver.TCPServer(("", PORT), Handler) as httpd:
       print("serving at port", PORT)
       httpd.serve_forever()

"http.server" can also be invoked directly using the "-m" switch of
the interpreter with a "port number" argument.  Similar to the
previous example, this serves files relative to the current directory:

   python -m http.server 8000

By default, server binds itself to all interfaces.  The option
"-b/--bind" specifies a specific address to which it should bind.  For
example, the following command causes the server to bind to localhost
only:

   python -m http.server 8000 --bind 127.0.0.1

バージョン 3.4 で追加: "--bind" 引数が導入されました。

class http.server.CGIHTTPRequestHandler(request, client_address, server)

   This class is used to serve either files or output of CGI scripts
   from the current directory and below. Note that mapping HTTP
   hierarchic structure to local directory structure is exactly as in
   "SimpleHTTPRequestHandler".

   注釈: "CGIHTTPRequestHandler" クラスで実行される CGI スクリプトは
     HTTP コード 200 (スクリプトの出力が後に続く) を実行に先立って出力
     され る (これがステータスコードになります) ため、リダイレクト(コ
     ード 302) を行なうことができません。

   The class will however, run the CGI script, instead of serving it
   as a file, if it guesses it to be a CGI script.  Only directory-
   based CGI are used --- the other common server configuration is to
   treat special extensions as denoting CGI scripts.

   "do_GET()" および "do_HEAD()" 関数は、HTTP 要求が "cgi_directories"
   パス以下のどこかを指している場合、ファイルを提供するのではなく、CGI
   スクリプトを実行してその出力を提供するように変更されています。

   "CGIHTTPRequestHandler" では以下のデータメンバを定義しています:

   cgi_directories

      この値は標準で "['/cgi-bin', '/htbin']" であり、CGI スクリプトを
      含んでいることを示すディレクトリを記述します。

   "CGIHTTPRequestHandler" は以下のメソッドを定義しています:

   do_POST()

      このメソッドは、CGI スクリプトでのみ許されている "'POST'" 型の
      HTTP 要求に対するサービスを行います。CGI でない url に対して
      POST を試みた場合、出力は Error 501, "Can only POST to CGI
      scripts" になります。

   Note that CGI scripts will be run with UID of user nobody, for
   security reasons.  Problems with the CGI script will be translated
   to error 403.

"CGIHTTPRequestHandler" can be enabled in the command line by passing
the "--cgi" option:

   python -m http.server --cgi 8000
