uokadaの見逃し三振は嫌いです

ここで述べられていることは私の個人的な意見に基づくものであり、私が所属する組織には一切の関係はありません。

Flask-debugtoolbarで開発を楽に!

Flaskを使った開発をやろうと思っていろいろ調べてるんだがその中でデバッグがかなり便利になりそうな拡張があったので紹介したい。

mgood/flask-debugtoolbar

Flask-DebugToolbar 0.7.1 : Python Package Index

インストール

$ pip install flask-debugtoolbar

サンプルアプリの作成

下のようなFlaskアプリケーションを作成しsample.pyで保存

#!/usr/bin/env python2.7
# -*- coding:utf-8 -*-

from flask import Flask, render_template
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)
# the toolbar is only enabled in debug mode:
app.debug = True

# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = 'asd'
# toolbar を作る前に debug=Trueにしておく
toolbar = DebugToolbarExtension(app)

# gist用にテンプレートファイルのディレクトリを変更
app.template_folder="."

@app.route('/')
def index():
    # ツールバーはテンプレートをフックする感じで出力されているので
    # render_templateしないで出力されるレスポンスには適用されない
    return render_template('index.html')

if __name__ == "__main__":
    app.run()

さらにテンプレートファイルをindex.htmlで保存。

<html>
    <head>
        <title>Flask-debug-toolbar</title>
    </head>
    <body>
        <h1>Flask-debug-toolbar</h1>
    </body>
</html>

実行

準備が完了したのでアプリケーションを起動します。

# ファイル構成はこんな感じ。
% ls  -1
index.html
sample.py

% python2.7 sample.py 
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader

アプリケーションを起動した状態でブラウザから下のURLにアクセスするとサイドバーが出た状態でページが表示されます。 http://localhost:5000/

f:id:uokada:20121203031944j:plain

サイドバーにはプロファイリングやリクエストパラメータの情報があるので開発中には非常に役立つ機能だと思います。

f:id:uokada:20121203032101j:plain

参考

flask-debugtoolbarが便利