1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flask 階層分け

Last updated at Posted at 2019-03-28

はじめに

  • せめて2階層にわけたい

構成

│  svr.py
├─ apps
│  ├─ root.py
│  └─ hello.py
├─ templates
│  ├─ root.html
│  └─ hello.html
└─ static ...空

実行結果

blueprint.png

app

[1]svr.py

from flask import Flask

# 分割先のコードをインポートする。appsはフォルダ名。
from apps import root
from apps import hello

app = Flask(__name__)

# 分割先のコントローラー(Blueprint)を登録する
app.register_blueprint(root.app)  # /
app.register_blueprint(hello.app) # /hello

# 起動する
if __name__ == "__main__":
    app.run(debug=True)


[2]root.py

# Blueprintをimportする
from flask import Blueprint
# render_template を追加
from flask import Flask, render_template


# "root"という名前でBlueprintオブジェクトを生成します
app = Blueprint('root', __name__)

# ルーティング処理を書きます
@app.route("/")
def root():
    # render_template を使って root.html を表示
    return render_template('root.html')

[3]hello.py

# Blueprintをimportする
from flask import Blueprint
# render_template を追加
from flask import Flask, render_template


# "hello"という名前でBlueprintオブジェクトを生成します
app = Blueprint('hello', __name__)

# ルーティング処理を書きます
@app.route("/hello")
def hello():
    # render_template を使って hello.html を表示
    return render_template('hello.html')

[4]root.html

<html>
<body>
<div>
this is root.
</div><div>
<a href="./hello">hello</a>
</div>
</body>
</html>

[5]hello.html

<html>
<body>
<div>
this is hello.
</div><div>
<a href="./">root</a>
</div>
</body>
</html>

参考(今日のレシピ)

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?