flask blueprints
1. flask blueprints
Blueprint is a combination of web page templates, you can easily register to the flask.
Blueprint can be declared in the document can also be declared in the package, in general recommendation statement (case below) in the package.
1.1. Basic use
Statement after more than a blueprint directory structure:
app/
bluep # blueprint folder 1
blueo # blueprint folder 2
app.py
Case blueprint statement:
__init__.py
from flask import Blueprint
blue_t = Blueprint('blue_t', __name__)
from . import views
views.py
#coding:utf-8
__author__ = 'sss'
……
from . import blue_t
@blue_t.route('/')
@blue_t.route('/index')
def index():
#print(blue_t.template_folder)
#print(blue_t.root_path)
return render_template('bluep/index.html', title='我的', user=user, posts=posts)
# 登录
@blue_t.route('/login', methods=['GET', 'POST'])
def login():
…
@blue_t.route('/lougout')
def logout():
logout_user()
return redirect(url_for('blue_t.index'))
@blue_t.errorhandler(404)
def error_handle(error):
return render_template('error/404.html')
Registration: app.py
from .bluep import blue_t as blueprint_test
app.register_blueprint(blueprint_test, url_prefix='/blue')
access:
http://127.0.0.1:9000/blue/index
url_prefix declared additional path.
1.2. Common parameters
1.2.1. Resource Path
Resources from its path blueprint __name__ parameters derived from.
By Blueprint.root_path view the properties.
1.2.2. static files
admin = Blueprint('admin', __name__, static_folder='static')
1.2.3. templates folder
There are two forms of organization blueprint
- Blueprint has its own resources folder:
- All share a resource blueprint folder:
The main difference is template_folder different parameter settings.
- Have their own resources folder
Blueprint need to build in a directory
blue_t = Blueprint('blue_t', __name__, template_folder=r'templates\bluep')
At this blueprint will go to app \ find the template file bluep \ templates under the \ bluep.
- Original shared resource folder
Blueprint not need to build in the directory
Note, however, different wording: render_template ( 'bluep / index.html')
At this blueprint will go to app \ find the template file templates \ bluep directory
Note that other template files referenced in the template file path if not specified, will look for in the app \ templates.
Resource Directory can be viewed through the property blue.root_path. template_folder will be attached to the rear.
Resource directory can be an absolute path or a relative path, but the resource directory levels below the blueprint of the application resource directory.
1.2.4. url_for
Blueprint endpoint can be understood as: the name of the function name blueprint
url_for query url address endpoint, and then find the view function
return redirect(url_for('blue_t.index'))
If at the same blueprint may also like:
url_for('.index')