【Python】Tornado で ローカルでWEBサーバーを起動して Hello World してみる。
おはようございます。
今回は Python で人気のあるフレームワーク「Tornado(トルネード)」を使ってローカルでWEBサーバーを起動し、WEBページに Hello World を出力してみました。
Tornadoについてはまとめている方が沢山いらっしゃるので詳しい説明は割愛させていただきます。
Python のインストールについては次の記事を参考にしていただければ。
【Python】 Python3 のインストールから Hello World まで
スポンサーリンク
ダウンロード
https://pypi.python.org/pypi/tornado/4.1
緑色のDownloadボタンをクリックします。
インストール
ダウンロードしたファイルを展開し、
コマンドプロンプトより展開したディレクトリに移動、下記のコマンドを実行する
python setup.py install
コマンドプロンプトに色々出力された後、出力が止まってエラーが出ていなければOKです。
プログラムの作成
クラス
server.py
import os
import tornado.ioloop
import tornado.web
import signal
import logging
from tornado.options import options
is_closing = False
def signal_handler(signum, frame):
global is_closing
logging.info('exiting...')
is_closing = True
def try_exit():
global is_closing
if is_closing:
# clean up here
tornado.ioloop.IOLoop.instance().stop()
logging.info('exit success')
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
application = tornado.web.Application([
(r"/", MainHandler)
],
template_path=os.path.join(os.getcwd(), "templates"),
static_path=os.path.join(os.getcwd(), "css"),
)
if __name__ == "__main__":
tornado.options.parse_command_line()
signal.signal(signal.SIGINT, signal_handler)
application.listen(8888)
logging.info('server started')
tornado.ioloop.PeriodicCallback(try_exit, 100).start()
tornado.ioloop.IOLoop.instance().start()
CSS
css/style.css
body {
font-family:'Lucida Grande', 'Hiragino Kaku Gothic ProN', 'ヒラギノ角ゴ ProN W3', "MS Pゴシック", sans-serif;
width: 100%;
margin: 0 auto;
}
div {
margin:20px;
}
div span {
font-size:200%;
margin:1px;
}
div span:first-child {
color:#3175ad;
}
div span:last-child {
color:#ffcf42;
}
HTML
templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello, world</title>
<link rel="stylesheet" href="{{ static_url("style.css") }}"/>
</head>
<body>
<div id="container">
<div id="main">
<span>Hello</span><span>world!</span>
</div>
</div>
</body>
</html>
起動してみる
コマンドプロンプトを起動し、作成した「server.py」がある場所に移動し、
次のコマンドを実行
python server.py
これだけでローカル環境にWEBサーバーが立ち上がります。
ブラウザで「http://localhost:8888」にアクセスすると次のような画面が表示されます。
無事に「Hello World!」が表示されました。
終了する
コマンドプロンプト上で、CTRL+Cを実行すると止まります。
まとめ
思ったより簡単にWEBページの表示ができました。
これから色々やってみたいと思います。
ではでは。
ディスカッション
コメント一覧
まだ、コメントがありません