LoginSignup
21
21

More than 3 years have passed since last update.

python-cgiで超シンプルな画面遷移を書く

Posted at

cgiとは

Common Gateway Interfaceの略称。
Webサーバが、Webブラウザの要求に応じて、外部プログラムを呼び出し
その実行結果をWebブラウザに送信する仕組み。

image.png

仕組み

Webサーバーにブラウザからアクセスすることで
Pythonファイルが実行され、
その処理結果をhtmlとしてWebサーバーに返却する。
image.png
本記事では、返却するhtmlを別ファイルとして定義し、
Pythonファイルの中でそのhtmlファイルを読み込んでいます。

ディレクトリ構成

├── cgiserver.py
├── cgi-bin
│   └── test.py
└── html
     ├── view_001.html
     └── view_002.html

※ cgiserver.py, cgi-bin以外は任意の名称で良いです。

サンプルコード(Python)

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import cgi
import codecs

form = cgi.FieldStorage()

# 初回ロード時
if form.list == []:
    html = codecs.open('./html/view_001.html', 'r', 'utf-8').read()
# SUBMITボタン押下時
else:
    html = codecs.open('./html/view_002.html', 'r', 'utf-8').read()

print("")
print(html)

import cgi

Pythonの標準ライブラリであるcgiモジュールを
インポートすることでpython-cgiを使えるようになります

print()

Pythonファイルをcgiプログラムとして実行すると
print()の出力は標準出力ではなく
Web画面への描画になります。

本記事では、
L.17でprint()にhtmlタグを渡すことでWebページを表現しています。

codecs.open()

描画するhtmlファイルの内容を(String型として)読み込みます。
それを最後にprint()に渡すことでWeb画面に描画します。

cgi.FieldStorafe()

このクラスをインスタンス化することで
クライアント側のフォームの情報を取得できます。

この取得した情報によって処理を分岐することで、描画するhtmlを振り分けています。

サンプルコード(html)

Web画面に描画したいhtmlソースをそのまま記述します。

view_001.html

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
  <title>topPage</title>
</head>
  <p>This is Top Page.</p>
  <form name="formSubmit" action="test.py">
    <input type="submit" name="button" value="SUBMIT">
  </form>
</body>
</html>

view_002.html

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
  <title>movedPage</title>
</head>
  <p>Success Page transition</p>
</body>
</html>

動かし方

cgiserver.pyがある階層まで移動して以下のコマンドを実行して、Pythonサーバーを立ち上げます。

python -m http.server --cgi

その状態でURLを指定してアクセスします。
http://localhost:8000/cgi-bin/cgibin.py

すると、Pythonファイルで出力しているhtmlがブラウザに表示されます。

img_0722_001.png

ボタンを押下すると、Pythonで処理している通りに、表示するhtmlが切り替わります。

img_0722_002.png

まとめ

python-cgiモジュールを使うことでPythonでWeb画面処理、サーバー処理を実現出来ました。

今回はシンプルな画面遷移だけ触れましたが、
cgi.FieldStorage()を上手く使うことで
Webページ間のデータの受け渡しやクライアント側のフォームの内容での処理分岐なども実現できます。

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