ラベル CGI の投稿を表示しています。 すべての投稿を表示
ラベル CGI の投稿を表示しています。 すべての投稿を表示

2017年5月31日水曜日

[Python][CGI]SQLクエリーを実行した結果を表示する

test3.html
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
  <head>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=UTF-8">
    <title>Ajax Test, SQL query</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $('#sendButton').click(function(event) {
          $.post(
            "/cgi-bin/python_test/test3.py",
            { sendValue: $('#animal').val() },
            function(data, textStatus) {
              if (textStatus == 'success') {
                $('#textStatus').text('Success');
              }
              $("#result").html(data);
          }, 'html')
          .fail(function() {
              $("#result").html("Failed");
            }
          );
        });
      });
    </script>
  </head>
  <body>
    動物名<br/>
    <input type="text" name="animal" value="" id="animal"/><br/>
    <button type="button" id="sendButton">送信</button><br/><br/>
    textStatus: <span id="textStatus"></span><br/>
    Result: <span id="result"></span>
  </body>
</html>
test3.py
#!/usr/bin/python
#-*- coding:utf-8 -*-

import cgi
import psycopg2

# エラー発生時にレポートを表示
import cgitb
cgitb.enable()

html0 = """
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"/>
"""

#######################################################################
# DBに接続
#######################################################################
def connectDb():
 connection = psycopg2.connect("dbname=testdb user=username password=password")
 cur = connection.cursor()

 return connection, cur

#######################################################################
# DBから切断
#######################################################################
def disconnectDb(connection, cur):
 # commit
 connection.commit()

 cur.close()
 connection.close()

#######################################################################
# SQL query
#######################################################################
def select(cur, animal):
 sql = "SELECT id FROM animals WHERE name='" + animal + "';"
 print(sql + '<br/>')
 cur.execute(sql)
 result = cur.fetchone()
 if result == None:
  print(animal + ' is not found.<br/>')
 else:
  print(animal + "'s id is " + str(result[0]))

#######################################################################
# Main function
#######################################################################
if __name__ == '__main__':
 print(html0)
 form = cgi.FieldStorage()
 animal = form['sendValue'].value
 print('animal: ' + animal + '<br/>')

 # DBに接続する
 connection, cur = connectDb()

 # SQL query (SELECT)
 id = select(cur, facility)

 # DBから切断する
 disconnectDb(connection, cur)
実行結果(ブラウザに渡されるHTMLソース)
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; CHARSET=UTF-8">
    <title>Ajax Test, SQL query</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $('#sendButton').click(function(event) {
          $.post(
            "/cgi-bin/python_test/test3.py",
            { sendValue: $('#animal').val() },
            function(data, textStatus) {
              if (textStatus == 'success') {
                $('#textStatus').text('Success');
              }
              $("#result").html(data);
          }, 'html')
          .fail(function() {
              $("#result").html("Failed");
            }
          );
        });
      });
    </script>
  </head>
  <body>
    動物名<br>
    <input type="text" name="animal" value="" id="animal"><br>
    <button type="button" id="sendButton">送信</button><br><br>
    textStatus: <span id="textStatus">Success</span><br>
    Result: <span id="result">
      <meta http-equiv="Content-Type" content="text/html; CHARSET=utf-8">
      animal: dog<br>
      SELECT id FROM animals WHERE name='dog';<br>
      dog's id is 3
    </span>
  </body>
</html>

[Python][CGI]Ajax

id="sendButton"の送信ボタンを押した時に、test2.pyに対してname="a"のinput欄に入力したテキストをsendValueという変数に入れて渡す。 python2.pyから返ってきた文字列はid=resultのspan内に格納される。

test2.html
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
  <head>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=UTF-8">
    <title>Ajax Test</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $('#sendButton').click(function(event) {
          $.post(
            "/cgi-bin/python_test/test2.py",
            { sendValue: $('#a').val() },
            function(data, textStatus) {
              if (textStatus == 'success') {
                $('#textStatus').text('Success');
              }
              $("#result").html(data);
          }, 'html')
          .fail(function() {
              $("#result").html("Failed");
            }
          );
        });
      });
    </script>
  </head>
  <body>
    入力欄に文字列を入れると、POST されて応答が返ってきます<br/>
    <input type="text" name="a" value="" id="a"/><br/>
    <button type="button" id="sendButton">送信</button><br/><br/>
    textStatus: <span id="textStatus"></span><br/>
    Result: <span id="result"></span>
  </body>
