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

2017年9月6日水曜日

[Python][MongoDB]PyMongo

PyMongoはPythonからMongDBを使うためのAPI

インストール

# yum install python-pymongo

データの表示

#-*- coding: utf-8 -*-
import pymongo
import pytz

#######################################################################
# Main function
#######################################################################
if __name__ == '__main__':
# MongoDBに接続するためのclientを作成する
client = pymongo.MongoClient()

# Databaseに接続する
db = client.test

# Collectionを取得する
collection = db.tbl1

# find()
print('find()')
documents = collection.find()
for doc in documents:
#print(doc)
print('%s\t%d' % (doc['message'], doc['value']))

print('\n')
print("find({'message':'hello'})")
documents = collection.find({'message':'hello'})
print('count=%d' % (documents.count()))
for doc in documents:
#print(doc)
print('%s\t%d' % (doc['message'], doc['value']))

print('\n')
print("find({'value':{'$gte':10}})")
documents = collection.find({'value':{'$gte':10}})
print('count=%d' % (documents.count()))
for doc in documents:
#print(doc)
print('%s\t%d' % (doc['message'], doc['value']))
実行結果
$ python test3.py
find()
hello 10
goodbye 25

find({'message':'hello'})
count=1
hello 10

find({'value':{'$gte':10}})
count=2
hello 10
goodbye 25

[Python]jsonモジュール

test0.py
#-*- coding: utf-8 -*-
import json

#######################################################################
# Main function
#######################################################################
if __name__ == '__main__':
# jsonファイル(辞書型)の読み込み
print('=== read test0_dict_read.txt ===')
f = open('test0_dict_read.txt', 'r')
json_dict = json.load(f)
f.close()

print(json_dict)
print(json_dict['book1'])
print(json_dict['book1']["title"])
print(json.dumps(json_dict, indent=4))

# 辞書型をjsonファイルへ書き出し
print('=== write test0_dict_write.txt ===')
json_dict = {}
data = {}
data['name'] = 'tokyo'
data['temperature_high'] = 37.7
data['temperature_low'] = -2.6
json_dict["prefecture_1"] = data

print(json.dumps(json_dict, indent=4))

f = open('test0_dict_write.txt', 'w')
json.dump(json_dict, f)
f.close()

# jsonファイル(配列型)の読み込み
print('=== read test0_list_read.txt ===')
f = open('test0_list_read.txt', 'r')
json_list = json.load(f)
f.close()

print(json_list)
print(json_list[0])
print(json_list[0]['title'])
print(json.dumps(json_list, indent=4))

# 配列型をjsonファイルへ書き出し
print('=== write test0_list_write.txt ===')
json_list = []
data = {}
data['name'] = 'tokyo'
data['temperature_high'] = 37.7
data['temperature_low'] = -2.6
json_list.append(data)

data = {}
data['name'] = 'naha'
data['temperature_high'] = 33.9
data['temperature_low'] = 6.1
json_list.append(data)

print(json.dumps(json_list, indent=4))

