隨著功能的添加,路由越來越多,view層的拆分變成了剛需
方式
- 模塊
Module
- 藍(lán)圖
Blueprint
實(shí)現(xiàn)
Module
開始是通過Module來實(shí)現(xiàn),但是運(yùn)行時(shí)收到Flask的提示Module已經(jīng)被摒棄,建議通過Blueprint來實(shí)現(xiàn),就不在多說,留個(gè)Git上別人的實(shí)例Module
Blueprint
- 創(chuàng)建藍(lán)圖和路由(
errors.py
)
from flask import Blueprint
# 創(chuàng)建藍(lán)圖
err = Blueprint('err', __name__)
# 404
@err.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
# test
@err.route('/nimei', methods=['POST', 'GET'])
def nimei():
return 'nimei'
- 注冊(cè)藍(lán)圖(
__init__.py
)
應(yīng)用初始化的時(shí)候注冊(cè)藍(lán)圖
from errors import err
# 注冊(cè)藍(lán)圖
app.register_blueprint(err)
# 附加前綴
# app.register_blueprint(err, url_prefix='/err')
- 外部引用(
view.py
)
@app.route('/secret')
@login_required
def secret():
return redirect(url_for('err.nimei'))
Blueprint還有很多其他的功能比如動(dòng)態(tài)URL前綴等,詳情Flask文檔