「毎日Unity」の技術ブログ

開発で役立つ情報を発信する

【Python】Webアプリの作成/実行方法

[ 記事の内容 ]

この記事では、PythonCGIを使って累乗計算をしてくれるWebアプリケーションの作成方法とローカル環境での実行方法を簡単に紹介します。

[ CGIとは ]

CGIとはCommon Gateway Interfaceの略で、簡単に説明するとWebページを動的に変化させるための仕組みです。この記事ではCGIPythonで作成する方法を紹介しますが、CGIPerlPHP等で作成することもできます。

[ 作成方法 ]

まず下記の画像のように「index.html」と「cgi-bin」フォルダを同じ階層に作成してください。下記の画像ではこれら2つを「test」という名前のフォルダ内に作成していますが、これら2つが同じ階層になるのであればどこに作成しても大丈夫です。
f:id:EDunity:20210119204335p:plain

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」を作成してください。
f:id:EDunity:20210119222522p:plain

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」があるフォルダに指定します。下記はコマンドプロンプトでの例です。
f:id:EDunity:20210119221413p:plain

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」と入力します。
f:id:EDunity:20210119221707p:plain

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

入力したらエンターを押してください。押すと下記の画像のようにサーバーが起動すると思います。
f:id:EDunity:20210119221931p:plain

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」を開いてください。開くと下記の画像と同じ画面になると思います。
f:id:EDunity:20210119222059p:plain
試しに4の5乗を計算してみます。「Base」と「Exponent」に4と5を入力して「Caluclate」ボタンを押してみてください。押した後に「The answer is 1024.」と出力されれば成功です。
f:id:EDunity:20210119222158p:plain

[ 続き ]

今回作成したwebアプリケーションを公開する方法を下記にまとめました。
edunity.hatenablog.com