LoginSignup
9
9

More than 5 years have passed since last update.

Python3.5でhttp.server使うときの注意点

Last updated at Posted at 2018-08-09

はじめに

pythonでwebサーバ立ち上げたくなって、ラズパイ上で試してみた。

試行錯誤

ここらへんを読みながら真似してみた。
pythonでローカルwebサーバを立ち上げる - Qiita
21.22. http.server — HTTP サーバ — Python 3.6.5 ドキュメント

こんな感じ。

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

するとエラーが出た。

File "simpleserver.py", line 8, in <module>
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
AttributeError: __exit__

わからないんで、そのまま調べてみると、ヒットした。

AttributeError: exit with socketserver on python-3.4.3 - Stack Overflow

ここに、こんなん書いてあった。

Changed in version 3.6: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling server_close().

らしい。

python3のバージョン調べてみると、

python3 --version
Python 3.5.3

やった。

バージョン指定してドキュメント見てみると、サンプルコードが微妙に違う。
21.22. http.server — HTTP サーバ — Python 3.5.3 ドキュメント

そのまんま、こんな感じで書いた。

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

httpd = socketserver.TCPServer(("", PORT), Handler)

print("serving at port", PORT)
httpd.serve_forever()

動いた。よかった。

おわりに

大概のエラーはstackoverflowに解決方法書いてある。
公式ドキュメント見るとき、バージョンを指定するの大事。
python3の中でも微妙にバージョンによる差異がある。
気をつけよ。

9
9
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
9
9