2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

テスト用に任意の処理をするWebサーバをpythonで書く

Last updated at Posted at 2022-07-25

概要

検証用途などで何かしら好きな処理をさせるWebサーバの作り方をちょくちょく忘れるので、備忘録として書いておく。

基本形

基本的な任意の処理をするWebサーバは以下のように書く。

import http.server

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

class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        """任意の処理を書く"""

if __name__ == "__main__":
    run(handler_class=MyHTTPRequestHandler)

HTTPServer Classの第一引数に使用するアドレスとポートのタプル、第二引数にリクエストのハンドラを指定して、serve_forever関数を起動する。
リクエストのハンドラはBaseHTTPRequestHandlerクラスのサブクラスとして実装する。このままだとなんのリクエストも処理しないので、GETリクエストを処理させたい場合はdo_GET関数を定義する。

マルチスレッド

上記のサーバはシングルスレッドで、同時に複数のリクエストを処理できない。同時に複数のリクエストを処理するマルチスレッドのWebサーバを立てたい場合は、以下のようにする(要python 3.7以上)。

import http.server

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

class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        """任意の処理を書く"""

if __name__ == "__main__":
    run(server_class=http.server.ThreadingHTTPServer, handler_class=MyHTTPRequestHandler)

使用するサーバのクラスをHTTPServerからThreadingHTTPServerに変更する。中身はThreadingMixInなので従来と大して変わらない。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?