[ CGIとは ]
CGIとはCommon Gateway Interfaceの略で、簡単に説明するとWebページを動的に変化させるための仕組みです。この記事ではCGIをPythonで作成する方法を紹介しますが、CGIはPerlやPHP等で作成することもできます。
[ 作成方法 ]
まず下記の画像のように「index.html」と「cgi-bin」フォルダを同じ階層に作成してください。下記の画像ではこれら2つを「test」という名前のフォルダ内に作成していますが、これら2つが同じ階層になるのであればどこに作成しても大丈夫です。
index.htmlの中身
<html> <head> <meta charset="utf-8"> <title>Exponents Calculator</title> </head> <body> <h1>Exponents Calculator</h1> <form action="/cgi-bin/sample.py" method="POST"> Base: <input type="text" name="Value1"> <br> Exponent: <input type="text" name="Value2"> <br> <br> <input type="submit" value="Calculate"> </form> </body> </html>
次に先ほど作成した「cgi-bin」フォルダの中に「sample.py」を作成してください。
sample.pyの中身
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- import cgi Forms = cgi.FieldStorage() Value1 = int(Forms["Value1"].value) Value2 = int(Forms["Value2"].value) Answer = (Value1 ** Value2) Text = """ <html> <head> <meta charset="utf-8"> <title>Exponents Calculator</title> </head> <body> <h1>Exponents Calculator</h1> The answer is %s. <br> <br> <a href="../index.html">Back</a> </body> </html> """%Answer print(Text)
[ 実行方法 ]
まずWindowsの場合はコマンドプロンプト、Macの場合はターミナルを起動してカレントフォルダを先ほど作成した「index.html」と「cgi-bin」があるフォルダに指定します。下記はコマンドプロンプトでの例です。
Microsoft Windows [Version 10.0.18363.1316] (c) 2019 Microsoft Corporation. All rights reserved. C:\Users\EDunity>cd C:\Users\EDunity\Desktop\test C:\Users\EDunity\Desktop\test>
次に下記の画像のように「py -m http.server --cgi 8000」と入力します。
Microsoft Windows [Version 10.0.18363.1316] (c) 2019 Microsoft Corporation. All rights reserved. C:\Users\EDunity>cd C:\Users\EDunity\Desktop\test C:\Users\EDunity\Desktop\test>py -m http.server --cgi 8000
入力したらエンターを押してください。押すと下記の画像のようにサーバーが起動すると思います。
Microsoft Windows [Version 10.0.18363.1316] (c) 2019 Microsoft Corporation. All rights reserved. C:\Users\EDunity>cd C:\Users\EDunity\Desktop\test C:\Users\EDunity\Desktop\test>py -m http.server --cgi 8000 Serving HTTP on :: port 8000 (http://[::]:8000/) ...
サーバーが起動したら最後に「http://localhost:8000」を開いてください。開くと下記の画像と同じ画面になると思います。
試しに4の5乗を計算してみます。「Base」と「Exponent」に4と5を入力して「Caluclate」ボタンを押してみてください。押した後に「The answer is 1024.」と出力されれば成功です。
[ 続き ]
今回作成したwebアプリケーションを公開する方法を下記にまとめました。
edunity.hatenablog.com