Flask(Blueprint, Jinja Template)


Blueprintとは?


Flask機能が徐々に強化されるにつれて、コード量は自然に増加します.
したがって,Blueprintを用いて長くなったコードをモジュール化し,修正開発やメンテナンス時にコードを管理することができる.
Blueprintを無効にする場合
app.py
from flask import Flask, jsoinfy
app = Flask(__name__)

@app.route("/", methods=["GET"])
def home_route():
	return jsonfiy('home')

@app.route("/first", methods=["GET"])
def first_route():
	return jsonfiy('first page')
    
@app.route("/second", methods=["GET"])
def second_route():
	return jsonfiy('second page')

@app.route("/third", methods=["GET"])
def third_route():
	return jsonfiy('third page')

#...생략
if __name__=='__main__':
	app.run(debug=True)
Blueprintを使用している場合
app.py
from flask import Flask
from first_api import bp

app = Flask(__name__)
app.register_blueprint(bp)

if __name__=='__main__':
	app.run(debug=True)
first_api.py
from flask import Blueprint, jsoinfy
bp = Blueprint('bp', __name__)

@bp.route('/first', methods=['GET'])
def first_route():
	return jsonfiy('first page')

@bp.route("/second", methods=["GET"])
def second_route():
	return jsonfiy('second page')

Jinja 2とは?


Jinja 2はpythonで最もよく使われるテンプレートです.
サーバから受信したデータを効率的に表示し、比較的簡略な表現でデータを加工することができる.
Jinja 2 Templateからのデータ転送-単一変数
app.py
@app.route("/")
def home():
	return render_template(
    		'index.html',
            data = 'hello'
          )
index.html
<html>
	<head>
    	<title>jinja example</title>
    </head>
    <body>
    	{{ data }}
    </body>
</html>
Jinja 2 Templateからデータを渡す-list
app.py
@app.route("/")
def home():
	my_list = [1,2,3,4,5]
	return render_template(
    		'index.html',
            data = my_list
          )
index.html
<html>
	<head>
    	<title>jinja example</title>
    </head>
    <body>
    	{{ data }}
        {% for d in data %}
        	{{ d }}
        {$ endfor $}
    </body>
</html>
Jinja 2 Templateからのデータ転送-Dictionary
app.py
@app.route("/")
def home():
	my_data = {'name': 'elice'}
	return render_template(
    		'index.html',
            data = my_data
          )
index.html
<html>
	<head>
    	<title>jinja example</title>
    </head>
    <body>
    	{{ data.get('name') }}
    </body>
</html>