Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Python3の標準ライブラリのみでCGI その1:とりあえず簡単なモノ

業態上、作るシステムは小型なのが多いです。
大規模アクセスはそもそも仕様外なのでCGIでも十分なケースは少なくありません。
CGIというとPHPのイメージがあるのですが、仕組み上はPythonだろうがLispだろうが実行はできるおのこと。

実際のところ

とりあえず動きを見るため「ページのボタンを押したら現在時刻を標準出力に出す」という単純なのを実装してみます。

<!DOCTYPE html>
<html>
<head>
    <title>Call Python Script</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button id="myButton">Get Current Time</button>

    <p id="response"></p>

    <script>
        $(document).ready(function(){
            $("#myButton").click(function(){
                $.ajax({
                    url: "/path/to/callAction.py",  //実際のPythonスクリプトのパスを指定
                    context: document.body,
                    success: function(response) {
                        $('#response').html(response);
                    },
                    error: function(error){
                        console.log(error);
                    }
                });
            });
        });
    </script>
</body>
</html>

CGI本体

#!/usr/bin/env python3
# ↑ 適切なパスを指定

import cgi
import cgitb
import datetime

cgitb.enable() # CGIアクションを有効化

print("Content-Type: text/html")    # レスポンスヘッダ
print()                             # 空文字をつけてヘッダ終了

# 現在時刻の取得
current_time = datetime.datetime.now()

print(current_time) 

実行

特に性能も必要ないしルーティングも無いので組み込みのhttp.serverCGIオプションを付けて実行

$ python -m http.server --cgi 8000