index.html , python.cgi を作成
index.html
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /></head>
<h1>入力値の演算を表示</h1>
<form action="python.cgi" method="POST">
値1を入力:
<input type="number" name="a"><BR><BR>
記号を入力:
<INPUT type="radio" name="b" value="+"> +
<INPUT type="radio" name="b" value="-"> -
<INPUT type="radio" name="b" value="x"> x
<INPUT type="radio" name="b" value="/"> ÷ <BR><BR>
値2を入力:
<input type="number" name="c"><BR>
<BR>
<input type="submit" name="submit" value=" = ">
</form>
</body>
</html>
python.cgi
#!/opt/alt/python37/bin/python3
import sys
import io
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
import cgi
import cgitb
import math
import json
cgitb.enable()
form = cgi.FieldStorage() #クエリ文字列の値を取得
if "a" not in form or "b" not in form or "c" not in form:
a=0
b="e"
c=0
else:
a = int(form['a'].value)
b = form['b'].value
c = int(form['c'].value)
if b == "+" :
d = str(a + c)
elif b == "-" :
d = str(a - c)
elif b == "x" :
d = str(a * c)
elif b == "/" and c != 0:
d = str(a / c)
else:
d = "解なし"
print("Content-type: text/html; charset=utf-8\n")
htmlText = '''
<!DOCTYPE html>
<html>
<head><meta charset="shift-jis" /></head>
<p>入力値の計算は %s<br/></p>
<hr/>
<a href="index.html">戻る</a>
</body>
</html>
'''