f = open('test0_list_write.txt', 'w')
json.dump(json_list, f)
f.close()
test0_dict_read.txt
{
"book1":{
"title": "Python Beginners",
"year": 2005 ,
"page": 399
},
"book2":{
"title": "Python Developers",
"year": 2006 ,
"page": 650
}
}
test0_list_read.txt
[
{
"title": "Python Beginners",
"year": 2005 ,
"page": 399
},
{
"title": "Python Developers",
"year": 2006 ,
"page": 650
}
]
実行結果 コンソール
$ python test0.py
=== read test0_dict_read.txt ===
{u'book1': {u'year': 2005, u'page': 399, u'title': u'Python Beginners'}, u'book2': {u'year': 2006, u'page': 650, u'title': u'Python Developers'}}
{u'year': 2005, u'page': 399, u'title': u'Python Beginners'}
Python Beginners
{
  "book1": {
  "year": 2005,
  "page": 399,
  "title": "Python Beginners"
  },
  "book2": {
  "year": 2006,
  "page": 650,
  "title": "Python Developers"
  }
}
=== write test0_dict_write.txt ===
{
  "prefecture_1": {
  "temperature_high": 37.7,
  "temperature_low": -2.6,
  "name": "tokyo"
  }
}
=== read test0_list_read.txt ===
[{u'year': 2005, u'page': 399, u'title': u'Python Beginners'}, {u'year': 2006, u'page': 650, u'title': u'Python Developers'}]
{u'year': 2005, u'page': 399, u'title': u'Python Beginners'}
Python Beginners
[
  {
  "year": 2005,
  "page": 399,
  "title": "Python Beginners"
  },
  {
  "year": 2006,
  "page": 650,
  "title": "Python Developers"
  }
]
=== write test0_list_write.txt ===
[
  {
  "temperature_high": 37.7,
  "temperature_low": -2.6,
  "name": "tokyo"
  },
  {
  "temperature_high": 33.9,
  "temperature_low": 6.1,
  "name": "naha"
  }
]
test0_dict_write.txt
{"prefecture_1": {"temperature_high": 37.7, "temperature_low": -2.6, "name": "tokyo"}}
test0_list_write.txt
[{"temperature_high": 37.7, "temperature_low": -2.6, "name": "tokyo"}, {"temperature_high": 33.9, "temperature_low": 6.1, "name": "naha"}]

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月15日土曜日

[Python]PyMedia

PyMedia から最新版 (pymedia-1.3.7.3.tar.gz, 2014/08/11時点) をダウンロードする。 ダウンロードしたファイルを解凍する。
$ tar zxvf pymedia-1.3.7.3.tar.gz
必要なライブラリをインストールする。 ライブラリが足りないとビルドする時に下記のように表示される。
$ python setup.py build
Using UNIX configuration...

OGG : not found
VORBIS : not found
FAAD : not found
MP3LAME : not found
VORBISENC : not found
ALSA : not found
Continue building pymedia ? [Y,n]:
依存関係解消できず。(2014/08/11) ビルド
$ python setup.py build
インストール
# python setup.py install

2015年8月14日金曜日

[Python][pyExcelerator]動作確認

次のデータが入った Excel ファイルを準備する
January February March April May June July August September October November December
tokyo 7.0 6.5 9.1 12.4 19.0 23.6 28.0 29.6 25.1 18.9 13.5 9.9
naha 16.8 18.3 19.9 21.2 23.8 26.7 28.7 28.9 28.0 25.7 21.4 18.1
sapporo -2.0 -3.2 -0.1 5.5 12.2 19.2 22.1 24.8 20.0 12.2 5.9 0.6
2 枚目の sheet, 3 枚目の sheet は空、Sheet 名は Sheet2, Sheet3
test00.py
# -*- coding:utf-8 -*-
import pyExcelerator

xlsSheets = pyExcelerator.parse_xls("test00.xls")
# (Sheet 名, シートの中身) というリストで格納される
print xlsSheets
for sheetName, values in xlsSheets:
    print "Sheet name: %s" % (sheetName)
    print "values.keys(): ", sorted(values.keys())
    row = ""
    for rowIdx, colIdx in sorted(values.keys()):
        v = values[(rowIdx, colIdx)]
        print "(%d, %d): %s" % (rowIdx, colIdx, v)

