チラ裏備忘録

情報整理

Flaskの超基本的な使い方

自分なりにまとめるため,【Python】フレームワークFlaskの基本をマスター | 侍エンジニア塾ブログ(Samurai Blog) - プログラミング入門者向けサイトより抜粋させていただきました.

超基本

from flask import Flask
app = Flask(__name__)
 
@app.route('/')
def hello():
    hello = "Hello world"
    return hello
 
if __name__ == "__main__":
    app.run()

実行

$ python3 hello.py

デコレータによって,hello関数(及び戻り値)に何らかの処理がなされてウェブ上に適切に埋め込まれる仕組みなのだろう(適当)

基本(HTML読み込み)

from flask import Flask, render_template
app = Flask(__name__)
 
@app.route('/')
def hello():
    html = render_template('index.html')
    return html
 
if __name__ == "__main__":
    app.run()

ポイント

  • render_templateをimportする
  • ルート直下にtemplateディレクトを作成し,htmlファイルを置く

変数の利用

HTMLファイル内に{{変数名}}という記述を埋め込み,

@app.route('/')
def hello():
    html = render_template('index.html', var="hatena")
    return html

というふうにrender_templateの引数に変数名と値をセットすることで,変数をページに埋め込むことができる.

CSS, Javascriptの適用

  • ルート直下にstaticディレクトを作成
  • そこに適用したいCSSJavascriptファイルを置く
  • HTMLファイルから読み込む(< link rel="stylesheet" href="/static/test.css">)