0
0

More than 1 year has passed since last update.

Python3でCGIチャレンジ1 フォーム送信

Last updated at Posted at 2021-12-03

はじめに

学んだことをもう一回調べ直さなくて済むよう記録することにした。

前提

  • VisualStudioCodeがインストール済み
  • Python3インストール済み

参考までに現在のVisualStudioCodeのバージョンは、1.62.3。
image.png

下準備

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

現時点の状況

image.png

ターミナルから新しいターミナルを開く

image.png

ターミナルでコマンド実行

python -m http.server --cgi 8000

image.png

ブラウザで確認

[http://localhost:8000]

結果

初期画面
image.png

文字入力
image.png

送信後
image.png

理解したこと

  • htmlのhead部に文字コードセットをしていないと文字化けする。
  • formに送信した内容をforで回して取得すると、文字コード順に取得されるらしい。
  • 文字コード順に取得されるとは限らないらしい。

情報源

Googleで「Python3 CGI」で検索し、出てきたサイトを上から順に試してみた。

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