蓝图分离视图函数的缺陷
- flask中的Blueprint是用来做模块级别的区分的,而不是用来做视图函数的区分
- 比如项目中的一个api模块,cms模块,就可以使用蓝图来区分
创建自己的Redprint
红图层级
Flask核心对象 app
蓝图层 v1
红图层(Redprint) book user
视图函数 get_book get_user
红图的实现及视图函数向红图的注册
- 红图实现
app
libs
redprint.py
redprint.py
class Redprint:
'''
红图创建
'''
pass
- 视图函数向红图的注册
api(和app文件夹同级)
v1
book.py
__init__.py
book.py
from app.libs.redprint import Redprint
api = Redprint("book")
@api.route('/v1/book/get')
def get_book():
return "book"
@api.route("/v1/book/create")
def create_book():
return "create_book"
初始化蓝图对象及红图向蓝图的注册
将v1视作蓝图层,我们在v1的初始化文件中完成这个操作
__init__.py
from flask import Blueprint
def create_blueprint_v1():
bp_v1 = Blueprint("bp_v1", __name__)
# 红图向蓝图对象的注册
from api.v1 import book
book.api.register(bp_v1)
return bp_v1
蓝图向app核心对象的注册
app.py
from flask import Flask
def register_blueprint(app):
from api.v1 import create_blueprint_v1
app.register_blueprint(create_blueprint_v1())
def create_app():
app = Flask(__name__)
app.config.from_object("app.config.secure")
app.config.from_object("app.config.setting")
# v1蓝图向app核心对象的注册
app.register_blueprint(app)
return app
删除v1
app.register_blueprint(create_blueprint_v1(), url_prefix="/v1")
删除book
book.api.register(bp_v1, url_prefix="/book")
实现Redprint类
class Redprint:
'''
红图创建
'''
def __init__(self, name):
self.name = name
self.mound = []
def route(self, rule, **options):
def decorator(f):
self.mound.append((rule, options, f))
# 先将当前信息保存,
return f
return decorator
def register(self, bp, url_prefix=None):
if url_prefix == None:
url_prefix = self.name
for rule, options, f in self.mound:
endpoint = options.pop("endpoint", f.__name__)
bp.add_url_rule(url_prefix + rule, endpoint, f, **options)