</html>
test2.py
#!/usr/bin/python
#-*- coding:utf-8 -*-

import cgi

# エラー発生時にレポートを表示
import cgitb
cgitb.enable()

html0 = """
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"/>
"""

#######################################################################
# Main function
#######################################################################
if __name__ == '__main__':
 print(html0)
 form = cgi.FieldStorage()
 #print(form)
 value = form['sendValue'].value
 print('Hello, ' + value)
実行結果(ブラウザに渡されるHTMLソース)
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; CHARSET=UTF-8">
    <title>Ajax Test</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $('#sendButton').click(function(event) {
          $.post(
            "/cgi-bin/python_test/test2.py",
            { sendValue: $('#a').val() },
            function(data, textStatus) {
              if (textStatus == 'success') {
                $('#textStatus').text('Success');
              }
              $("#result").html(data);
          }, 'html')
          .fail(function() {
              $("#result").html("Failed");
            }
          );
        });
      });
    </script>
  </head>
  <body>
    入力欄に文字列を入れると、POST されて応答が返ってきます<br>
    <input type="text" name="a" value="" id="a"><br>
    <button type="button" id="sendButton">送信</button><br><br>
    textStatus: <span id="textStatus">Success</span><br>
    Result: <span id="result">
      <meta http-equiv="Content-Type" content="text/html; CHARSET=utf-8">
      Hello, abc
    </span>
  </body>
</html>

[Python][CGI]FORMからのPOSTデータ受け取り

test1.html
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
  <form name="form" method="POST" action="/cgi-bin/python_test/test1.py">
    name: <input type="text" size="30" name="name"/><br/>
    mail: <input type="text" size="30" name="mail"/><br/>
    <input type="submit" value="submit" name="button"/>
  </form>
  </body>
</html>
上記のページで[Submit]ボタンを押すとtest1.pyが実行される。
test1.py
#!/usr/bin/python
#-*- coding:utf-8 -*-

import cgi

# エラー発生時にレポートを表示
import cgitb
cgitb.enable()

html0 = """
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"/>
<html>
<head>
<title>Test 1</title>
</head>
<body>
"""

html1 = """
</body>
</html>
"""

#######################################################################
# Main function
#######################################################################
if __name__ == '__main__':
 print(html0)
 form = cgi.FieldStorage()
 print('<b>name: </b>' + form['name'].value + '<br/>')
 print('<b>mail: </b>' + form['mail'].value + '<br/>')
 print(html1)
実行結果(ブラウザに渡されるHTMLソース)
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; CHARSET=utf-8">
    <title>Test 1</title>
  </head>
  <body>
    <b>name: </b>aa<br>
    <b>mail: </b>bb<br>
  </body>
</html>

[Python][CGI]Hello, world

test0.py
#!/usr/bin/python
#-*- coding:utf-8 -*-

# エラー発生時にレポートを表示
import cgitb
cgitb.enable()

html = """
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"/>
<html>
<head>
<title>Test 0</title>
</head>
<body>
Hello, world<br/>
</body>
</html>
"""

#######################################################################
# Main function
#######################################################################
if __name__ == '__main__':
 print(html)
実行結果(ブラウザに渡されるHTMLソース)
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; CHARSET=utf-8">
    <title>Test 0</title>
  </head>
  <body>
    Hello, world<br>
  </body>
</html>

2015年8月14日金曜日

[Python][CGI]MySQL からデータを読み込んでグラフを描く

#!/usr/bin/python
# -*- coding:utf-8 -*-
import MySQLdb
import tempfile
import os

# エラー発生時にレポートを表示
import cgitb
cgitb.enable()

html = """
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"/>
<html>
<head>
<title>MySQL & Gnuplot</title>
</head>
<body>
data<br/>
%s
<img src="%s"/>
</body>
</html>
"""

