0
0

More than 1 year has passed since last update.

Python3でCGIチャレンジ3 ファイル読み込み

Posted at

前提

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

ブラウザで確認

[http://localhost:8000]

結果

ファイル
image.png

ブラウザ
追加したボタンが下にある。押す。
image.png

ファイルの内容が表示されている
image.png

理解したこと

  • ボタン名の変更方法
  • 何故かファイルの中身は直列で取得される(改行コード無視?)

情報源

Googleで「Python3 ファイル読み込み」で上から順に試した。

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