pythonでWebアプリケーションを作成する方法はいくつかあるが、 Flaskを使用すると非常に簡単に作成することができる。
インストールはpipでできるので、詳細は省く。
使い方
ディレクトリ構成
作業ディレクトリのルートにpythonスクリプトを置き、「templates」ディレクトリ配下にhtmlファイルを置く。
次に例を示す。
. ├── hello.py └── templates └── hello.html
hello.py(pythonスクリプト)
スクリプトの例を示す。
# coding: utf-8 from flask import Flask, render_template app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" @app.route("/hello") def index(): hello = 'hello' return render_template('hello.html', message=hello) if __name__ == "__main__": app.run()
この例では、サイトのルートにアクセスされると、「Hello World!」とブラウザに返し、 「/hello」にアクセスされると、「hello.html」の内容をブラウザに返す。
この時、引数messageを介して「hello」という文字列をhtmlファイルへ渡している。
htmlファイル
「hello.html」の例を次に示す。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <title>Title</title> </head> <body> <div class="container"> <div class="page-header"> <h1>{{message}}</h1> </div> </div> </body> </html>
{{{message}}
で、pythonスクリプトから渡された文字列を表示する。
スクリプトから渡されたデータはjanja2の記法によってhtmlから参照することができる。
Flaskを使用すると、pythonで計算した結果などを簡単にブラウザに表示できるようになるのが便利。
また、見栄えを良くするためにBootstrapを読み込んでいる。Flaskを使用するアプリを紹介しているサイトでは、Bootstrapと組み合わせているものが多かった。
ブラウザからアクセス
スクリプトを実行し、同じPC上でブラウザから「http://127.0.0.1:5000」にアクセスすると動作を確認することができる。
デフォルトでは他のマシンからのアクセスは許可されていないため、これを許可するには、pythonスクリプト側で次のようにする。
app.run(host='0.0.0.0')
ポートを変更する場合は次のようにする。
app.run(host='0.0.0.0', port=8080)
参考サイト
下記のサイトが非常に参考になった。
今回の例では、特にhtml側でデータの有無をチェックせずに参照しているが、このサイトではそれらのチェックの方法や、 String以外のデータの受け渡しなども紹介している。
上記のサンプルはほぼ丸パクリ。
yoctoでの使用方法
meta-pythonに次のパッケージがある。
- python-flask