実行結果
> python test00.py
[(u'Sheet1', {(1, 3): 9.1, (3, 0): u'sapporo', (2, 8): 28.9, (3, 11): 5.9, (0, 7): u'July', (1, 6): 23.6, (0, 10): u'October', (2, 10): 25.7, (3, 7): 22.1, (0,3): u'March', (1, 11): 13.5, (2, 5): 23.8, (1, 2): 6.5, (3, 3): -0.1, (2, 9): 28.0, (2, 0): u'naha', (3, 10): 12.2, (1, 5): 19.0, (0, 11): u'November', (3, 6):19.2, (0, 4): u'April', (1, 10): 18.9, (1, 1): 7.0, (2, 7): 28.7, (3, 2): -3.2,(2, 6): 26.7, (2, 2): 18.3, (1, 4): 12.4, (0, 12): u'December', (2, 1): 16.8, (3, 9): 20.0, (0, 5): u'May', (1, 9): 25.1, (1, 0): u'tokyo', (0, 8): u'August', (3, 5): 12.2, (0, 1): u'January', (3, 12): 0.6, (1, 12): 9.9, (3, 1): -2.0, (2, 11): 21.4, (2, 4): 21.2, (3, 8): 24.8, (0, 6): u'June', (1, 8): 29.6, (1, 7): 28.0, (0, 9): u'September', (2, 3): 19.9, (3, 4): 5.5, (0, 2): u'February', (2, 12): 18.1}), (u'Sheet2', {}), (u'Sheet3', {})]
Sheet name: Sheet1
values.keys():  [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1,5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12)]
(0, 1): January
(0, 2): February
(0, 3): March
(0, 4): April
(0, 5): May
(0, 6): June
(0, 7): July
(0, 8): August
(0, 9): September
(0, 10): October
(0, 11): November
(0, 12): December
(1, 0): tokyo
(1, 1): 7.0
(1, 2): 6.5
(1, 3): 9.1
(1, 4): 12.4
(1, 5): 19.0
(1, 6): 23.6
(1, 7): 28.0
(1, 8): 29.6
(1, 9): 25.1
(1, 10): 18.9
(1, 11): 13.5
(1, 12): 9.9
(2, 0): naha
(2, 1): 16.8
(2, 2): 18.3
(2, 3): 19.9
(2, 4): 21.2
(2, 5): 23.8
(2, 6): 26.7
(2, 7): 28.7
(2, 8): 28.9
(2, 9): 28.0
(2, 10): 25.7
(2, 11): 21.4
(2, 12): 18.1
(3, 0): sapporo
(3, 1): -2.0
(3, 2): -3.2
(3, 3): -0.1
(3, 4): 5.5
(3, 5): 12.2
(3, 6): 19.2
(3, 7): 22.1
(3, 8): 24.8
(3, 9): 20.0
(3, 10): 12.2
(3, 11): 5.9
(3, 12): 0.6
Sheet name: Sheet2
values.keys():  []
Sheet name: Sheet3
values.keys():  []

[Python][pyExcelerator]インストール

  1. pyExcelerator から pyexcelerator-0.6.4.1.zip (2011/05/04 現在) をダウンロードする
  2. setup.py を実行してインストールする
    > python setup.py install
    

[Python]mod_wsgiインストール

  1. mod_wsgi をインストール
    # yum install mod_wsgi
    
  2. /etc/httpd/conf/httpd.conf を編集
    # mod_wsgi
    LoadModule wsgi_module modules/mod_wsgi.so
    WSGIScriptAlias        /wsgi /var/www/cgi-bin/python/wsgi/test00.wsgi
    <Directory /var/www/cgi-bin/python/wsgi>
        Order allow,deny
        Allow from all
    </Directory>
    
  3. Test Script 作成
    test00.wsgi
    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    def application(environ, start_response):
        status = '200 OK'
        output = "Hello, world!"
        response_header = [('Content-type', 'text/plain'),
                           ('Content-Length', str(len(output)))]
        start_response(status, response_header)
        return output
    
  4. Test script 配置
    httpd.conf で設定した WSGIScriptAlias (/var/www/cgi-bin/python/wsgi) に上記のスクリプトを置く
  5. http://localhost/wsgi/ へアクセスする

[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)

[Python][numpy]行列計算

転置行列 (transpose)
a = numpy.arange(0, 6).reshape(2, 3) # 2x3 行列
print "arange(0, 6).reshapre(2, 3):"
print a
print "transpose():"
print a.transpose() # 転置行列 (transpose)
arange(0, 6).reshapre(2, 3):
[[0 1 2]
[3 4 5]]
transpose():
[[0 3]
[1 4]
[2 5]]



