T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 59 天:博客项目(二):套上现成主题

这是「Python 100 天」系列第 59 天的学习笔记:博客项目(二):套上现成主题。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

Day 57 的博客只有裸 HTML,这次换成 Start Bootstrap 的 Clean Blog 主题:首页文章列表、关于页、联系页、文章详情页,全部走 Flask 路由。README 知识点与 Day 57 相同(Jinja 动态页面、Jinja + API、多行语句、url_for)——这一天的重点是"工程化":多页面、模板复用、静态资源组织。

一、多页面怎么组织

1
2
3
4
@app.route('/')            → index.html   文章列表
@app.route('/about.html') → about.html 关于
@app.route('/contact.html')→ contact.html 联系
@app.route('/post/<int:p_id>') → post.html 详情

注意路由名带 .html:这是为了和主题里原有的链接(about.html、contact.html)对上,让静态页面迁过来时链接不断。真实项目一般用 /about 这种干净路径,再用 301 重定向兼容旧链接。

二、详情页怎么取文章

1
2
3
@app.route('/post/<int:p_id>')
def get_post(p_id):
return render_template('post.html', post=all_posts[int(p_id) - 1])

URL 里的 id 从 1 开始(人读的),列表索引从 0 开始 → p_id - 1。这是"人类编号 vs 程序索引"的经典转换。

三、主题是怎么接进来的

Start Bootstrap 的主题通常给的是:index.html + about.html + post.html + css/styles.css + js/scripts.js + 图片。接入步骤固定为:

  1. HTML 全部放进 templates/;
  2. css/、js/、assets/ 放进 static/;
  3. 把 HTML 里所有 href="css/..." 改成 {{ url_for('static', filename='css/styles.css') }};
  4. 把写死的文章内容替换成 {{ post.title }}、{{ post.body }};
  5. 重复的导航栏/页脚抽成 base.html(Day 61 会正式讲继承)。

那份 styles.css 有 200KB,因为它是 Bootstrap 5 的完整源码 + 主题样式打包在一起——这就是为什么真实项目不手写 CSS 框架。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# ============================================================
# day59/main.py —— 把一个现成博客模板接上数据(Flask 博客 v2)
# 作用:启动时拉一次 API 拿到所有文章,然后让 /、/about、/contact、/post/N 各自渲染。
# 知识点:模块级(全局)数据 vs 每次请求取数据、多个 route 共享一个视图、
# render_template 传对象、列表下标取第 N 篇、/xxx.html 这种“假静态”路由
# 运行:python main.py
# ============================================================

from flask import Flask, render_template
import requests


blog_url = "https://api.npoint.io/2b1e1701b179fe512483"
blog_resp = requests.get(blog_url)
all_posts = blog_resp.json()
# 这三行在“模块被加载时”执行一次 —— 也就是服务器启动时拉一次数据,
# 之后所有请求都用内存里这份 all_posts。
# 好处:快;坏处:改了这个 npoint 的内容,必须重启服务器才看得到。


app = Flask(__name__)


@app.route('/')
def home():
return render_template("index.html", posts=all_posts)
# 把全部文章交给模板,模板里用 {% for post in posts %} 生成列表。


@app.route('/index.html')
def index():
# 这里故意又注册了一个 /index.html 的路由,返回和首页完全相同的内容。
# 原因:模板里的链接写的是 href="/posts/python-day-59.html/"(静态站写法),
# 如果 Flask 只注册了 '/',点链接会 404。
# 更干净的做法是不改 Python 而改模板:用 {{ url_for('home') }}。
return render_template("index.html", posts=all_posts)


@app.route('/about.html')
def about():
return render_template('about.html')


@app.route('/contact.html')
def contact():
return render_template('contact.html')


