1.什么是蓝图(Blueprint)
Blueprint 是一种组织一组相关视图及其他代码的方式。与把视图及其他 代码直接注册到应用的方式不同,蓝图方式是把它们注册到蓝图,然后在工厂函数中 把蓝图注册到应用。
2.为什么要引入蓝图
在写代码时,我们有时候会出现一个文件中导入其他的模块,并且随着功能的增加,那么就会出现路由循环导入的情况,这样很容易出错,所以将路由按照模块来划分(各个路由的集合),就是为了避免出现路由循环导入的问题
3.文件结构
4.main.py文件
#蓝图:将路由按照模块来划分(各个路由的集合)
import os
#导入蓝图模块
from book import blue_book
from flask import render_template,Flask,request,url_for,redirect
app=Flask(__name__)
@app.route('/index',methods=['POST','GET'])
def index():
return render_template('index.html')
if __name__ == '__main__':
print('PyCharm')
#注册蓝图
app.register_blueprint(blue_book)
#启动
app.run(debug=True)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
5.index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
div {
width:300px;
height:300px;
background:#A020F0;
border:2px solid #00FF7F;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
6.book.py文件
import os
from flask import Flask,render_template,redirect,request,Blueprint
blue_book=Blueprint('blue_books',__name__)
#这里就使用blue_book路由了,就不用app.route进行路由,避免出现循环路由(特别是随着项目模块的增加)
@blue_book.route('/books/index',methods=['POST','GET'])
def books():
return render_template('book.html')
if __name__ == '__main__':
print('Pycharm')
7.book.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>book</title>
<style>
div {
width:200px;
height:100px;
background:#ffffff;
border:2px solid #000000;
}
</style>
</head>
<body>
<div>我是蓝图:books</div>
</body>
</html>