蓝图用于为应用提供目录划分:
一:上目录结构
二:上代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户登录</h1> <form method="POST"> <input type="text" name="user"/> <input type="submit" value="提交"/> </form> <img src="static/code.png"> <img src="{{ url_for('static',filename='code.png') }}"> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/5 13:54 from flask import Blueprint from flask import render_template from flask import request # 创建一个蓝图 # template_folder表示找模板的时候可以放在自己的目录找 # url_prefix表示给当前蓝图的url加个前缀,批量操作 account = Blueprint('account', __name__, url_prefix='/acc',template_folder='tpls') @account.route('/login', methods=['GET', 'POST'], endpoint='account') # 注意蓝图的名字和函数名字不能相同 def login(): # return render_template('login.html') return render_template('login.html') # 在单个蓝图中定义扩展,只有在当前蓝图中生效 @account.before_request def process_request(*args,**kwargs): print('来了')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/5 13:58 from flask import Blueprint, render_template blog = Blueprint('blog', __name__) @blog.route('/blog', methods=['GET', 'POST'],endpoint='blog') def blog2(): # return render_template('blog.html') return 'blog'
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/5 13:59 from flask import Blueprint, session, url_for, redirect user = Blueprint('user', __name__) @user.route('/user', methods=['GET', 'POST'], endpoint='user') # 蓝图和函数不能重名,因为重名的话,导入就不知道导入哪个了 def user2(): # return render_template('user.html') return 'user' # 使用扩展来解决登录问题,比用装饰器好,每次访问之前都执行,使用蓝图之后就不用设置白名单了 # 因为扩展只对当前蓝图生效 @user.before_request def process_request(*args, **kwargs): user = session.get('user_info') if user: return None url = url_for('l1') # 根据别名生成url return redirect(url)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/5 13:51 from flask import Flask app = Flask(__name__, template_folder='templates', static_folder='static', static_url_path='/static') from .views.account import account from .views.blog import blog from .views.user import user # 注册蓝图 app.register_blueprint(account) app.register_blueprint(blog) app.register_blueprint(user) # 在app这添加扩展,对所有注册的蓝图都生效 @app.before_request def process_request(*args, **kwargs): print('来了')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/5 13:50 from pro_flask import app if __name__ == '__main__': app.run()
简单的蓝图(小型的应用程序):下载