@app.route('/post/<int:p_id>')
def get_post(p_id):
# <int:p_id> 把 URL 里的数字转成 int 传给 p_id,例如 /post/1 → p_id=1。
return render_template('post.html', post=all_posts[int(p_id) - 1])
# all_posts 是列表,下标从 0 开始,而文章 id 从 1 开始 → 所以要 -1。
# 隐患:完全不校验范围。
# /post/0 → 下标 -1 → 取到最后一篇(Python 负下标,不报错但答案错)
# /post/999 → IndexError → 500 错误
# 正确做法:先判断 1 <= p_id <= len(all_posts),否则 abort(404)。


if __name__ == "__main__":
app.run(debug=True)

代码走读

  1. 模块级请求 API 拿全部文章,只请求一次(比 Day 57 每次请求都调接口好)。
  2. home() / index() 两个路由返回同一个模板——为了同时支持 / 和 /index.html。
  3. about() / contact() 返回静态页。
  4. get_post(p_id) 用 p_id - 1 取列表元素,直接传 post(单篇)给模板,模板里用 post.title 而不是循环。

这份代码的问题

(1) 索引越界没有防护

访问 /post/999 直接 IndexError → 500。应该:

1
2
if not 1 <= p_id <= len(all_posts):
return render_template("404.html"), 404

(2) 依赖"id 恰好等于列表下标 + 1"

API 返回的文章如果顺序变了、中间删了一篇,p_id - 1 就全错位。正确做法是按 post["id"] 查找:

1
post = next((p for p in all_posts if p["id"] == p_id), None)

(3) 两个路由重复代码

home 和 index 函数体完全一样。可以用一个函数注册两次,或用 @app.route('/') + @app.route('/index.html') 叠在同一函数上。

(4) 模块级请求 API

服务器启动时请求一次。好处是快,坏处是API 挂了服务就起不来,且数据永远不更新。生产环境应该加缓存 + 失败降级。

运行结果

首页是主题的大图 hero + 文章列表卡片;点标题进详情;导航栏能切到 About / Contact。

易错点

  1. 静态文件 404:主题的 css/、js/ 没放进 static/,或路径没改成 url_for。
  2. 模板里 post 未定义:/ 传的是 posts(复数,列表),详情页传的是 post(单数),名字混用就报错。
  3. url_for('static', filename=...) 的 filename 是相对 static/ 的路径。
  4. 改了 CSS 浏览器没变:缓存,强制刷新(Cmd+Shift+R)。

动手改

  • 加 404 处理。
  • 改成按 post["id"] 查找。
  • 把导航栏抽成 base.html,其余模板 {% extends %}(提前看 Day 61)。

源文件逐个讲解

这是全书第一次「模块化重构」,文件数 10 个:

