1. 创建蓝图: 在一个独立的 Python 文件中创建你的蓝图,定义路由和视图函数。例如,创建一个名为 my_blueprint.py 的文件:
# my_blueprint.py
from flask import Blueprint, render_template
# 创建蓝图
my_blueprint = Blueprint('my_blueprint', __name__)
# 定义路由和视图函数
@my_blueprint.route('/hello')
def hello():
return render_template('hello.html', message='Hello from My Blueprint!')
2. 在主应用中注册蓝图: 在你的主应用文件中,导入蓝图并使用 register_blueprint 方法将其注册到应用中。例如,在 app.py 文件中:
# app.py
from flask import Flask
from my_blueprint import my_blueprint # 导入蓝图对象
# 创建 Flask 应用
app = Flask(__name__)
# 注册蓝图
app.register_blueprint(my_blueprint, url_prefix='/my')
在这个例子中,我们将蓝图注册到应用中,并指定了路由前缀 /my。这意味着在访问蓝图中定义的路由时,需要加上 /my 前缀。
3. 运行应用: 在主应用文件中添加运行代码,然后运行应用。
# app.py
if __name__ == '__main__':
app.run(debug=True)
4. 访问蓝图路由: 打开浏览器并访问 http://localhost:5000/my/hello,你应该能够看到蓝图中定义的 hello 视图的输出。
通过以上步骤,你就成功地将一个简单的蓝图注册到了 Flask 应用中。在实际应用中,你可以创建多个蓝图,每个负责不同的功能模块,然后通过注册的方式将它们组织在一起,提高应用的可维护性和可扩展性。
转载请注明出处:http://www.zyzy.cn/article/detail/7341/Flask