前言
Flask是一个轻量级的python web框架,与django相比,flask抛开了繁琐的配置项等等。
Flask与Django一样,支持模块化开发,使用BluePrint(蓝图)实现。
但是,这个蓝图并不支持嵌套。。
正文
当然,我能想到的问题早就有人想到,并解决了。
详情见issue.
解决方案
class NestableBlueprint(Blueprint):
"""
Hacking in support for nesting blueprints, until hopefully https://github.com/mitsuhiko/flask/issues/593 will be resolved
"""
def register_blueprint(self, blueprint, **options):
def deferred(state):
url_prefix = (state.url_prefix or u"") + (options.get('url_prefix', blueprint.url_prefix) or u"")
if 'url_prefix' in options:
del options['url_prefix']
state.app.register_blueprint(blueprint, url_prefix=url_prefix, **options)
self.record(deferred)
使用方法
以下为从我的flask demo里复制出来的代码。
from flask import Blueprint
from ..libs.nestable_blueprint import NestableBlueprint
exam = NestableBlueprint('exam', __name__, template_folder='templates', static_folder='static')
exam_admin = NestableBlueprint('exam.admin', __name__, template_folder='templates', static_folder='static')
exam_admin_category = Blueprint('exam.admin.category', __name__, template_folder='templates', static_folder='static')
exam_admin_question = Blueprint('exam.admin.question', __name__, template_folder='templates', static_folder='static')
exam_admin.register_blueprint(exam_admin_category, url_prefix='/category')
exam_admin.register_blueprint(exam_admin_question, url_prefix='/question')
exam.register_blueprint(exam_admin, url_prefix='/admin')
exam_category = Blueprint('exam.category', __name__, template_folder='templates', static_folder='static')
exam_question = Blueprint('exam.question', __name__, template_folder='templates', static_folder='static')
exam.register_blueprint(exam_category, url_prefix='/category')
exam.register_blueprint(exam_question, url_prefix='/question')
from . import views, models
from .admin.category import views
from .admin.question import views
from .category import views