####################################################################
# @brief グラフを描く
####################################################################
def drawGraph(dataFilename, pngfile, xmin, xmax, ymin, ymax):
 # plot データ作成
 (fd, pltFilename) = tempfile.mkstemp()

 # print "Plot tempfile name: %s" % (pltFilename)
 f = os.fdopen(fd, 'w')
 str = """
 set terminal png font "/usr/share/fonts/ipa-gothic/ipag.ttf,12"
 set output '%s'
 set title '各地の気温'
 set xlabel '場所'
 set ylabel '気温'
 set xrange [-1:3]
 set yrange [0:30]
 set boxwidth 0.5 relative
 set style fill solid 0.2
 set grid
 unset key
 plot '%s' using 2:xticlabels(1) with boxes
 """ % (pngfile, dataFilename)
 f.write(str)
 f.close()

 # gnuplot コマンド実行
 os.system("gnuplot %s" % pltFilename)

 # Temporary file 削除
 os.remove(pltFilename)

####################################################################
# @brief Main function
####################################################################
# DB に接続
db = MySQLdb.connect(user="username", passwd="password", db="dbname", charset="utf8")

# SELECT
q = "SELECT `area`, `temperature` FROM `temperature`;"
db.query(q)
result = db.store_result()

# データ表示 & データ格納
num = result.num_rows()
(fd, dataFilename) = tempfile.mkstemp()
f = os.fdopen(fd, 'w')
#print "filename: %s" % filename
data = """
<table border="1">
"""

for row in result.fetch_row(num):
 str = "<tr><td>%s</td><td>%.2f</td></tr>" % (row[0], row[1])
 data = data + str
 str = "%s\t%.2f\n" % (row[0], row[1])
 f.write(str)

data = data + "</table>"
f.close()

# グラフ作成
pngfile = "test03.png"
drawGraph(dataFilename, pngfile, -1, 3, 0, 30)

# Temporary file 削除
os.remove(dataFilename)

print html % (data, "test03.png")
これを実行しても SELinux が書き込みを禁止するので test03.png を cgi-bin 以下に生成することができない。
今は SELinux を一時停止して実験する。
# setenforce 0
この cgi ファイルのある場所に test03.png が作成されるが、cgi 実行権限のあるディレクトリ (cgi-bin) はすべて実行ファイルと解釈されるので画像が表示できない。
そこで httpd.conf の cgi ディレクトリ設定に AddHandler image/png .png を追加する。
<Directory "/var/www/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
AddHandler image/png .png
</Directory>
SELinux を有効のままでファイル書き込みを許可するにはスクリプトを実行するディレクトリの Type を httpd_sys_rw_content_t に変更する。
# ls -Z
drwxrwxrwx. root root unconfined_u:object_r:httpd_sys_script_exec_t:s0 python
# chcon -t httpd_sys_script_rw_t python/
# ls -Z
drwxrwxrwx. root root unconfined_u:object_r:httpd_sys_rw_content_t:s0 python

[Python][CGI]CGI で Cookie を使う

POST されたデータを Cookie で保存するように指示する
cookiePostResult.cgi
#!/usr/bin/python
# -*- coding:utf-8 -*-
import cgi
import cgitb

# エラー発生時にレポートを表示
cgitb.enable()
f = cgi.FieldStorage()
field1 = f.getfirst('field1', '')
field2 = f.getfirst('field2', '')

# Cookie に保存
print "Set-Cookie: FIELD1=%s" % (field1)
print "Set-Cookie: FIELD2=%s" % (field2)
print "\n"

html = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Cookie POST Result</title>
</head>
<body>
<h1>Cookie POST Result</h1>
Field1: %s<br/>
Field2: %s<br/>
<a href="/cgi-bin/python/cookiePostResult2.cgi">次へ</a>
</body>
</html>
"""

print html % (field1, field2)
Set-Cookie でクライアントのブラウザに Cookie 保存するように指示する。

保存された Cookie を読み込んで表示する
cookiePostResult2.cgi
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import cgi
import cgitb
import Cookie

# Cookie の値を読み出す
cookie = Cookie.SimpleCookie()
cookie.load(os.environ["HTTP_COOKIE"])
field1 = cookie["FIELD1"].value
field2 = cookie["FIELD2"].value

html = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Cookie POST Result 2</title>
</head>
<body>
<h1>Cookie POST Result 2</h1>
Field1: %s<br/>
Field2: %s<br/>
</body>
</html>
"""

print html % (field1, field2)