细致划分 利用红图
核心概念就是在蓝图和路由之间加了层红图,这样就把红图挂载到蓝图上。帮助蓝图节省空间
(1) 新建一个文件 libs 文件夹
- 里面新建两个文件 一个init.py 一个 redprint.py
**options 就是把字典里面的属性和值 变成表达式属性=值
redprint.py 里面写
class Redprint:
def __init__(self, name):
self.name = name
self.mound = []
def route(self, rule, **options):
def decorator(f):
self.mound.append((f, rule, options))
return f
return decorator
def register(self, bp, url_prefix=None):
# bp就是蓝图
if url_prefix is None:
url_prefix = "/"+self.name
for f, rule, options in self.mound:
endpoint = options.pop("endpoint", f.__name__)
bp.add_url_rule(url_prefix + rule, endpoint, f, **options) # 蓝图的注册
(2) 修改 v1 下面的 book.py 和 user.py 文件代码
- user.py
# 蓝图
from app.libs.redprint import Redprint
# from flask import Blueprint
# user = Blueprint('user', __name__)
# @user.route("/v1/user/get")
# def get_user():
# return '测试名称'
# 红图
api_http = Redprint('user')
@api_http.route("/get", methods=['GET', 'POST'])
def get_user():
return '测试名称'
- book.py
# 蓝图
# from flask import Blueprint
# book = Blueprint('book', __name__)
# @book.route("/v1/book/get")
# def get_book():
# return '测试书本'
# 红图
from app.libs.redprint import Redprint
api_http = Redprint('book')
@api_http.route("/get", methods=['GET', 'POST'])
def get_book():
return '测试书本'
(3) 上面红图结束了,把红图注册到蓝图
- book.py 的同级目录下找到init.py 里面写代码
from flask import Blueprint
# 加载模块
from app.api.v1 import book, user
def create_blueprint_v1():
bp_v1 = Blueprint('v1', __name__)
user.api_http.register(bp_v1, url_prefix='/user')
book.api_http.register(bp_v1, url_prefix='/book')
return bp_v1
(4) 蓝图注册到 app.js
- 修改 app.js
# 把项目所有的初始化配置文件都放到这里
from flask import Flask
__author__ = "雾烟云"
# 注册蓝图
def register_blurprints(app):
# from app.api.v1.user import user
# from app.api.v1.book import book
# app.register_blueprint(user)
# app.register_blueprint(book)
from app.api.v1 import create_blueprint_v1
# 把/v1传给蓝图
app.register_blueprint(create_blueprint_v1(), url_prefix='/v1')
def create_app():
app = Flask(__name__)
# 加载配置项目
app.config.from_object('app.config.setting')
app.config.from_object('app.config.secure')
# 使用蓝图
register_blurprints(app)
return app
(5) app.js 挂载到启动文件
from app.app import create_app
__author__ = '雾烟云'
app = create_app()
if __name__ == '__main__':
app.run(host='127.0.0.1', debug=True, port=5000)