1.不同的程序功能,推荐使用不同的蓝图,蓝图本身可以包含基于此蓝图对象路由/视图/表单/模版/静态资源/错误处理等,这时保持代码整洁有序的好方法
FlaskWeb/app/auth/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#
# Authors: limanman
# OsChina: http://my.oschina.net/pydevops/
# Purpose:
#
"""
from flask import Blueprint
auth = Blueprint('auth', __name__, template_folder='templates', static_folder='static')
from . import views, errors
说明:auth蓝图保存在同名包中,在包的构造文件创建蓝本对象,再导入路由和错误处理,template_folder='templates',设置独立模版目录, static_folder='static',设置独立静态文件目录,默认蓝图会从程序templates/static目录下寻找模版和静态资源,如果不存在则会从蓝图下独立目录中寻找
FlaskWeb/app/auth/views.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#
# Authors: limanman
# OsChina: http://my.oschina.net/pydevops/
# Purpose:
#
"""
from . import auth
from flask import render_template
@auth.route('/login', methods=['GET', 'POST'])
def login():
return render_template('auth/login.html')
注意:render_template('auth/login.html')指定的模版文件保存在auth文件夹下,此文件夹必须在FlaskWeb/app/templates目录中,因为Flask认为模版路径是相对于程序模版文件夹的,这样可以避免与main蓝图模版命名冲突.
FlaskWeb/app/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#
# Authors: limanman
# OsChina: http://my.oschina.net/pydevops/
# Purpose:
#
"""
from flask import Flask
from config import config
from flask_mail import Mail
from flask_moment import Moment
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
mail = Mail()
db = SQLAlchemy()
moment = Moment()
bootstrap = Bootstrap()
def create_app(env='default'):
env_config = config.get(env)
app = Flask(__name__)
app.config.from_object(env_config)
db.init_app(app)
mail.init_app(app)
moment.init_app(app)
bootstrap.init_app(app)
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
说明:注册蓝图时url_prefix是可选的,url_prefix='/auth'则所有基于此蓝图的路由和错误处理都会加上/auth前缀,如/login路由会注册成/auth/login,在开发服务器中完整的Url就变成http://127.0.0.1/auth/login