http.server --- HTTP サーバー

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


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

警告

http.server は、本番環境では推奨されません。これは、 基本的なセキュリティチェック のみを実装します。

利用可能な環境: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、WebAssembly プラットフォーム を見てください。

クラス 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)

This class builds on the TCPServer class by storing the server address as instance variables named server_name and server_port. The server is accessible by the handler, typically through the handler's server instance variable.

server_name

The HTTP server's fully qualified domain name.

server_port

The HTTP server's port number obtained from server_address.

class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)

このクラスは HTTPServer と同じですが、ThreadingMixIn を使い、スレッドでリクエストを処理します。 ウェブブラウザーがあらかじめ開いたソケットに対応するのに便利です。 このようなソケットでは HTTPServer は無期限に待機してしまいます。

Added in version 3.7.

The HTTPServer and ThreadingHTTPServer must be given a RequestHandlerClass on instantiation, of which this module provides three different variants:

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

This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (for example, 'GET' or 'POST'). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses.

ハンドラーはリクエストとヘッダーを解析してから、リクエストの種類に対応するメソッドを呼び出します。 メソッド名はリクエストから組み立てます。 例えば、リクエストメソッドが 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 the 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

Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request. The parse_headers() function from http.client is used to parse the headers and it requires that the HTTP request provide a valid RFC 5322 style header.

rfile

入力データがあればその先頭から読み込める状態の io.BufferedIOBase 入力ストリームです。

wfile

クライアントにレスポンスを書き返すための出力ストリームを保持します。 HTTP クライアントと正しくやり取りするため、このストリームへの書き込みは HTTP プロトコルに正しく従う必要があります。

バージョン 3.6 で変更: io.BufferedIOBase ストリームになりました。

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 passed to send_error().

error_content_type

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

protocol_version

サーバーが準拠する HTTP バージョンを指定します。 この値はレスポンスで送信され、後続のリクエストで使えるサーバーの通信機能をクライアントに知らせます。 'HTTP/1.1' にすると HTTP の持続的接続を許可しますが、その場合はクライアントへのすべてのレスポンスに、 (send_header() を使って) 正確な Content-Length ヘッダーを含める 必要があります。 後方互換性のため、デフォルトは 'HTTP/1.0' です。

MessageClass

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

responses

この属性は、整数のエラーコードから、短いメッセージと長いメッセージを含む 2 要素タプルへのマッピングを保持します。 例えば {code: (shortmessage, longmessage)} です。 通常、shortmessage はエラーレスポンスの message キー、longmessage は explain キーとして使います。 send_response_only() メソッドと send_error() メソッドがこの属性を使います。

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

handle()

handle_one_request() を 1 回 (持続的接続が有効な場合は複数回) 呼び出し、届いた HTTP リクエストを処理します。 このメソッドをオーバーライドする必要はないはずです。 代わりに、適切な do_*() メソッドを実装してください。

handle_one_request()

このメソッドは、リクエストを解析して適切な do_*() メソッドに振り分けます。 このメソッドをオーバーライドする必要はないはずです。

handle_expect_100()

When an HTTP/1.1 conformant server receives an Expect: 100-continue request header it responds 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 example, the server can choose to send 417 Expectation Failed as a response header and return False.

Added in version 3.2.

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

完全なエラー応答をクライアントに送信し、ログに記録します。 数値の code は HTTP エラーコードを指定します。 オプションの message には、人間が読める短いエラー説明を指定します。 explain 引数には、エラーについてより詳しい情報を指定できます。 この情報は error_message_format 属性を使って書式化し、ヘッダー全体の後にレスポンス本体として出力します。 responses 属性は、値を指定しなかったときに使う message と explain のデフォルト値を保持します。 未知のコードでは、どちらのデフォルト値も文字列 ??? です。 メソッドが HEAD の場合や、レスポンスコードが 1xx、204 No Content、205 Reset Content、304 Not Modified のいずれかの場合、本体は空になります。

バージョン 3.4 で変更: エラーレスポンスに Content-Length ヘッダーを含めるようになりました。 explain 引数を追加しました。

send_response(code, message=None)

レスポンスヘッダーをヘッダーバッファーに追加し、受け付けたリクエストをログに記録します。 HTTP レスポンス行を内部バッファーに書き込み、続いて Server ヘッダーと Date ヘッダーを書き込みます。 これらの値は、それぞれ version_string() メソッドと date_time_string() メソッドから取得します。 send_header() メソッドで他のヘッダーを送信する予定がなければ、send_response() の後に end_headers() を呼び出してください。

バージョン 3.3 で変更: ヘッダーは内部バッファーに保持されるようになったため、end_headers() を明示的に呼び出す必要があります。

send_header(keyword, value)

HTTP ヘッダーを内部バッファーに追加します。 end_headers() または flush_headers() を呼び出すと、このバッファーを出力ストリームに書き出します。 keyword にはヘッダーのキーワード、value にはその値を指定します。 send_header() の呼び出しを終えたら、処理を完了するために必ず end_headers() を呼び出してください。

This method does not reject input containing CRLF sequences.

バージョン 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 are not buffered and sent directly the output stream. If the message is not specified, the HTTP message corresponding the response code is sent.

This method does not reject message containing CRLF sequences.

Added in version 3.2.

end_headers()

