網站後端.Flask.實戰-社交博客開發-建立認證藍圖?

1.不一樣的程序功能,推薦使用不一樣的藍圖,藍圖自己能夠包含基於此藍圖對象路由/視圖/表單/模版/靜態資源/錯誤處理等,這時保持代碼整潔有序的好方法html

FlaskWeb/app/auth/__init__.pypython

#!/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目錄下尋找模版和靜態資源,若是不存在則會從藍圖下獨立目錄中尋找sql

FlaskWeb/app/auth/views.pyflask

#!/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藍圖模版命名衝突.bootstrap

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/loginapp

相關文章
相關標籤/搜索