とても良い質問です。
Pythonだけでも、外部フレームワーク(FlaskやDjangoなど)を使わずに標準ライブラリだけでWebサーバを構築できます。
ここでは、基本から本格的な実装まで段階的に説明します。
① 最も簡単な方法(HTTPサーバを一瞬で建てる)
Python標準ライブラリの http.server モジュールを使えば、
1行でHTTPサーバを立ち上げられます。
python -m http.server 8000
これで、カレントディレクトリが http://localhost:8000 でアクセス可能になります。
静的ファイル(HTML, CSS, 画像など)を配信する簡易サーバです。
② Pythonコードで書く(最小限のWebサーバ)
from http.server import HTTPServer, BaseHTTPRequestHandlerclass SimpleHandler(BaseHTTPRequestHandler): def do_GET(self): # ステータスコード200を返す self.send_response(200) # レスポンスヘッダ self.send_header("Content-type", "text/html; charset=utf-8") self.end_headers() # 本文 self.wfile.write(b"<h1>Hello, Python Web Server!</h1>")# サーバ設定server = HTTPServer(('localhost', 8080), SimpleHandler)print("Server running on http://localhost:8080")server.serve_forever()
これで http://localhost:8080 にアクセスすると “Hello, Python Web Server!” が表示されます。
③ POST通信などを処理するサーバ
フォーム送信やAPIリクエストを受け取るなら、do_POST を追加します。
from http.server import HTTPServer, BaseHTTPRequestHandlerimport urllib.parseclass MyHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html; charset=utf-8") self.end_headers() html = """ <form method="POST"> <input name="name"> <input type="submit" value="Send"> </form> """ self.wfile.write(html.encode("utf-8")) def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) params = urllib.parse.parse_qs(post_data.decode('utf-8')) name = params.get('name', [''])[0] self.send_response(200) self.send_header("Content-type", "text/html; charset=utf-8") self.end_headers() self.wfile.write(f"<h1>Hello, {name}!</h1>".encode("utf-8"))server = HTTPServer(('localhost', 8080), MyHandler)print("Server running on http://localhost:8080")server.serve_forever()
これでフォームを送信すると、入力値が画面に表示されます。
④ 本格的に作るには
Python標準ライブラリのみでは以下のような制約があります。
本格的にやるなら、socket モジュールを使って
HTTPプロトコルを自前で処理することも可能です。
⑤ ソケットレベルでの最小HTTPサーバ(完全自作)
import socketHOST = 'localhost'PORT = 8080with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen(1) print(f"Server running on http://{HOST}:{PORT}") while True: conn, addr = s.accept() with conn: request = conn.recv(1024).decode('utf-8') print(request) # 受信内容を表示 response = ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" "\r\n" "<h1>Hello from pure socket!</h1>" ) conn.sendall(response.encode('utf-8'))
このコードでは、HTTPリクエスト文字列を直接解析してレスポンスを返しています。
完全な自作HTTPサーバです。
まとめ
| 方法 | 特徴 | 難易度 |
|---|
python -m http.server | ファイル共有向け。1行。 | ★☆☆☆☆ |
http.server + BaseHTTPRequestHandler | 簡単なAPIやフォーム処理可 | ★★☆☆☆ |
socket で自作 | プロトコルレベル理解が深まる | ★★★★★ |