LoginSignup
4
3

More than 5 years have passed since last update.

【Python】コーディングメモ(Flask、Jinja2)

Last updated at Posted at 2018-11-02

バージョンを確認する

# 引数は大文字のVで有る点に注意
python -V

Hello Worldを出力する(Flaskを利用)

from flask import Flask
app = Flask(__name__)

@app.route("/hello")
def hello_world():
    return "<h1>Hello World</h1>"

Jinja2テンプレート

  • Pythonで作成されたテンプレートエンジン
  • HTMLタグの中にPythonコードを記載できる
  • Flask内にテンプレートエンジンとして組み込まれている

Jinja2テンプレートを使用したサンプル

  • 以下、サンプルを作成。
    • ワークディレクトリ:/home/xxx/workdir/sample_app
    • indexページ:/home/xxx/workdir/sample_app/index.py
    • テンプレート:/home/xxx/workdir/sample_app/templates/index.html
index.py
import random
from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
    rand_num = random.randrange(10)
    #render_templateの第1引数にテンプレートファイルを指定する。
    # 第2引数にテンプレートファイルに渡したい変数を設定する
    return render_template("index.html", rand_num = rand_num)
index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>Flask</title>
        <style>body {padding: 10px;}</style>
    </head>
    <body>
        <h1>奇数偶数判定</h1>
        <!-- {% … %}で、テンプレート内にPythonコードを埋め込める -->
        <!-- index.pyから受け取った変数値を参照して、奇数偶数判定を行い、結果を出力している -->
        {% if (rand_num % 2) == 0 %}
            <p>{{rand_num}}は偶数です!</p>
        {% else %}
            <p>{{rand_num}}は奇数です!</p>
        {% endif %}

    </body>
</html>
  • コマンドを実行してFlaskのサーバーを起動
FLASK_APP="index.py" FLASK_ENV=development flask run

sample.PNG

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3