クライアントプログラムのちょっとしたテスト用に
手軽なHTTPサーバーが欲しくなること、ないですか。
簡単なJSONを受けてJSONを返すようなサーバーが欲しいだけなんで
PythonなんかのCGIが動けば十分…みたいな。
ちょっと探してみると、サーバー自体をPythonで作れるらしい。
Windowsでも大丈夫だった。以下手順。
Download Python | Python.org から「python-3.5.2.exe」をダウンロードしてインストール。
サーバー本体のプログラムを「server.py」として作成。
from http.server import HTTPServer, CGIHTTPRequestHandler
class Handler(CGIHTTPRequestHandler):
cgi_directories = ["/cgi-bin"]
PORT = 8080
httpd = HTTPServer(("", PORT), Handler)
httpd.serve_forever()
「server.py」のあるフォルダー内に「cgi-bin」フォルダーを作成してその中に
CGIプログラムを「test.py」として作成。
import cgi, cgitb
form = cgi.FieldStorage()
name = form.getvalue('name')
print ("Content-type:text/html\n\n")
print ("<html>")
print ("<head>")
print ("<title>Hello, world!</title>")
print ("</head>")
print ("<body>")
print ("Hello, %s!" % (name, ))
print ("</body>")
print ("</html>")
コマンドプロンプトを起動して以下を実行するとサーバーが起動する。
「C:\Users\user\AppData\Local\Programs\Python\Python35-32」はPythonのインストール先によって変えてください。
インストール時にPathに追加としている場合は不要です。
「C:\temp」は「server.py」を置いたフォルダーのパスです。
set path=%path%
cd C:\temp
python server.py
Webブラウザーから「http://localhost:8080/cgi-bin/test.py?name=Kurima」にアクセスしてみると…動いた。
すごい。簡単。
参考:html - How to run a python cgi web server in windows - Stack Overflow