逆行列 (inverse)
a = numpy.arange(0, 4).reshape(2, 2) # 2x2 行列
print "arange(0, 4).reshapre(2, 2):"
print a
print "linalg.inv(a):"
print numpy.linalg.inv(a) # 逆行列 (inverse)
arange(0, 4).reshapre(2, 2):
[[0 1]
[2 3]]
linalg.inv(a):
[[-1.5 0.5]
[ 1. 0. ]]


[Python][numpy]様々な行列

すべて 0 の行列
a = numpy.zeros((3, 4)) # 3x4 行列
print "zeros((3, 4)):"
print a
zeros((3, 4)):
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]


すべて 1 の行列
a = numpy.ones((3, 4)) # 3x4 行列
print "ones((3, 4)):"
print a
ones((3, 4)):
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]


単位行列
i = numpy.identity(3) # 3x3 単位行列 (identity matirx)
print "identity(3):"
print i
identity(3):
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]


要素を指定して行列生成
a = numpy.array([0, 2, 3, 4, 6, 8]).reshape(2, 3)
print "array([0, 2, 3, 4, 6, 8]).reshape(2, 3):"
print a
array([0, 2, 3, 4, 6, 8]).reshape(2, 3):
[[0 2 3]
[4 6 8]]


特定の対角のみ 1 にする行列
a = numpy.eye(3)
print "eye(3):"
print a
a = numpy.eye(3, k=1)
print "eye(3, k=1):"
print a
eye(3):
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
eye(3, k=1):
[[ 0. 1. 0.]
[ 0. 0. 1.]
[ 0. 0. 0.]]


[Python][numpy]numpy 事始

# -*- coding:utf-8 -*-
import numpy

a = numpy.arange(5) # start:0, stop:5
print "arange(5): ",
print a

a = numpy.arange(3, 10) # start:3, stop:10
print "arange(3, 10): ",
print a

a = numpy.arange(3, 10, 2) # start:3, stop:10, step:2
print "arange(3, 10, 2): ",
print a

a = numpy.linspace(0, 2, 6) # 0 から 2 までを 6 段階に線形分割
print "linespace(0, 2, 6): ",
print a

a = numpy.arange(10).reshape(2, 5)
print "arange(10).reshape(2, 5):"
print a
print "a.shape: ",
print a.shape
print "a.ndim: ",
print a.ndim
実行結果
> python test00.py
arange(5): [0 1 2 3 4]
arange(3, 10): [3 4 5 6 7 8 9]
arange(3, 10, 2): [3 5 7 9]
linespace(0, 2, 6): [ 0. 0.4 0.8 1.2 1.6 2. ]
arange(10).reshape(2, 5):
[[0 1 2 3 4]
[5 6 7 8 9]]
a.shape: (2, 5)
a.ndim: 2
lispace(0, 2, 6) で 0 から 2 までを 6 段階に線形分割した数列を得られる。
arange(10).reshapre(2, 5) で 0 から 10 まで (10 は含まず) の数値 (0 - 9) を 2x5 行列に並び替えている

[Python][Paramiko(sftp)]カレントディレクトリのファイルをサーバーにアップする

ソースコード
# -*- coding:utf-8 -*-
##########################################################################
# ファイルアップロードスクリプト
##########################################################################
import os
import re
import paramiko

## Upload files
def uploadFiles(top, exp):
    for file in os.listdir(top):
    if re.search(exp, file):
        print top + file
        sfconn.put(top + file, top + file)

## Main function
host = 'serveraddress'
user = 'username'
password = 'password'

currentDir = ''
dstDir = 'documents/' + currentDir
dstImgDir = 'documents/' + currentDir + 'img'

conn = paramiko.SSHClient()
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn.connect(host, username=user, password=password)
sfconn = conn.open_sftp()

sfconn.chdir(dstDir)

uploadFiles('./', 'html$')
uploadFiles('./img/', 'png$')

sfconn.close()
conn.close() 

[Python][Paramiko(sftp)]基本的な使い方

情報元: Paramiko
ソースコード
# -*- coding:utf-8 -*-
import paramiko

host = 'serveraddress'
user = 'username'
password = 'password'

