flask blueprints

1.      flask blueprints

蓝图是一种网页模板的组合,可以方便的注册到flask中。

蓝图可以在文件中声明,也可以在包中声明,一般而言推荐在包中声明(下文如是)。

1.1.    基本使用

声明多个蓝图后的目录结构:

app/

bluep #蓝图文件夹1

blueo #蓝图文件夹2

app.py

蓝图声明案例:

__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')

注册:app.py

from .bluep import blue_t as blueprint_test
app.register_blueprint(blueprint_test, url_prefix='/blue')

访问:

http://127.0.0.1:9000/blue/index

url_prefix声明了附加路径。

1.2.   
常用参数

1.2.1.  
资源路径

蓝图的资源路径从它的__name__参数中推导而来。

可以通过Blueprint.root_path属性查看。

1.2.2.  
static files

admin = Blueprint('admin', __name__, static_folder='static')

1.2.3.  
templates folder

蓝图有两种组织形式

  1. 蓝图有自己的资源文件夹:
  2. 所有蓝图共用一个资源文件夹:

主要的不同是template_folder参数设置的不同。

  1. 有自己的资源文件夹

蓝图需要建在一个目录下

blue_t = Blueprint('blue_t', __name__, template_folder=r'templates\bluep')

这时蓝图会去app\bluep\templates\bluep下寻找模板文件。

  1. 共用原始资源文件夹

蓝图不需要建在目录下

但需要注意写法的不同:render_template(‘bluep/index.html’)

这时蓝图会去app\templates\bluep目录下寻找模板文件

需要注意的是在模板文件中引用的其它模板文件如未指明路径,仍会在app\templates下寻找。

资源目录可通过属性blue.root_path查看。template_folder会附加在后部。

资源目录可以是绝对路径也可以是相对路径,但蓝图的资源目录级别是低于应用资源目录的。

1.2.4.  
url_for

蓝图的endpoint可以理解为:
蓝图名.函数名

url_for是通过endpoint查询url地址,然后找视图函数

return redirect(url_for('blue_t.index'))

如果在同一蓝图下也可以这样:

url_for('.index')

最新文章

  1. oracle 知识
  2. CheckListBox的实现方式分析
  3. hdu 2018 母牛的故事
  4. python_way day12 RabbitMQ ,pymysql
  5. SQL2008:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。
  6. iOS第三方支付-银联支付
  7. gdb与adb相关命令总结
  8. Java--获取request中所有参数的方法
  9. c# webBrowser 获取Ajax信息 .
  10. 通过google的inurl:backupdata*dede_admin获取账号密码
  11. Centos 下安装Zabbix Linux 客户端
  12. 使用Python操作excel文件
  13. ExpandableListView的完美实现,JSON数据源,右边自定义图片
  14. UVALive - 7639 G - Extreme XOR Sum(思维)
  15. Git工程迁移方法总结(命令行) .(转载)
  16. Redis /etc/redis.conf 常用配置
  17. jsonp 方式处理跨域前后端代码如何配合?
  18. C#:文件/注册表/线程的操作
  19. C#一个FTP操作封装类FTPHelper
  20. 在 Linux 下使用任务管理器

热门文章

  1. node 连接数据库异常
  2. 吴裕雄 python 机器学习——集成学习随机森林RandomForestRegressor回归模型
  3. [LEETCODE] 初级算法/数组 1.3旋转数组
  4. C语言当中int,float,double,char这四个有什么区别?
  5. jquery 获取 父级 iframe 里的控件对象
  6. 解决:执行python脚本,提示错误:/usr/bin/python^M: 解释器错误: 没有那个文件或目录。
  7. pysftp-tools
  8. Postman的使用和测试
  9. [Bug合集] java.lang.IllegalStateException: Could not find method onClickcrea(View) in a parent
  10. 【C语言】无参函数调用实例