文件 行数/规模 职责
main.py35五个路由
templates/header.html20公共 head({% include %} 片段)
templates/footer.html40公共页脚(社交图标 + 版权)
templates/index.html92首页:文章列表(一个 for 循环)
templates/post.html60文章详情(一个模板管所有文章)
templates/about.html48关于页
templates/contact.html66联系页(SB Forms 表单)
static/css/styles.css约 7000 行(压缩)Start Bootstrap「Clean Blog」主题,第三方
static/js/scripts.js约 10 行主题脚本(导航栏滚动收缩)
static/assets/favicon.ico—图标
static/assets/img/*.jpg5 张各页横幅背景
README.md8说明页

main.py(35 行)

1
2
3
blog_url = "https://api.npoint.io/2b1e1701b179fe512483"
blog_resp = requests.get(blog_url)
all_posts = blog_resp.json()

关键改动:requests.get 挪到了「模块级」,在 app = Flask(__name__) 之前。

这意味着「服务器启动时拉一次,之后所有请求共用」——这就是 Day 57「每个请求都重新拉」的修复。

代价:如果 API 挂了,整个应用启动就崩;内容更新了要重启服务器。真实项目会用缓存 + 定时刷新。

1
2
3
4
5
6
7
8
@app.route('/')
def home():
return render_template("index.html", posts=all_posts)


@app.route('/index.html')
def index():
return render_template("index.html", posts=all_posts)

两个路由指向同一个模板——因为模板里的导航链接写的是 index.html(静态站的遗留)。

这是「为了让旧链接不断」而加的兼容路由。更好的做法是把导航改成 url_for('home')(post.html 里就是这么干的,见下)。

1
2
3
@app.route('/post/<int:p_id>')
def get_post(p_id):
return render_template('post.html', post=all_posts[int(p_id) - 1])

这一天最核心的一行:

Day 57 是三个模板(post.html/post2.html/post3.html)+ 三个 if;这一天是「一个模板 + 一个下标」。

all_posts[int(p_id) - 1] 的逻辑是:URL 里的 id 从 1 开始,列表下标从 0 开始,所以减 1。

这个写法有两个前提:

  1. id 必须等于「列表位置 + 1」——如果 API 的 id 是 10, 20, 30,就全错;
  2. p_id 必须 ≤ 列表长度——访问 /post/99 会 IndexError → 500。

更稳的写法:

1
2
3
4
post = next((p for p in all_posts if p["id"] == p_id), None)
if post is None:
abort(404)
return render_template("post.html", post=post)

int(p_id) 也是多余的——<int:p_id> 转换器已经保证是 int 了。

templates/header.html(20 行)——片段,不是完整页面

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
...
<link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet" />
</head>
<body>

</body>
</html>

这是一个「只有头」的 HTML——<body> 是空的,<html> 都没真正闭合(闭合标签在 footer.html 里)。

用法:

1
2
3
4
<html lang="en">
{% include "header.html" %}
<body>
...内容...

{% include "header.html" %} 会把这段原样插进来——结果就是:

1
2
3
4
5
6
7
8
<html lang="en">
<!DOCTYPE html>
<html lang="en">
<head>...</head>
<body></body>
</html>
<body>
...内容...

⚠️ 这是一个结构性 bug:嵌套了 <html> 和 <body>。

header.html 应该只包含 <head>...</head>,不该带 <!DOCTYPE>、<html>、<body>。现在每个页面都会嵌套两层文档结构——浏览器容错(忽略内层),但 HTML 是无效的。

正确做法:

1
2
3
4
5
<!-- header.html -->
<head>
<meta charset="utf-8" />
...
</head>

然后页面里:

1
2
3
4
5
<!DOCTYPE html>
<html lang="en">
{% include "header.html" %}
<body> ... </body>
</html>

这一天「用 include」的思路是对的,拆的位置错了。

url_for('static', filename='...') 用对了——这是 Day 56/57 硬编码 static/ 的修复。favicon.ico 和 styles.css 都用了它。

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<footer class="border-top">
...
</footer>
</body>
</html>

问题更严重:它带 <head> 和 <title>Title</title>——插进页面后会出现两个 <title>(虽然浏览器只认第一个)。

页面里是这么用的:

1
2
3
        {% include "footer.html" %}
<!-- Bootstrap core JS-->
<script src="...bootstrap.bundle.min.js"></script>

注意 include 在 <body> 内部、脚本之前——因为 footer.html 自己带了 </body></html>,所以后面的 <script> 实际上在 </html> 之后。

浏览器会容错把它们挪回 body,所以能跑。但这段 HTML 是「错位」的。

fa-stack 的技巧:

1
2
3
4
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-twitter fa-stack-1x fa-inverse"></i>
</span>

两层图标叠起来:底层大圆(fa-stack-2x)+ 上层小图标(fa-stack-1x),fa-inverse 让上层变白。效果是「实心圆 + 白色图标」。这是 FontAwesome 的经典用法。

templates/index.html(92 行)——一个循环代替三份复制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
                    {% for post in posts: %}
<!-- Post preview-->
<div class="post-preview">
<a href="{{ url_for('get_post', p_id=post['id']) }}">
<h2 class="post-title">
{{post['title']}}
</h2>
<h3 class="post-subtitle">
{{post['subtitle']}}
</h3>
</a>
<p class="post-meta">
Posted by
<a href="#!">
{{post['author']}}
</a>
on {{post['date']}}
</p>
</div>
<!-- Divider-->
<hr class="my-4"/>
{% endfor %}

和 Day 57 对比,这是「重构」的全部意义:

Day 57 Day 59
三个 div.card 复制三遍一个 {% for %}
每张卡里 {% if id == 1 %} 挑数据循环变量直接给数据
url_for('find_post', post_id=1) 写死p_id=post['id'] 动态

加第 4 篇文章完全不用改模板。

{% for post in posts: %} 末尾的冒号——Jinja 不需要,是 Python 习惯带来的(Day 57 也有)。

url_for('get_post', p_id=post['id']):用数据里的 id 生成链接——这就是「列表页 → 详情页」的正确连接方式。

templates/post.html(60 行)——一个模板管所有文章

1
2
3
4
5
6
7
8
9
<h1>{{post['title']}}</h1>
<h2 class="subheading">{{post['subtitle']}}</h2>
<span class="meta">
Posted by
<a href="#!">{{post['author']}}</a>
on {{post['date']}}
</span>
...
<p>{{post['body']}}</p>

整个模板只有一处变量 post——传哪篇就显示哪篇。

对比 Day 57 的 {% for %} + {% if id == 1 %}:模板里不再有「选择逻辑」,选择在 Python 里做完了。这是「关注点分离」。

<a href="{{ url_for('home') }}">:导航栏用 url_for 了(index.html 里还是 href="/posts/python-day-59.html/")——两个模板不一致。

style="background-image: url({{'...'}})":用 Jinja 包一个字符串字面量,没有意义({{'硬编码'}} 等于直接写)——这是「为了以后换图片」留的占位,但现在看着很怪。

templates/about.html / contact.html

结构完全一样:{% include "header.html" %} → 导航 → <header class="masthead"> 横幅 → <main> 内容 → {% include "footer.html" %}。

三处不一致:

1
2
3
4
5
6
<!-- about.html / contact.html -->
<a class="navbar-brand" href="/posts/python-day-59.html/">Start Bootstrap</a>
<li class="nav-item"><a class="nav-link ..." href="/posts/python-day-59.html/">Home</a></li>

<!-- post.html -->
<a class="navbar-brand" href="{{ url_for('home') }}">Start Bootstrap</a>

: 导航里一半是硬编码 index.html、一半是 url_for`。

<header style="background-image: url('static/assets/img/about-bg.jpg')">——又是硬编码 static/(应该在 static 目录下用 url_for)。

contact.html 的表单是「假的」:

1
<form id="contactForm" data-sb-form-api-token="API_TOKEN">

data-sb-form-api-token="API_TOKEN" 是 SB Forms 服务的占位 token——要真能用必须去 startbootstrap.com 注册拿 token。现在提交什么也不会发生。

static/css/styles.css——第三方,不讲实现

这是 Start Bootstrap 的「Clean Blog」主题,约 7000 行(压缩后),已经把 Bootstrap 5 整包编译进去了(所以 header.html 里不需要单独引 bootstrap.css)。

scripts.js(约 10 行):导航栏滚动时收缩的脚本(给 #mainNav 加 navbar-shrink 类)。

这份代码的问题

  1. header.html 带了 <html>/<body>(嵌套文档)。
  2. footer.html 带了 <head> 和 <title>Title</title>(出现两个 title)。
  3. all_posts[int(p_id) - 1] 假设 id 连续从 1 开始,/post/99 会 500。
  4. /index.html 和 / 两个路由重复(为了兼容旧链接,但模板没统一)。
  5. 导航链接一半硬编码、一半 url_for。
  6. about.html/contact.html 的背景图硬编码 static/。
  7. 表单 token 是占位符。
  8. {% for %} 末尾多余冒号。

README.md(8 行)

标题 Day 59 - Blog Capstone Project Part 2 - Adding Styling,知识点:Jinja、Templating、URL Building、Bootstrap。

「Part 2 - Adding Styling」:Day 57 是「能跑」,Day 59 是「好看 + 不重复」。这一天真正学到的是「模板继承/包含」——把公共部分抽出来,页面只写差异。

微信收款码 微信
支付宝收款码 支付宝
评论