LoginSignup
41
47

More than 3 years have passed since last update.

Python + Flask + Blueprint で複数のアプリケーションを登録する際に気をつけること

Last updated at Posted at 2018-07-31

概要

  • PythonのFlaskを使ってアプリケーションを公開したい
  • FlaskのBlueprintを使うとアプリケーションのURLを分けて管理できる
  • URLに分けて管理する際には(Flaskの仕様に則った)ディレクトリ構成に気をつける

Flaskを使う場合の自分のディレクトリ構成

ディレクトリ構成
run.py
app1/
    __init__.py
    views.py
    static/
        stylesheet.css
    templates/
        app1/
            index.html
app2/
    __init__.py
    views.py
    static/
        stylesheet.css
    templates/
        app2/
            index.html
  • staticフォルダ,templatesフォルダはappごとにディレクトリに格納できる
  • templatesをapp以下に置く場合は,そのディレクトリ以下にapp名のディレクトリを挟む
  • 今回の例ではapp1/templates/app1/index.htmlのように配置

メインファイル

run.py
from flask import Flask
app = Flask(__name__)

from app1.views import app1
app.register_blueprint(app1, url_prefix='/app1')

from app2.views import app2
app.register_blueprint(app2, url_prefix='/app2')

if __name__ == "__main__":
    app.run(host='0.0.0.0')
  • 各ディレクトリからappを取ってきて登録する
  • url_prefixを指定することでアドレス指定

viewファイル

app1/views.py
from flask import Blueprint, render_template
app1 = Blueprint('app1', __name__, template_folder='templates', static_folder='./static')

@app1.route('/')
def index():
    return render_template('app1/index.html')
app2/views.py
from flask import Blueprint, render_template
app2 = Blueprint('app2', __name__, template_folder='templates', static_folder='./static')

@app2.route('/')
def index():
    return render_template('app2/index.html')
  • Blueprintで構成する
  • templates_folderはスラッシュなしで記述
  • template_folder='templates'
  • static_folderは相対パスで記述した(良い方法がわかってないです)
  • template_folder='./static'
  • テンプレートからレンダーする場合はapp名を挟む
  • return render_template('app1/index.html')

感想

ややこしい.
このへんの話はstack overflowとかでもかなり議論されている.が実装上の都合でこういったことになっているようだ.
FlaskとBlueprintを使えば1つのサーバで複数のアプリケーションを登録できるので便利.Blueprintでこのようなファイル構成にすれば各アプリケーションごとを分離して管理できるところがうれしい.

参考文献

いまさらながら Flask についてまとめる 〜Blueprint〜
Flask Blueprint における template_folderパス解決の罠

41
47
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
41
47