LoginSignup
5
3

More than 3 years have passed since last update.

公開ディレクトリ指定方法 Python 簡易HTTPサーバー

Last updated at Posted at 2020-04-21

PythonにはWEB開発用の簡易HTTPサーバー機能が備わっています。
便利なのですが、公開したいディレクトリ直下に公開用スクリプトを置く必要がある(と思い込んでました)ため不便であり、公開ディレクトリを指定する方法を調べただけです。

結論

(Python3.7以上対応)
以下DIRECTORYにスクリプトからの相対パスを入れればOK。

参考1 より引用

server.py
import http.server
import socketserver

PORT = 8000
DIRECTORY = "web"

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)


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

参考1

StackOverflow "How to run a http server which serves a specific path?"
私が知りたいことそのまま書いていた。

コードの意味

公開ディレクトリを特に指定しない場合は、以下のようなコードでよい。自動的にスクリプトの存在するディレクトリが公開ディレクトリとなる。
TCPServer()にハンドラを引数として渡すことで、TCPServer()の中でSimpleHTTPRequestHandlerのコンストラクタに適切な引数を入れている。だからこのHandlerは関数ポインタのようなイメージ。(つまり、それが"ハンドラ"か。)

ディレクトリ指定しない.py

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

で、上の結論のコードにおいて何をやっているかというとTCPServer()の中でSimpleHTTPRequestHandlerのコンストラクタを呼ぶという大枠は変えないで(以下のコードで言うところのargsと*kwargs),
引数 directory に"任意の指定ディレクトリ"を渡すようにコンストラクタを上書きしている。

難しかったところだけ調べた.py

#SimpleHTTPRequestHandlerの初期化関数を再定義
class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

#ほんとはこれがやりたいのだけど、引数足りないエラーになる。
#引数はTCPServer()の内部で適当に入れているから、ここでは入れられない&わからない。
Handler = http.server.SimpleHTTPRequestHandler(directory="web")

#これもだめ。当然だがargsってなんだよって言われる。
Handler = http.server.SimpleHTTPRequestHandler(*args,directory="web",**kwargs)

参考2

python仕様書より http.server
image.png

そう!やりたいのは以下のdirectoryに引数を入れたいだけなんだよ!
image.png

参考3

pythonで継承とsuper()を使って派生クラスをinitしてみよう
コンストラクタ上書きの部分がわからなくてお世話になりました。
Pythonの可変長引数(*args, **kwargs)の使い方
*argsのアスタリスクの意味が分からなくてお世話になりました。

5
3
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
5
3