5
4

More than 1 year has passed since last update.

【Flask】Blueprint を簡単にまとめてみた

Last updated at Posted at 2023-04-23

Blueprint とは

Blueprintの役割は、「アプリを分割して管理するため」のもの。

通常のPythonのコードは分割しても、インポートすることで使用することが可能。
例えば、フォームやモデルを記述したファイルは、view関数から呼び出す形で記述するので、そのままインポートして使うことができる。

しかし、view関数はそのまま分割してしまうと、関数ごとに設定した URL が動作しなくなってしまう。

そのため、 Blueprint を使用することにより、 view関数 を機能ごとに分割し、その URL を管理することができるようになるため、view関数に付随するフォームやモデルのファイルも分割することが可能となる。

分割できることのメリットとしては、機能ごとにフォルダ管理ができるので「どこになにがあるか」がわかりやすくなること。

実装方法

Blueprintをインポート

# Blueprint をインポート
from flask import Blueprint

 # Blueprint を インスタンス化
sample = Blueprint('sample', __name__)
"""
'sample' : Blueprint名
__name__ : このファイルのディレクトリ名が格納されている
"""

# Blueprint名を view関数 のデコレータに指定
@sample.route('/login', methods=['GET', 'POST'])
def login():

# view関数を指定するときには、 Blueprint名 を関数名の前に付ける
return redirect(url_for("sample.login"))

Flaskアプリに Blueprint を登録する

# Flaskをインスタンス化
app = Flask(__name__)

# Blueprint名をインポートする
from folder.subfolder.file import sample

# Blueprintをアプリに登録し、Blueprintを有効にする
app.register_blueprint(sample)

以上、Blueprint について簡単にまとめてみました。

5
4
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
5
4