Flask蓝图的使用(七)

本文介绍如何使用Flask蓝图和flask-script插件优化项目结构和命令行管理,包括单蓝图和多蓝图模式的实现,以及如何通过flask-script增强Flask项目的命令行功能。

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

  由于我们现在的项目开发是一个相对于来说非常耗时间和精力的一个工程,如果我们将所有的Flask的请求方法都写在同一个文件下的话,非常的不便于我们的代码的管理和后期的功能代码的添加, 就像我们在一个文件中写入多个路由视图,这会使代码维护变得困难。

  flask 蓝图(blueprint)是flask自带的一种框架结构,方便搭建更大的项目结构

现在我们先使用flask 蓝图展示一下他的单蓝图和多蓝图案例:

一、Flask blueprint 的官方案例(使用app启动项目)

1、单蓝图模式
在这里插入图片描述

"""
蓝图的官方案例
注册单一的蓝图实例
使用app加载蓝图
"""
from flask import Blueprint
from flask import Flask

# 创建蓝图
simple_blueprint = Blueprint("simple_page",__name__)

# 蓝图的路由和视图
@simple_blueprint.route("/")
def hello():
    return "hello world"

# 使用flask App方式启动项目
if __name__ == "__main__":
    app = Flask(__name__)
    # 注册蓝图
    app.register_blueprint(simple_blueprint)
    app.run()

2、多蓝图模式
在这里插入图片描述
BluePrintone.py

from flask import Blueprint

# 创建蓝图
simple_blueprint1 = Blueprint("simple_page1",__name__)

# 蓝图的路由和视图
@simple_blueprint1.route("/index1/")
def hello():
    return "hello world1"

BluePrinttwo.py

from flask import Blueprint

# 创建蓝图
simple_blueprint2 = Blueprint("simple_page2",__name__)

# 蓝图的路由和视图
@simple_blueprint2.route("/index2/")
def hello():
    return "hello world2"

manage.py

"""
多蓝图启动文件
"""
from flask import Flask

from muchBluePrint.BluePrintone import simple_blueprint1
from muchBluePrint.BluePrinttwo import simple_blueprint2

app = Flask(__name__)

# 注册蓝图
app.register_blueprint(simple_blueprint1)
app.register_blueprint(simple_blueprint2)

# 使用flask App方式启动项目
if __name__ == "__main__":
    app.run()

二、使用flask-script插件结合蓝图

与bluePrint结合紧密的有两个插件,我们采用blueprint之后,通常会用一种叫做惰性加载的方式,加载app.

flask_scrtip 结合蓝图或者自己可以定义flask项目的命令模式。类似django的python manage.py runserver

由于flask轻量,便于开发,Flask项目和爬虫或者其他的项目结合。

  • 使用flask + celery 驱动爬虫
  • 使用flask + 微信(qq) 进行聊天机器人管理
  • 使用flask + psutil 自动化监控

那么这个时候,就需要我们拓展flask命令 ,类似Django的python manage.py

1、安装flask-script插件

pip install flask-script

在这里插入图片描述

2、官方的单一版本flask-script案例
在该文件中,必须有一个Manager实例,Manager类追踪所有在命令行中调用的命令和处理过程的调用运行情况;

Manager只有一个参数——Flask实例,也可以是一个函数或其他的返回Flask实例;

调用manager.run()启动Manager实例接收命令行中的命令;

flask-script启动方式不是通过直接运行脚本方式,而是通过python 脚本名 runserver启动

# flaskScriptMain.py
"""
flask_script官方案例
"""
from flask import Flask
from flask_script import Manager

app = Flask(__name__)

@app.route('/')
def hello():
    return "hello world"

# 对app进行命令行序列化
manage = Manager(app)


if __name__ == "__main__":
    # 启动flask manage,以manage方式启动app
    manage.run()


# 在命令使用“--python 文件名 runserver--启动

在这里插入图片描述
在这里插入图片描述

3、flask-script添加命令案例

使用Command实例的@command修饰符来给指定函数添加命令功能

# flaskScriptAddCommand.py
"""
给flask_script 添加命令
"""
from flask import Flask
from flask_script import Manager

app = Flask(__name__)

@app.route('/')
def hello():
    return "hello world"

