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

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

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

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

警告:

  "http.server" is not recommended for production. It only implements
  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" イ
   ンスタンス変数からアクセスします。

class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)

   This class is identical to HTTPServer but uses threads to handle
   requests by using the "ThreadingMixIn". This is useful to handle
   web browsers pre-opening sockets, on which "HTTPServer" would wait
   indefinitely.

   バージョン 3.7 で追加.

"HTTPServer" と "ThreadingHTTPServer" は *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

      Contains the request path. If query component of the URL is
      present, then "path" includes the query. Using the terminology
      of **RFC 3986**, "path" here includes "hier-part" and the
      "query".

   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()

      When a HTTP/1.1 compliant server receives an "Expect:
      100-continue" request header it responds back with a "100
      Continue" followed by "200 OK" headers. This method can be
      overridden to raise an error if the server does not want the
      client to continue.  For e.g. server can choose to send "417
      Expectation Failed" as a response header and "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)

      メッセージヘッダ向けに書式化された、 *timestamp* ("None" または
      "time.time()" のフォーマットである必要があります)で与えられた日
      時を返します。もし *timestamp* が省略された場合には、現在の日時
      が使われます。

      出力は "'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, directory=None)

   This class serves files from the directory *directory* and below,
   or the current directory if *directory* is not provided, directly
   mapping the directory structure to HTTP requests.

   バージョン 3.7 で追加: The *directory* parameter.

   バージョン 3.9 で変更: The *directory* parameter accepts a *path-
   like object*.

   リクエストの解釈のような、多くの作業は基底クラス
   "BaseHTTPRequestHandler" で行われます。このクラスは関数 "do_GET()"
   および "do_HEAD()" を実装しています。

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

   server_version

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

   extensions_map

      A dictionary mapping suffixes into MIME types, contains custom
      overrides for the default system mappings. The mapping is used
      case-insensitively, and so should contain only lower-cased keys.

      バージョン 3.9 で変更: This dictionary is no longer filled with
      the default system mappings, but only contains overrides.

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

   do_HEAD()

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

   do_GET()

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

      リクエストがディレクトリに対応付けられた場合、 "index.html" また
      は "index.htm" を (この順序で) チェックします。もしファイルを発
      見できればその内容を、そうでなければディレクトリ一覧を
      "list_directory()" メソッドで生成して、返します。このメソッドは
      "os.listdir()" をディレクトリのスキャンに用いており、
      "listdir()" が失敗した場合には "404" 応答が返されます。

      If the request was mapped to a file, it is opened. Any "OSError"
      exception in opening the requested file is mapped to a "404",
      "'File not found'" error. If there was a "'If-Modified-Since'"
      header in the request, and the file was not modified after this
      time, a "304", "'Not Modified'" response is sent. Otherwise, the
      content type is guessed by calling the "guess_type()" method,
      which in turn uses the *extensions_map* variable, and the file
      contents are returned.

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

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

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

      バージョン 3.7 で変更: Support of the "'If-Modified-Since'"
      header.

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.  Similar to the previous example, this serves files
relative to the current directory:

   python -m http.server

The server listens to port 8000 by default. The default can be
overridden by passing the desired port number as an argument:

   python -m http.server 9000

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

   python -m http.server --bind 127.0.0.1

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

バージョン 3.8 で追加: "--bind" argument enhanced to support IPv6

By default, the server uses the current directory. The option
"-d/--directory" specifies a directory to which it should serve the
files. For example, the following command uses a specific directory:

   python -m http.server --directory /tmp/

バージョン 3.7 で追加: "--directory" argument was introduced.

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

   このクラスは、現在のディレクトリかその下のディレクトリにおいて、フ
   ァイルか CGI スクリプト出力を提供するために使われます。 HTTP 階層構
   造からローカルなディレクトリ構造への対応付けは
   "SimpleHTTPRequestHandler" と全く同じなので注意してください。

   注釈:

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

   このクラスでは、ファイルが CGI スクリプトであると推測された場合、こ
   れをファイルとして提供する代わりにスクリプトを実行します。 --- 他の
   一般的なサーバ設定は特殊な拡張子を使って CGI スクリプトであることを
   示すのに対し、ディレクトリベースの CGI だけが使われます。

   "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" になります。

   セキュリティ上の理由から、CGI スクリプトはユーザ nobody の UID で動
   作するので注意してください。 CGI スクリプトが原因で発生した問題は、
   Error 403 に変換されます。

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

   python -m http.server --cgi


Security Considerations
=======================

"SimpleHTTPRequestHandler" will follow symbolic links when handling
requests, this makes it possible for files outside of the specified
directory to be served.

Earlier versions of Python did not scrub control characters from the
log messages emitted to stderr from "python -m http.server" or the
default "BaseHTTPRequestHandler" ".log_message" implementation. This
could allow remote clients connecting to your server to send nefarious
control codes to your terminal.

バージョン 3.9.16 で追加: scrubbing control characters from log
messages
