flask之Blueprint

用途:扩展已有的应用结构的方式。蓝图提供一种将功能类似的视图函数组合在一起的方式。以这种方式将应用拆分成不同组件。在我们的架构中,蓝图的作用类似于控制器。

视图可以注册到蓝图中,可以在一个蓝图中定义蓝图独有的模板文件目录及静态文件目录(通过给实例传参:template_folder、static_folder、static_url_path)。当所需内容都被添加到蓝图,可以将蓝图注册到Flask主应用中。

from flask import Flask

example=Blueprint(
    ‘example’,__name__,
    template_folder=’template/example’,
    static_folder=’static/example’,
    url_prefix=’/example’ 
#自动将url前缀添加到这个蓝图所有路由之前。
#如home视图在应用中的实际url是/example/。
#在使用url_for()函数时,需要告诉它在哪个蓝图中找路由:{{url_for(‘example.home’)}}也可以这样写,让它找与当前视图在同蓝图{{url_for(‘.home’)}}
)

@example.route(‘/’)
def home():
       return render_template(‘home.html’)

注册到蓝图主应用:

app.register_blueprint(example)

 

posted @ 2018-08-28 09:28  桥前石头  阅读(348)  评论(0编辑  收藏  举报