web.pyでpingアプリ
最近はtwitterでつぶやくばかりではてな日記は書いてませんね。こっちに書かないと回想できないのでたまにはこっちにも書きます。
前準備
web.pyをインストール
$ easy_install web.py
- 現時点でのバージョンは0.32。
作ってみる
ディレクトリ構成
hoge/ - main.py - static/ - jquery-1.4.2.min.js - test.css - test.js
- web.pyはstatic/ディレクトリを作れば勝手に静的ファイルとして扱ってくれるらしい。
main.py
# -*- coding: utf-8 -*- import web import os from subprocess import * urls = ( r'^/test$', 'test', r'^/.*$', 'index', ) app = web.application(urls, globals(), autoreload = True) class index: def GET(self): return '''\ <html> <head> <title>home</title> <link rel="stylesheet" type="text/css" href="/static/test.css"/> <script type="text/javascript" src="/static/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="/static/test.js"></script> </head> <body> <span id="title">this is home.</span><br> <input id="id_host" type="text" value="localhost"> <a href="javascript:void(0)" onclick="test()">ping</a> <pre id="result">ready</pre> </body> </html>''' class test: def POST(self): i = web.input() conv = Popen('ping '+i.host, stdout=PIPE) ret = conv.stdout.read() ret = ret.strip() return ret if __name__ == '__main__': web.webapi.internalerror = web.debugerror app.run()
test.js
function test() { $("#result").text("ready"); $.post( "/test", { host: $("#id_host").val() }, function(result){ $("#result").text(result); }); return false; }
test.css
body { background-color: lightyellow; font: 8pt tahoma; } span#title { background-color: lightblue; font: 12pt impact; color: white; padding: 2px; } pre#result { background-color: silver; color: black; font: 10pt "MS UIGothic"; width: 500px; padding: 4px; }
jquery-1.4.2.min.js
- http://jquery.com/ からダウンロード
実行してみる
サーバーを起動
$ cd hoge $ python main.py 127.0.0.1:8080
- web.pyは引数を指定しないとデフォルトで誰からでもアクセスできる(0.0.0.0:8080)になるので注意。
ウェブブラウザでアクセス
- http://localhost:8080/を開く
- こんな感じになるはず。pingをクリックすると裏でpingを実行して終了したら結果を表示。
感想
- webアプリ結構面白い。
- web.pyでローカル用のランチャとか簡単に作れそう。
- jQuery楽ちん&楽しい。
- 「this is home」は関係無いな。消せばよかった。まぁいいか。