蓝图是一种网页模板的组合,可以方便的注册到flask中。
蓝图可以在文件中声明,也可以在包中声明,一般而言推荐在包中声明(下文如是)。
声明多个蓝图后的目录结构:
app/
bluep #蓝图文件夹1
blueo #蓝图文件夹2
app.py
蓝图声明案例:
__init__.py
from flask import Blueprint
blue_t = Blueprint(‘blue_t‘, __name__)
from . import views
views.py
#coding:utf-8
__author__ = ‘sss‘
……
from . import blue_t
@blue_t.route(‘/‘)
@blue_t.route(‘/index‘)
def index():
#print(blue_t.template_folder)
#print(blue_t.root_path)
return render_template(‘bluep/index.html‘, title=‘我的‘, user=user, posts=posts)
# 登录
@blue_t.route(‘/login‘, methods=[‘GET‘, ‘POST‘])
def login():
…
@blue_t.route(‘/lougout‘)
def logout():
logout_user()
return redirect(url_for(‘blue_t.index‘))
@blue_t.errorhandler(404)
def error_handle(error):
return render_template(‘error/404.html‘)
注册:app.py
from .bluep import blue_t as blueprint_test
app.register_blueprint(blueprint_test, url_prefix=‘/blue‘)
访问:
http://127.0.0.1:9000/blue/index
url_prefix声明了附加路径。
蓝图的资源路径从它的__name__参数中推导而来。
可以通过Blueprint.root_path属性查看。
admin = Blueprint(‘admin‘, __name__, static_folder=‘static‘)
蓝图有两种组织形式
主要的不同是template_folder参数设置的不同。
蓝图需要建在一个目录下
blue_t = Blueprint(‘blue_t‘, __name__, template_folder=r‘templates\bluep‘)
这时蓝图会去app\bluep\templates\bluep下寻找模板文件。
蓝图不需要建在目录下
但需要注意写法的不同:render_template(‘bluep/index.html’)
这时蓝图会去app\templates\bluep目录下寻找模板文件
需要注意的是在模板文件中引用的其它模板文件如未指明路径,仍会在app\templates下寻找。
资源目录可通过属性blue.root_path查看。template_folder会附加在后部。
资源目录可以是绝对路径也可以是相对路径,但蓝图的资源目录级别是低于应用资源目录的。
蓝图的endpoint可以理解为: 蓝图名.函数名
url_for是通过endpoint查询url地址,然后找视图函数
return redirect(url_for(‘blue_t.index‘))
如果在同一蓝图下也可以这样:
url_for(‘.index‘)
原文:https://www.cnblogs.com/wodeboke-y/p/11074766.html