什么是蓝图?
在 Flask 中,蓝图(Blueprints) 是一种将应用分解为多个模块的方式,可以帮助开发者更好地组织代码,使得应用更易于维护和扩展。
项目示例:构建一个博客项目
我们以一个简单的博客项目为例,展示如何通过蓝图来组织代码。
需求:
主模块显示网站主页。
博客模块显示博客列表以及单篇博客详情。
每个模块独立管理自己的路由和视图函数。
项目目录结构:
buleprints_project/
├── app/
│ ├── init.py
│ ├── main/
│ │ ├── init.py
│ │ ├── routes.py
│ │ ├── templates/
│ │ │ ├── index.html
│ ├── blog/
│ │ ├── init.py
│ │ ├── routes.py
│ │ ├── templates/
│ │ │ │ ├── blog_list.html
│ │ │ │ ├── blog_detail.html
├── run.py
1. 创建主模块 (main)
文件 app/main/init.py:
from flask import Blueprint
main = Blueprint('main', __name__, template_folder='templates')
from . import routes
文件 app/main/routes.py:
from . import main
from flask import render_template
@main.route('/')
def index():
return render_template('index.html')
文件 app/main/templates/main/index.html:
<!DOCTYPE html>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>欢迎来到主页!</h1>
</body>
</html>
2. 创建博客模块 (blog)
文件 app/blog/init.py:
from flask import Blueprint
blog = Blueprint('blog', __name__, template_folder='templates')
from . import routes
文件 app/blog/routes.py:
from . import blog
from flask import render_template
@blog.route('/blogs')
def blog_list():
return render_template('blog_list.html')
@blog.route('/blogs/<int:id>')
def blog_list_detail(id):
return render_template('blog_detail.html', id=id)
文件 app/blog/templates/blog/blog_list.html:
<!DOCTYPE html>
<html>
<head>
<title>博客列表</title>
</head>
<body>
<h1>博客列表</h1>
<ul>
<li><a href="/blog/blogs/1">Blog 1</a></li>
<li><a href="/blog/blogs/2">Blog 2</a></li>
</ul>
</body>
</html>
文件 app/blog/templates/blog/blog_detail.html:
<!DOCTYPE html>
<html>
<head>
<title>博客详情</title>
</head>
<body>
<h1>博客{{ id }}的详情</h1>
</body>
</html>
3. 初始化应用并注册蓝图
文件 app/init.py:
from flask import Flask
def create_app():
app = Flask(__name__)
# 注册蓝图
from .main import main as main_blueprint
from .blog import blog as blog_blueprint
app.register_blueprint(main_blueprint)
app.register_blueprint(blog_blueprint, url_prefix='/blog')
return app
4. 启动项目
文件 run.py:
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
运行项目:
启动服务器:
python run.py
打开浏览器访问:
主页:访问 http://127.0.0.1:5000/,可以看到主页内容。
这是效果图:
博客列表:访问 http://127.0.0.1:5000/blog/blogs,可以看到博客列表。
这是效果图:
博客详情:访问 http://127.0.0.1:5000/blog/blogs/1,可以看到具体博客的详情。
这是效果图:
tips:
在 Flask 蓝图中,from . import blog 实际上是从同一包的 init.py 文件中引入名为 blog 的对象。这种写法是标准的 Python 相对导入,用于在包内模块间共享蓝图实例或其他公共对象