ヘッダーバッファーに空行 (レスポンスの HTTP ヘッダーの終わりを示す行) を追加し、flush_headers() を呼び出します。

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

flush_headers()

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

Added in version 3.3.

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

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

log_error(...)

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

log_message(format, ...)

Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client IP address and current date and time are prefixed to every message logged.

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 で変更: 以前は名前の検索を行っていました。 名前解決による遅延を避けるため、常に IP アドレスを返すようになりました。

class http.server.SimpleHTTPRequestHandler(request, client_address, server, directory=None)

このクラスは、ディレクトリ構造を HTTP リクエストに直接対応付け、directory とその下位ディレクトリにあるファイルを配信します。 directory を省略すると、現在のディレクトリを使います。

バージョン 3.7 で変更: directory 引数を追加しました。

バージョン 3.9 で変更: directory 引数が path-like object を受け付けるようになりました。

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

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

server_version

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

index_pages

Specifies the filenames that are treated as directory index pages.

Defaults to ("index.html", "index.htm").

Added in version 3.12.

extensions_map

拡張子から MIME 型へのマッピングで、システムのデフォルトのマッピングを上書きする独自の設定を保持する辞書です。 大文字と小文字を区別せずに使うため、キーには小文字だけを含めてください。

バージョン 3.9 で変更: この辞書にシステムのデフォルトのマッピングを格納しなくなり、上書きする設定だけを含むようになりました。

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

do_HEAD()

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

do_GET()

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

If the request was mapped to a directory, the directory is checked for an index page as specified by index_pages. 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.

リクエストがファイルに対応する場合、そのファイルを開きます。 ファイルを開く際に発生した OSError 例外は、404、'File not found' エラーに対応付けます。 リクエストに 'If-Modified-Since' ヘッダーがあり、ファイルがその日時より後に変更されていなければ、304、'Not Modified' レスポンスを送信します。 そうでなければ、extensions_map 変数を使う guess_type() メソッドを呼び出してコンテントタイプを推測し、ファイルの内容を返します。

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

続いてヘッダーの終わりを示す空行を出力し、その後にファイルの内容を出力します。

使用例は Lib/http/server.py の test 関数の実装を参照してください。

バージョン 3.7 で変更: 'If-Modified-Since' ヘッダーをサポートしました。

list_directory(path)

Helper to list the contents of path when no index page is present.

This returns either a file-like object (which must be closed by the caller) or None to indicate an error, in which case the caller has nothing further to do. In either case, the headers are sent.

guess_type(path)

Guess the type of the file at the given path.

This returns a string of the form type/subtype, usable for a MIME Content-type header.

The default implementation looks the file's extension up in extensions_map, falling back to mimetypes.guess_file_type() and then to 'application/octet-stream'.

バージョン 3.13 で変更: Add mimetypes.guess_file_type() as a fallback.

The SimpleHTTPRequestHandler class can be used to create a very basic webserver serving files relative to the current directory as follows:

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

SimpleHTTPRequestHandler can also be subclassed to enhance behavior, such as using different index file names by overriding the class attribute index_pages.

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

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

注釈

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

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

The do_GET() and do_HEAD() functions are modified to run CGI scripts and serve the output, instead of serving files, if the request leads to somewhere below the cgi_directories path.

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 に変換されます。

Deprecated since version 3.13, will be removed in version 3.15: CGIHTTPRequestHandler is being removed in 3.15. CGI has not been considered a good way to do things for well over a decade. This code has been unmaintained for a while now and sees very little practical use. Retaining it could lead to further security considerations.

コマンドライン・インターフェース

http.server can also be invoked directly using the -m switch of the interpreter. The following example illustrates how to serve files relative to the current directory:

python -m http.server [OPTIONS] [port]

以下のオプションが使用できます:

port

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
-b, --bind <address>

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

python -m http.server --bind 127.0.0.1

Added in version 3.4.

バージョン 3.8 で変更: --bind オプションで IPv6 をサポートしました。

-d, --directory <dir>

Specifies a directory to which it should serve the files. By default, the server uses the current directory. For example, the following command uses a specific directory:

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

Added in version 3.7.

-p, --protocol <version>

Specifies the HTTP version to which the server is conformant. By default, the server is conformant to HTTP/1.0. For example, the following command runs an HTTP/1.1 conformant server:

python -m http.server --protocol HTTP/1.1

Added in version 3.11.

--cgi

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

python -m http.server --cgi

Deprecated since version 3.13, will be removed in version 3.15: http.server command line --cgi support is being removed because CGIHTTPRequestHandler is being removed.

警告

CGIHTTPRequestHandler and the --cgi command-line option are not intended for use by untrusted clients and may be vulnerable to exploitation. Always use within a secure environment.

セキュリティで考慮すべき点

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

Methods BaseHTTPRequestHandler.send_header() and BaseHTTPRequestHandler.send_response_only() assume sanitized input and do not perform input validation such as checking for the presence of CRLF sequences. Untrusted input may result in HTTP header injection attacks.

以前の Python では、python -m http.server や BaseHTTPRequestHandler のデフォルトの .log_message 実装が stderr に出力するログメッセージから、制御文字を除去していませんでした。 そのため、サーバーに接続したリモートクライアントが、悪意のある制御コードを端末に送信できる可能性がありました。

バージョン 3.12 で変更: stderr のログから制御文字を除去するようになりました。