Flask Blueprints 蓝图

1. 使用 templates、static 基本蓝图

from flask import Blueprint, render_template 

test = Blueprint('test', __name__, static_folder='static', template_folder='templates') 

@test.route('/index.html') 
def index(): return render_template('test/test.html')

注册蓝图:

app.register_blueprint(test, url_prefix='/test')

html 页面:

{% raw %}
href="{{ url_for('static', filename='test/index.css') }}"
{% endraw %}

项目结构:

application/templates/test/test.html

application/static/test/index.css


2. 自定义外部 templates、static 蓝图

from flask import render_template, Blueprint, abort, url_for 
from jinja2 import TemplateNotFound 

simple_page = Blueprint('simple_page', __name__, template_folder='bp/templates', static_folder='bp/static') 

@simple_page.route('/', defaults={'page': 'index'}) 
@simple_page.route('/') 
def show(page): 
    try: 
        return render_template('%s.html' % page) 
    except TemplateNotFound: 
        abort(404)

注册蓝图:

app.register_blueprint(simple_page, url_prefix='/bp')

html 页面:

{% raw %}
src="{{ url_for('simple_page.static', filename='index.js') }}"
{% endraw %}

项目结构:

application/bp/templates/index.html

application/bp/static/index.js


总结:

静态文件目录始终是蓝图前缀 url_prefix + /static。如果不知道前缀 url_prefix,则路径就是 static。模板文件 templates 则根据指定的 template_folder 路径查找。

在蓝图内可以使用相对路径轻易跳转:

url_for('.index')

蓝图的请求 url :

url_for('test.index')

蓝图的 404、405 错误处理方式:

@app.errorhandler(404) 
@app.errorhandler(405) 
def _handle_api_error(ex): 
    if request.path.startswith('/bp/'): # 蓝图规则 
        #  蓝图错误处理方式 
    else: 
        return ex # 通用错误处理方式


展开阅读全文