はじめに
学んだことをもう一回調べ直さなくて済むよう記録することにした。
前提
- VisualStudioCodeがインストール済み
- Python3インストール済み
参考までに現在のVisualStudioCodeのバージョンは、1.62.3。
下準備
VisualStudioCodeのファイルからフォルダーを開くで、サンプル用の作業フォルダを作成する。
適当にps1(PythonSample1の意)で作成。
作業
index.htmlを作成する。
index.html
<html>
<head><meta http-equiv="content-type" charset="UTF-8"></head>
<body>
<form action="/cgi-bin/sample.py" method="POST">
入力1<input type="text" name="foo">
入力2<input type="text" name="bar">
<input type="submit">
</form>
</body>
</html>
ディレクトリを作成する。
名前はcgi-bin。
sample.pyをcgi-bin配下で作成
sample.py
import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html")
print()
form = cgi.FieldStorage()
for key in form:
value = form[key].value
print('<p>%s: %s</p>' % (key, value))
現時点の状況
ターミナルから新しいターミナルを開く
ターミナルでコマンド実行
python -m http.server --cgi 8000
ブラウザで確認
結果
理解したこと
- htmlのhead部に文字コードセットをしていないと文字化けする。
formに送信した内容をforで回して取得すると、文字コード順に取得されるらしい。- 文字コード順に取得されるとは限らないらしい。
情報源
Googleで「Python3 CGI」で検索し、出てきたサイトを上から順に試してみた。