前提
Python3でCGIチャレンジ2後
作業フォルダ
ps1
作業
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>
<!-- ここから追記 -->
<form action="/cgi-bin/readFile.py" method="POST">
<input type="submit" value="ファイル内容表示">
</form>
<!-- ここまで追記 -->
</body>
</html>
readFile.pyを作成。cgi-bin配下に。
readFile.py
import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html")
print()
# どうやらプログラムから見た相対パスではなく、index.htmlからの相対パスらしい(要確認)
file_name = "./file.txt"
try:
f = open(file_name, 'r', encoding='UTF-8')
data = f.read()
print(data)
except Exception as e:
print(e)
finally:
f.close()
ターミナルでコマンド実行して、ローカルでCGIサーバーを起動する。
python -m http.server --cgi 8000
ブラウザで確認
結果
理解したこと
- ボタン名の変更方法
- 何故かファイルの中身は直列で取得される(改行コード無視?)
情報源
Googleで「Python3 ファイル読み込み」で上から順に試した。