🧱 一、项目结构
最终项目目录如下:
flask_blog/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ └── templates/
│ ├── base.html
│ └── index.html
└── myblog.py

⚙️ 二、环境配置
1. 创建虚拟环境
# 创建并激活虚拟环境
python -m venv venv
source venv/bin/activate # macOS / Linux
venv\Scripts\activate # Windows
2. 安装 Flask
pip install flask
🧩 三、项目代码
app/init.py
from flask import Flask
app = Flask(__name__)
# 注意:这里导入 routes,是为了注册路由
from app import routes
app/routes.py
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'duke'}
posts = [
{'author': {'username': '刘'}, 'body': '这是模板模块中的循环例子~1'},
{'author': {'username': '忠强'}, 'body': '这是模板模块中的循环例子~2'}
]
return render_template('index.html', title='我的博客', user=user, posts=posts)
app/templates/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
{% if title %}
<title>{{ title }} - 博客</title>
{% else %}
<title>欢迎来到博客!</title>
{% endif %}
</head>
<body>
<div>
<h1>我的 Flask 博客</h1>
<hr>
{% block content %}{% endblock %}
</div>
</body>
</html>
app/templates/index.html
{% extends "base.html" %}
{% block content %}
<h2>你好呀, {{ user.username }}!</h2>
{% for post in posts %}
<div>
<p><b>{{ post.author.username }}</b> 说: {{ post.body }}</p>
</div>
{% endfor %}
{% endblock %}
myblog.py
from app import app
if __name__ == '__main__':
app.run(debug=True)
🚀 四、运行项目
1️⃣ 在项目根目录下设置环境变量
export FLASK_APP=myblog.py # macOS / Linux
set FLASK_APP=myblog.py # Windows
2️⃣ 启动 Flask 服务器
flask run
3️⃣ 打开浏览器访问:
http://127.0.0.1:5000/
