本記事ではPythonのWebアプリケーションフレームワークの一つであるFlaskのblueprintの使い方について紹介します。 blueprintを使うことによって、アプリケーションをblueprint単位で分割できます。 特に規模が大きなアプリケーションほど、blueprintの利用によってアプリケーションを分割することでプログラムを管理しやすくなり、得られるメリットが大きいです。 本記事はFlask-Large-Aplication-Exampleを参考にして、特にblueprintに関する箇所を抽出し、簡素化して自分の理解をまとめたものです。 Flaskのblueprintを使って初めてアプリケーションを実装する人の参考になるような入門記事です。

目次

Flaskのインストール

本記事ではPython3を使います。また、Flaskは次の通りインストールします。

$pip install flask
$pip freeze|grep Flask
Flask==1.0.2

アプリケーションのディレクトリ構成

.
├── application.py
├── blueprints.py
├── flask_sample
│   └── views
│       ├── __init__.py
│       ├── example1
│       │   ├── __init__.py
│       │   └── index.py
│       └── example2
│           └── __init__.py
├── run.py

blueprintの作成

blueprints.py にてblueprintを作成します。 本記事では2つのblueprintを作成します。

from flask import Blueprint

example1 = Blueprint('example1', import_name='flask_sample.views.example1', url_prefix='/example1')
example2 = Blueprint('example2', import_name='flask_sample.views.example2', url_prefix='/example2')


all_blueprints = (
    example1,
    example2
)

第一引数はblueprintの名前を指定します。 import_name はこのblueprintが利用するパッケージ名を指定します。 url_prefix にはこのblueprintのURLの接頭辞を指定します。たとえば example1 という名前のblueprintは URL:PORT/example1 というURLと紐付けられます。

flask_sample/views/example1/__init__.py および flask_sample/views/example1/index.py は以下のように記述します。

from . import index
from blueprints import example1

@example1.route('/')
def index():
    return 'example1'


@example1.route('/test')
def test():
    return 'test of example1'

flask_sample/views/example2/__init__.py および flask_sample/views/example2/index.py は以下のように記述します。

from . import index
from blueprints import example2

@example2.route('/')
def index():
    return 'example2'


@example2.route('/hoge')
def test():
    return 'hoge of example2'

@example1.route(URL_SUFFIX) で関数をデコレートすることによって、その関数は example1 という名前のblueprintで扱えるようになります。 具体的には@example1.route('/')とすることによって、indexURL:PORT/example1/ にアクセスした際に実行されるようになります。 また@example1.route('/test')とすることによって、testxURL:PORT/example1/test にアクセスした際に実行されるようになります。 @example2 も同様です。

blueprintの登録

application.py にてapplicationを作成し、applicationに上記のblueprintを登録します。

import importlib

import flask

import blueprints


def create_app():
    app = flask.Flask(__name__)

    for blueprint in blueprints.all_blueprints:
        importlib.import_module(blueprint.import_name)
        app.register_blueprint(blueprint)

    return app

blueprintの登録は以下の行で実行します。

    for blueprint in blueprints.all_blueprints:
        importlib.import_module(blueprint.import_name)
        app.register_blueprint(blueprint)

importlib.import_module(blueprint.import_name) でPythonモジュールをインポートします。 これを実行しないと、blueprintが利用するPythonモジュールがインポートされず、blueprintも登録できません。 app.register_blueprint(blueprint)blueprints.py にて定義した all_blueprints のすべての要素を app に登録します。

サーバの起動

run.py を以下のように記述し、実行します。

import application


app = application.create_app()
print(app.url_map)
app.run()

これを実行すると以下の結果が得られます。

$python run.py
Map([<Rule '/example1/test' (HEAD, OPTIONS, GET) -> example1.test>,
 <Rule '/example2/hoge' (HEAD, OPTIONS, GET) -> example2.test>,
 <Rule '/example1/' (HEAD, OPTIONS, GET) -> example1.index>,
 <Rule '/example2/' (HEAD, OPTIONS, GET) -> example2.index>,
 <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])
 * Serving Flask app "application" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

print(app.url_map) によって、Map(...) が標準出力に表示されます。 ここで、 /example1/example1/test などが表示されていれば、blueprintが app に登録されています。

おわり

本記事ではFlaskのblueprintを使ってウェブアプリケーションを作る際に参考となるような基本的な構成を紹介しました。 blueprintを使うことで、アプリケーションの実装をきれいに分割できそうです。


関連記事






最近の記事