temporaryなめも帳

だらだらと備忘録とか。誰かの為になることをねがって。

Flaskお勉強中メモ

※メモ書き

hello world

app.route()にルーティングするPathを指定して、直下にメソッドを定義すると、そのPathへのアクセスがあったときにメソッドが呼び出されるようになる。 app.run()を呼べば、サーバーが起動する。debug=Trueを指定すれば、デバッグオプションが有効になりソースコードの変更時に自動的に読み込み直しがかかるようになる。開発時はこれでいいけど、デプロイするときは外すようにする。 そのほかに、port=5678でポートの変更、host='0.0.0.0'でアドレスの変更がかかる。

from flask import Flask

app = Flask(__name__)

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

routing

変数を使う

@app.route()に<>を使うとURLを引数として利用することができる 例えば、localhost/user/kobashinにアクセスして、hello kobashin!を表示する場合は、

@app.route(&quot;/usr/&lt;username&gt;&quot;)
def show_user(username):
    return &quot;hello &quot; + username + &quot;!\n&quot;

<int:username>とすれば、入力値を限定することができる。

redirectとrul_for

redirectはリダイレクト用のメソッド、url_forはそのメソッドのURLに変換してくれるメソッド(?)

from flask import Flask, url_for, redirect

@app.route(&quot;/&quot;)
def root_index():
    return redirect(&quot;/link&quot;)


@app.route(&quot;/redirect_link&quot;)
def to_link():
    return redirect(url_for(&quot;link&quot;))


@app.route(&quot;/link&quot;)
def link():
    return &quot;link&quot;

htmlのテンプレートを使う

render_templateメソッドを使うと、templates以下のディレクトリの指定したhtmlファイルを探しに行ってくれる。 テンプレートとして利用できる書式については、以下ドキュメントが参照できる http://jinja.pocoo.org/docs/dev/templates/

from flask import Flask, render_template

@app.route(&quot;/&quot;)
def index():
    return render_template(&quot;index.html&quot;)
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head lang=&quot;en&quot;&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
hello world!
&lt;/body&gt;
&lt;/html&gt;