Blueprint(蓝图的使用)
Blueprint是一个存储了不同的URL请求操作的容器,这些操作在Blueprint被注册到一个应用以后就可以访问;flask通过Blueprint来组织URL和处理请求,所以Blueprint具有如下属性:
多个Blueprint可以注册到一个应用中
可以将一个Blueprint 注册到任何一个未使用的URL下
在应用初始化时,就需要注册需要使用的Blueprint
蓝图的使用:
项目目录结构
Blueprint的使用
-
在__init__.py文件中创建蓝图
from flask import Blueprint #创建名为app_core_blueprint的蓝图,并将core目录下的所有操作方法存储到这个Blueprint中 app_core_blueprint=Blueprint('core',__name__,static_folder='static',template_folder='templates') from qwzqapplication.core import uploadOpus,index,login_regist
-
在app.py文件中将蓝图注册到应用对象上
#第一种方式注册蓝图 app.register_blueprint(app_core_blueprint) 第二种方式我们可以将将这个蓝图注册到指定的URL上 #注册蓝图 app.register_blueprint(app_core_blueprint,url_prefix='/core')
-
index.py文件中在蓝图对象app_core_blueprint上进行操作
from qwzqapplication.core import app_core_blueprint from flask import render_template from qwzqapplication.db.optionDB import selectPaint @app_core_blueprint.route('/') def index(): data = selectPaint() contxt = { 'datas': data } return render_template('index.html', **contxt)
最后我们通过测试访问我们的应用:
如果通过第一种方式注册蓝图
http://127.0.0.1:5000/
如果通过第二种注册方式
http://127.0.0.1:5000/core/