# 对app进行命令行序列化
manage = Manager(app)

@manage.command
def user_register_show(name = "create"):
    """
    :param name: 是命令行可以传递的参数,在命令行以 --name 来传递
    """
    username = input("please enter your username: ")
    email = input("please enter your email: ")
    password = input("please enter your password: ")
    password_confirm = input("please enter your password again: ")
    print("恭喜你执行了%s命令!"%name)
    return "不好意思了,本注册功能逗你玩呢!"

if __name__ == "__main__":
    # 启动flask manage,以manage方式启动app
    manage.run()


# 在命令使用“--python 文件名 runserver--启动

可以发现我们通过@command装饰后,项目运行就会多出一个以装饰函数命名的命令
在这里插入图片描述
以此命令运行该脚本

在这里插入图片描述

被装饰函数中的参数可同–参数名 命令 来指定

在这里插入图片描述

4、flask-script结合蓝图进行flask项目启动

还是用多蓝图的模式,只不过使用了flask-script就是基于命令行的flask多蓝图模式

项目结构:
在这里插入图片描述
BluePrint1.py

"""
多蓝图命令模式 蓝图1
"""
from flask import Blueprint

# 创建蓝图
simple_blueprint1 = Blueprint("simple_page1",__name__)

# 蓝图的路由和视图
@simple_blueprint1.route("/index1/")
def hello():
    return "hello world1"

BluePrint2.py

"""
多蓝图命令模式 蓝图2
"""
from flask import Blueprint

# 创建蓝图
simple_blueprint2 = Blueprint("simple_page2",__name__)

# 蓝图的路由和视图
@simple_blueprint2.route("/index2/")
def hello():
    return "hello world2"

manage.py

"""
多蓝图命令模式 应用
"""
from flask import Flask
from flask_script import Manager

from BluePrint1 import simple_blueprint1
from BluePrint2 import simple_blueprint2

app = Flask(__name__)

# 注册蓝图
app.register_blueprint(simple_blueprint1)
app.register_blueprint(simple_blueprint2)

manage = Manager(app)

# 使用flask App方式启动项目
if __name__ == "__main__":
    manage.run()

启动flask-script命令行方式启动项目
在这里插入图片描述

总结:
flask蓝图和flask-script使用流程:

  • 创建 Flask 应用(app)
  • 搭建蓝图结构
  • Flask-script命令行结构管理
    1、先创建蓝图
    2、App安装蓝图
    3、命令行启动app
