サーバに処理内容のリクエストを送信する

前回は、サーバ側で何か処理をさせるところまでやった。クライアント側からは、何の指示もしていなかったので、今回は、クライアントからの指示内容に従って、サーバの処理を変える方法を検討してみた。
クライアント側がブラウザで見る画面は以下の通り。ラジオボタンでコマンドを選択する。submitボタンを押すとPOSTでクエリを送信する。

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
  <form action="/cgi-bin/command.py" method="POST">
    Select a command<br />
    <input type="radio" name="command" value="uname"/>uname
    <input type="radio" name="command" value="pwd"/>pwd
    <br />
    <input type="submit" name="submit" />
  </form>
</body>
</html>

サーバ側で動かすスクリプトcommand.pyは以下の通り。commandの値を受け取り、事前に決められたコマンドを実行し、出力結果をhtml表示する。

#!/usr/bin/env python

import cgi
import subprocess

form = cgi.FieldStorage()
cmd = form.getvalue('command', '')

p = subprocess.Popen([cmd],shell=True,
                     stdin=subprocess.PIPE,stdout=subprocess.PIPE,
                     close_fds=True)
out = p.stdout.readline()

print "Content-type: text/html\n"
print "<html><body>\n"
print out
print "</body></html>"

ここまでの進捗を絵にしておく。