conn = paramiko.SSHClient()
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn.connect(host, username=user, password=password)
sfconn = conn.open_sftp()

# カレントディレクトリのファイル一覧を取得
files = sfconn.listdir()
for f in files:
    print f

# ファイルを置く・取得する
sfconn.get('test.txt', 'test.txt')
sfconn.put('paramiko.txt', './paramiko.txt')

sfconn.close()
conn.close()

[Python][HTTP]Cookie 処理

urllib2.HTTPCookieProcessor() を使って Cookie 処理を行う。
# -*- coding: utf-8 -*-
## Cookie を使う
import urllib
import urllib2
import cookielib

# POST データ作成
req = {'field1':'abcde', 'field2':'12334'}
print req
params = urllib.urlencode(req)
print params

# Cookie handler
cj = cookielib.CookieJar()
cookieHandler = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookieHandler)
urllib2.install_opener(opener)

# localhost の Web サーバーに IIS を使っている場合は localhost 指定の Cookie を
# 作ることができないのでエラー終了する
url = 'http://localhost/cgi-bin/python/cookiePostResult.cgi'
request = urllib2.Request(url, params)
f = urllib2.urlopen(request)
print f.info()
data = f.read()
print data
print "================"
for index, cookie in enumerate(cj):
print index, ':', cookie
print cj
print "================"
url = 'http://localhost/cgi-bin/python/cookiePostResult2.cgi'
request = urllib2.Request(url)
f = urllib2.urlopen(request)
data = f.read()
print data
実行結果
$ python test04.py
{'field2': '12334', 'field1': 'abcde'}
field2=12334&field1=abcde
Date: Sun, 16 Jan 2011 07:12:21 GMT
Server: Apache/2.2.17 (Fedora)
Set-Cookie: FIELD1=abcde
Set-Cookie: FIELD2=12334
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

<!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: abcde<br/>
Field2: 12334<br/>
<a href="/cgi-bin/python/cookiePostResult2.cgi">次へ</a>
</body>
</html>
================
0 : <Cookie FIELD1=abcde for localhost.local/cgi-bin/python>
1 : <Cookie FIELD2=12334 for localhost.local/cgi-bin/python>
<cookielib.CookieJar[<Cookie FIELD1=abcde for localhost.local/cgi-bin/python>, <Cookie FIELD2=12334 for localhost.local/cgi-bin/python>]>
================
<!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: abcde<br/>
Field2: 12334<br/>
</body>
</html>
Web サーバーが IIS の場合 localhost の名前解決ができない場合に Cookie の保存ができないようだ。実験した環境では Cookie の保存ができず urlopen() でエラーとなった。
Linux Apache でテストした時は localhost 指定でも問題なく urlopen() できた。

[Python][HTTP]POST

POST するデータを urllib.urlencode() で作成し、urllib2.Request() で POST 先 URL とまとめてからアクセスする。
# -*- coding: utf-8 -*-
## POST
import urllib
import urllib2

# POST データ作成
req = {'field1':'abcde', 'field2':'12334'}
print req
params = urllib.urlencode(req)
print params
url = 'http://localhost/cgi-bin/python/postResult.cgi'
request = urllib2.Request(url, params)
f = urllib2.urlopen(request)
data = f.read()
print data
実行結果
$ python test03.py
{'field2': '12334', 'field1': 'abcde'}
field2=12334&field1=abcde
<!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>POST Result</title>
</head>
<body>
<h1>POST Result</h1>
Field1: abcde<br/>
Field2: 12334<br/>
</body>
</html>

[Python][HTTP]ファイルをダウンロード

read したファイルを write でファイルに書き出すことでファイルをダウンロードする。
# -*- coding: utf-8 -*-
## HTTP でファイルをダウンロードする
import urllib2

url = 'http://ftp.gnu.org/gnu/hello/hello-2.6.tar.gz'
f = urllib2.urlopen(url)
data = f.read()

# 出力先ファイルを指定して書き込む
out = open("hello-2.6.tar.gz", "wb")
out.write(data)
out.close()