<think>Flask蓝图Blueprint)是一种组织Flask应用的方式,可以将应用拆分成多个模块,使得项目结构更清晰,便于维护和扩展。下面是一个使用Flask蓝图的范例。 假设我们要构建一个简单的Web应用,包含两个模块:用户认证(auth)和文章管理(post)。我们将使用蓝图来组织这两个模块。 项目结构: ``` myapp/ __init__.py auth/ __init__.py views.py post/ __init__.py views.py templates/ ... # 模板文件 static/ ... # 静态文件 ``` 1. 首先,创建主应用文件 `myapp/__init__.py`: ```python from flask import Flask def create_app(): app = Flask(__name__) # 注册蓝图 from .auth.views import auth_bp from .post.views import post_bp app.register_blueprint(auth_bp, url_prefix='/auth') app.register_blueprint(post_bp, url_prefix='/post') return app ``` 2. 创建认证模块蓝图 `myapp/auth/views.py`: ```python from flask import Blueprint, render_template, redirect, url_for # 创建蓝图,第一个参数是蓝图名称,第二个参数是所在模块 auth_bp = Blueprint('auth', __name__) @auth_bp.route('/login') def login(): return render_template('auth/login.html') @auth_bp.route('/logout') def logout(): return redirect(url_for('auth.login')) ``` 3. 创建文章管理模块蓝图 `myapp/post/views.py`: ```python from flask import Blueprint, render_template post_bp = Blueprint('post', __name__) @post_bp.route('/') def index(): return "Post Index Page" @post_bp.route('/show/<int:id>') def show(id): return f"Showing post with id {id}" ``` 4. 运行应用:在项目根目录下创建一个 `run.py` 文件: ```python from myapp import create_app app = create_app() if __name__ == '__main__': app.run(debug=True) ``` 解释: - 在 `create_app` 工厂函数中,我们创建了Flask实例,并注册了两个蓝图:`auth_bp` 和 `post_bp`,并分别指定了URL前缀(`url_prefix`)。 -蓝图模块中,我们使用 `Blueprint` 类创建蓝图对象,然后使用 `@<blueprint_name>.route` 装饰器定义路由。 - 蓝图的名称在构造时指定(如 `'auth'`),在反向解析URL时,需要使用带命名空间的名称,格式为:`<blueprint_name>.<view_function_name>`,例如:`url_for('auth.login')`。 - 使用蓝图后,认证模块的登录URL为 `/auth/login`,文章模块的显示文章URL为 `/post/show/<id>`。 这样,通过蓝图我们将应用分成了两个模块,每个模块可以独立编写视图函数,便于团队协作和代码维护。 §§相关问题§§: 1. 如何在Flask蓝图使用模板目录和静态文件目录? 2. 如何在Flask蓝图使用before_request等钩子函数? 3. 如何在一个蓝图中嵌套另一个蓝图? 4. 蓝图之间如何共享数据或函数?</think>### Flask蓝图使用范例 Flask蓝图(Blueprint)是组织大型Flask应用的模块化方式,允许将应用拆分为可重用的组件。下面是一个完整的蓝图使用示例: ```python # 主应用文件: app.py from flask import Flask from auth import auth_bp # 导入认证蓝图 from blog import blog_bp # 导入博客蓝图 app = Flask(__name__) # 注册蓝图并指定URL前缀 app.register_blueprint(auth_bp, url_prefix='/auth') app.register_blueprint(blog_bp, url_prefix='/blog') @app.route('/') def home(): return "Welcome to the main page!" if __name__ == '__main__': app.run(debug=True) ``` ```python # 认证蓝图: auth/views.py from flask import Blueprint, render_template, redirect, url_for # 创建蓝图对象 auth_bp = Blueprint( 'auth', # 蓝图名称 __name__, # 当前模块名 template_folder='templates/auth', # 蓝图专用模板目录 static_folder='static/auth' # 蓝图专用静态文件目录 ) @auth_bp.route('/login') def login(): return render_template('login.html') # 使用蓝图模板 @auth_bp.route('/logout') def logout(): return redirect(url_for('auth.login')) # 蓝图内反向解析 @auth_bp.before_request def before_auth_request(): print("Auth blueprint request started") ``` ```python # 博客蓝图: blog/views.py from flask import Blueprint, jsonify blog_bp = Blueprint('blog', __name__) @blog_bp.route('/posts') def list_posts(): return jsonify([{'id': 1, 'title': 'First Post'}]) @blog_bp.route('/post/<int:post_id>') def show_post(post_id): return f"Showing post {post_id}" ``` ### 项目结构 ``` myapp/ ├── app.py # 主应用 ├── auth/ # 认证蓝图模块 │ ├── __init__.py │ ├── views.py │ └── templates/auth/ # 蓝图专用模板 │ └── login.html ├── blog/ # 博客蓝图模块 │ ├── __init__.py │ └── views.py └── templates/ # 全局模板 ``` ### 关键点解释: 1. **蓝图创建**: - 使用 `Blueprint()` 创建蓝图对象 - 参数:名称、导入名、模板/静态文件目录 2. **蓝图注册**: - 主应用使用 `register_blueprint()` 注册 - `url_prefix` 为蓝图添加统一URL前缀 3. **路由定义**: - 使用 `@blueprint_name.route` 装饰器定义路由 - 支持所有标准Flask路由功能 4. **反向解析**: - 蓝图使用 `url_for('蓝图名.视图函数名')` - 示例:`url_for('auth.login')` 5. **蓝图钩子**: - 支持 `before_request`、`after_request` 等钩子 - 只在蓝图范围内生效 6. **资源隔离**: - 每个蓝图可拥有独立的模板/静态文件目录 - 查找顺序:蓝图目录 > 全局目录 ### 优点: 1. **模块化**:将功能拆分为独立组件 2. **可重用**:蓝图可跨项目复用 3. **命名空间**:避免视图函数/URL冲突 4. **延迟注册**:蓝图可在应用初始化后注册
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孜孜孜孜不倦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值