PythonとCGI

 PerlやTclと同様、PythonでCGIスクリプトを書くことも、 もちろん可能です。下は簡単なサンプルです。

#! /Wintools/python22/python

import os, time
print "Content-Type: text/html\n" ; # 1行空行を出力
tm = time.localtime(time.time())
print """
<html><head><title>CGI Sample Output by Python</title></head>
<body bgcolor="white">
<h2>ようこそ</h2>
"""
print "現在、" + time.strftime("%Y/%m/%d %H:%M:%S", tm) + " です。<br>"
print "あなたがお使いのWebブラウザは、" + os.environ["HTTP_USER_AGENT"] +\
      "ですね?<br>"
print """
</body></html>
"""
# end.

 環境はWindowsXP(!!)、Apache 1.3.22、Python 2.2です。 Webサーバから渡される環境情報は環境変数os.environで取得できます。 CGI一般の話については、ここでは省略します。

 さて、CGIフォーム変数を使う場合には、Python処理系に標準でついている cgiモジュールをインポートすると便利です。 まずは、「名前」と「メールアドレス」を入力する簡単なフォームをもつHTML文書です。

<html>
<body bgcolor="white">

<h2>サンプル</h2>

<form action="/cgi-bin/pyform1.cgi" method="post">
名前:<input type="text" width="20" name="name"><br>
メールアドレス:<input type="text" width="40" name="mail_address"><br>
<br>
<input type="submit" value="決定">
</form>
</body>
</html>

そして、この入力内容を解析して、画面に表示する CGIスクリプトの例は次のようになります。

#! /Wintools/python22/python

import cgi
print "Content-Type: text/html\n" ; # 1行空行を出力
print """
<html><head><title>CGI Sample Output by Python</title></head>
<body bgcolor="white">
<h2>ようこそ</h2>
"""

form = cgi.FieldStorage()
name = form["name"].value
mail_address = form["mail_address"].value

print "こんにちは、" + name + " (" + mail_address + ") さん。<br>"
print """
</body></html>
"""
# end.

セクションのサブメニューに戻る
(first uploaded 2002/03/16 last updated 2002/03/17)