flask摘记

Blueprint

路由:处理URL到python函数的映射的函数,如下

1 @app.route('/')
2     def index():
3     return '<h1>Hello World!</h1>'

官方文档:why blueprint?http://flask.pocoo.org/docs/0.11/blueprints/#why-blueprints

flask web中引入blueprint的例子:
要方便在不同情况下使用不同的配置-> 在app/__init__.py中使用一个工厂函数create_app(config_name):来根据config_name创建app-> 蓝本可以创建一个休眠的路由(在工厂函数create_app()中注册以“激活”这个路由)。

例子:app/main 文件夹为蓝本文件夹,在app/main/__init__.py创建一个蓝本,代码如下

1 from flask import Blueprint
2 
3 main = Blueprint('main', __name__)
4 
5 from . import views, errors

Blueprint的第一个参数为我们创建的蓝本的名字。

为了避免循环导入,views, errors在末尾import,在error的开头有from . import main, '.'表示同文件夹下。

如之前所述,这个蓝本必须在工厂函数中注册

1 def create_app(config_name):
2     # ...
3     from .main import main as main_blueprint
4     app.register_blueprint(main_blueprint)
5     return app

我们这里要将error和view写为蓝本,写法的细节会稍有不同

比如app/main/error.py

 1 from flask import render_template
 2 from . import main
 3 
 4 @main.app_errorhandler(404)
 5 def page_not_found(e):
 6     return render_template('404.html'), 404
 7 
 8 @main.app_errorhandler(500)
 9 def internal_server_error(e):
10     return render_template('500.html'), 500

如果使用errorhandler修饰器,那么只有蓝本中的错误才能触发处理程序。要想注册程序全局的错误处理程序,必须使用app_errorhandler。

app/main/view.py

1 @main.route('/', methods=['GET', 'POST'])
2 def index():
3     form = NameForm()
4     if form.validate_on_submit():
5         #...
6    return redirect(url_for('.index')) 7 return render_template('index.html', 8 form=form, name=session.get('name'), 9 known=session.get('known', False), 10 current_time=datetime.utcnow())

1.路由定义使用蓝本提供的main.route

2.url_for()的第一个参数是路由的端点名,现在要加上一个蓝本的命名空间,写为main.index,这个main是可以省略的

further:https://exploreflask.com/en/latest/blueprints.html


原文地址:https://www.cnblogs.com/autoria/p/6044807.html