网站后端.Flask.实战-社交博客开发-创建认证蓝图?

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

转载于:https://my.oschina.net/pydevops/blog/700820

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值