Blueprint(蓝图的使用)

本文介绍了Flask中Blueprint的相关内容。Blueprint是存储不同URL请求操作的容器,flask用其组织URL和处理请求,具有可多个注册到一个应用、可注册到未使用URL下等属性。还说明了蓝图的使用,包括项目目录结构、创建和注册蓝图等,最后给出测试访问应用的URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Blueprint是一个存储了不同的URL请求操作的容器,这些操作在Blueprint被注册到一个应用以后就可以访问;flask通过Blueprint来组织URL和处理请求,所以Blueprint具有如下属性:
多个Blueprint可以注册到一个应用中
可以将一个Blueprint 注册到任何一个未使用的URL下
在应用初始化时,就需要注册需要使用的Blueprint
蓝图的使用:

项目目录结构
在这里插入图片描述

Blueprint的使用

  1. 在__init__.py文件中创建蓝图

    	from flask import Blueprint
    	#创建名为app_core_blueprint的蓝图,并将core目录下的所有操作方法存储到这个Blueprint中
    	app_core_blueprint=Blueprint('core',__name__,static_folder='static',template_folder='templates')
    	from qwzqapplication.core import uploadOpus,index,login_regist
    
  2. 在app.py文件中将蓝图注册到应用对象上

    #第一种方式注册蓝图
    app.register_blueprint(app_core_blueprint)
    第二种方式我们可以将将这个蓝图注册到指定的URL上
    #注册蓝图
    app.register_blueprint(app_core_blueprint,url_prefix='/core')
    
  3. index.py文件中在蓝图对象app_core_blueprint上进行操作

    from qwzqapplication.core import app_core_blueprint
    from flask import render_template
    from qwzqapplication.db.optionDB import selectPaint
    
    @app_core_blueprint.route('/')
    def index():
        data = selectPaint()
        contxt = {
            'datas': data
        }
        return render_template('index.html', **contxt)
    

最后我们通过测试访问我们的应用:
如果通过第一种方式注册蓝图
http://127.0.0.1:5000/
如果通过第二种注册方式
http://127.0.0.1:5000/core/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值