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

Python 100 天 · 第 67 天:博客项目(三):RESTful 增删改

这是「Python 100 天」系列第 67 天的学习笔记:博客项目(三):RESTful 增删改。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

把博客从"读"升级成"能写":新建文章、编辑文章、删除文章,正文用富文本编辑器。README 知识点:GET 读文章、POST 新建、DELETE 删除、编辑已有文章。

一、一套 CRUD 路由

1
2
3
4
5
6
7
GET  /                    → 列表
GET /post/<id> → 详情
GET /new-post (表单) → 新建页
POST /new-post (提交) → 写入
GET /edit-post/<id> → 编辑页(表单预填)
POST /edit-post/<id> → 更新
GET /delete/<id> → 删除(这份代码的问题,见下)

二、表单预填:编辑页怎么显示原内容

1
2
3
4
5
6
7
edit_form = CreatePostForm(
title=post.title,
subtitle=post.subtitle,
img_url=post.img_url,
author=post.author,
body=post.body
)

WTForms 的字段构造时可以传 default/位置值,实例化后模板里 {{ form.title }} 就带着原值。同一个表单类,新建时空、编辑时有值——这是复用表单的标准做法。

模板里再用一个 is_edit 标志区分标题和按钮文案:

1
return render_template("make-post.html", form=edit_form, is_edit=True)

三、富文本:CKEditor

1
2
3
4
from flask_ckeditor import CKEditor, CKEditorField
ckeditor = CKEditor(app)

body = CKEditorField("Blog Content", validators=[DataRequired()])

CKEditorField 渲染成一个可视化编辑器,提交的是 HTML 字符串。存进 db.Text(长文本,不限制长度)。

巨大的安全风险:存的是 HTML,模板里用 {{ post.body|safe }} 渲染就等于允许作者注入 <script>。真实博客必须用 bleach 之类的库做白名单过滤。

四、日期的存法

1
date=date.today().strftime("%B %d, %Y")     # "December 02, 2026"

存成格式化好的字符串。好处是直接显示,坏处是没法按时间排序(字符串排序对 "December" 无效)。正确做法是存 db.DateTime,显示时再 strftime。

代码全文

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# ============================================================
# day67/main.py —— 博客项目(三):把文章搬进数据库,做 RESTful 增删改
# 作用:/new-post 建文章、/edit-post/N 改文章、/delete/N 删文章、/post/N 看文章。
# 知识点:CKEditor 富文本字段、date.today().strftime 格式化日期、
# 用 FlaskForm 编辑已有对象时怎么预填数据、validate_on_submit 在编辑场景的复用
# 运行:python main.py(先 pip install flask-ckeditor;数据库 posts.db)
# ============================================================

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, URL
from flask_ckeditor import CKEditor, CKEditorField
# CKEditorField:把 textarea 换成富文本编辑器,提交上来的是 HTML 字符串。
# 安全提醒:富文本 = 用户可提交任意 HTML,未过滤就渲染到页面会 XSS。
# 真实项目要接 bleach 之类做白名单清洗。
from datetime import date
# 只导入 date 类,比 import datetime 更轻、也更直白。

app = Flask(__name__)
app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
# 写死的密钥:练习可以,上线必须换环境变量。
ckeditor = CKEditor(app)
# 初始化扩展:注册静态资源、给模板提供 CKEditor 的加载脚本。
Bootstrap(app)

# CONNECT TO DB
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


# CONFIGURE TABLE
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(250), unique=True, nullable=False)
subtitle = db.Column(db.String(250), nullable=False)
date = db.Column(db.String(250), nullable=False)
# 日期存字符串("December 02, 2026"),为了直接显示。
# 代价:没法按时间排序/筛选。规范做法是 db.Date 存真日期、显示时再格式化。
body = db.Column(db.Text, nullable=False)
# Text:不限长度的长文本,富文本 HTML 用它。
author = db.Column(db.String(250), nullable=False)
img_url = db.Column(db.String(250), nullable=False)
# db.create_all()
# 这行被注释掉了:表已经建过,注释掉是为了每次启动不重复执行。
# 首次运行必须解开注释跑一次。


# WTForm
class CreatePostForm(FlaskForm):
title = StringField("Blog Post Title", validators=[DataRequired()])
subtitle = StringField("Subtitle", validators=[DataRequired()])
author = StringField("Your Name", validators=[DataRequired()])
img_url = StringField("Blog Image URL", validators=[DataRequired(), URL()])
# URL():必须像 http(s)://host/path 的合法地址。
body = CKEditorField("Blog Content", validators=[DataRequired()])
submit = SubmitField("Submit Post")


@app.route('/')
def get_all_posts():
posts = BlogPost.query.all()
# 没有 order_by → 顺序由数据库决定(通常按主键),
# 想“最新在前”要写 .order_by(BlogPost.id.desc())。
return render_template("index.html", all_posts=posts)


@app.route("/post/<int:post_id>")
def show_post(post_id):
requested_post = BlogPost.query.get(post_id)
# 找不到时是 None,模板里访问 post.title 会报错 → 500,应 abort(404)。
return render_template("post.html", post=requested_post)


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


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


@app.route("/new-post", methods=["GET", "POST"])
def add_new_post():
form = CreatePostForm()
if form.validate_on_submit():
new_post = BlogPost(
title=form.title.data,
# 字段都验证过了(非空/URL 合法),这里直接取 .data。
subtitle=form.subtitle.data,
body=form.body.data,
img_url=form.img_url.data,
author=form.author.data,
date=date.today().strftime("%B %d, %Y")
# date.today() 拿今天;strftime 按格式串转字符串:
# %B 月份全名(December) %d 两位日(02) %Y 四位年(2026)
# 注意 %d 会给 "02",而 Windows 上某些格式化会出 "2" —— 想固定补零可用 f-string。
)
db.session.add(new_post)
db.session.commit()
return redirect(url_for("get_all_posts"))
return render_template("make-post.html", form=form)
# GET 或验证失败:渲染空表单(失败时表单里保留用户输入 + 显示错误)。


@app.route("/edit-post/<int:post_id>", methods=["GET", "POST"])
def edit_post(post_id):
post = BlogPost.query.get(post_id)
edit_form = CreatePostForm(
title=post.title,
subtitle=post.subtitle,
img_url=post.img_url,
author=post.author,
body=post.body
)
# 关键技巧:给 FlaskForm 传“字段名=值”的关键字参数,就是给各字段设默认值
# (内部等价于传 data={"title": ...})。这样编辑页一打开就是原文内容。
# 顺序很重要:POST 时 request.form 的优先级高于这里的默认值,
# 所以用户改过的内容不会被旧值覆盖。
if edit_form.validate_on_submit():
post.title = edit_form.title.data
post.subtitle = edit_form.subtitle.data
post.img_url = edit_form.img_url.data
post.author = edit_form.author.data
post.body = edit_form.body.data
# 逐字段覆盖:SQLAlchemy 会在 commit 时只 UPDATE 改过的列。
# date 故意不改 —— 文章保留原始发布日期。
db.session.commit()
return redirect(url_for("show_post", post_id=post.id))
# url_for("show_post", post_id=...) → /post/12
return render_template("make-post.html", form=edit_form, is_edit=True)
# is_edit=True 让同一个模板切换标题("New Post" / "Edit Post")和按钮文案。


@app.route("/delete/<int:post_id>")
def delete_post(post_id):
post_to_delete = BlogPost.query.get(post_id)
db.session.delete(post_to_delete)
db.session.commit()
return redirect(url_for('get_all_posts'))
# 又是 GET 删除:任何人分享这个链接就能删文章。
# 应改成 POST + 表单 + CSRF。


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

代码走读

  1. CKEditor(app) 初始化编辑器,Bootstrap(app) 提供模板。
  2. BlogPost 模型六个字段,body 用 Text。
  3. CreatePostForm:5 个字符串字段 + 1 个富文本字段,都 DataRequired,img_url 额外 URL()。
  4. get_all_posts():BlogPost.query.all()。
  5. show_post(post_id):按 id 取单篇。
  6. add_new_post():校验通过 → 构造对象(日期用今天)→ commit → 回列表。
  7. edit_post(post_id):先用数据库的值构造表单(预填)→ 如果提交且校验通过,逐字段覆盖 → commit → 跳到详情页。
  8. delete_post(post_id):查、删、commit、回列表。

这份代码的问题

(1) db.create_all() 被注释掉了

1
# db.create_all()

第一次运行会 OperationalError: no such table: blog_post。作者是在本地手动建过表才注释掉的——你 clone 下来必须放开这一行。这是"代码能跑但我跑不了"的最常见原因。

(2) 删除用 GET

/delete/<id> 是个 GET 请求。爬虫、浏览器预取、甚至聊天软件生成链接预览都可能触发删除。必须改成 POST + 表单 + CSRF。

(3) BlogPost.query.get() 已弃用

用 db.session.get(BlogPost, post_id)。

(4) 找不到文章就崩

/post/999 → post=None → 模板里 post.title 报错 500。要判断并返回 404 页面。

(5) title 唯一但没处理冲突

两篇文章同名 → IntegrityError。应该捕获后提示"标题已存在"。

(6) SECRET_KEY 硬编码

'8BYkEfBA6O6donzWlSihBXox7C0sKR6b' 提交到公开仓库就等于泄露。

(7) 没有作者/登录

任何人都能发文章、删文章。这是 Day 68–69 要补的(用户系统)。

运行结果

/ 是文章列表(卡片)→ "New Post" 进编辑页,CKEditor 里能加粗、插图 → 提交后回到列表 → 点文章进详情 → "Edit" 进来时表单已填好 → 保存跳回详情 → "Delete" 删掉。

易错点

  1. 忘了放开 db.create_all():表不存在。
  2. is_edit 没传:编辑页标题还显示 "New Post"。
  3. {{ post.body }} 不写 |safe:富文本的 HTML 被转义成源代码显示。
  4. 写了 |safe:XSS 风险,必须配合后端过滤。
  5. flask_ckeditor 装不上:它对 Flask 版本敏感,可换 Flask-CKEditor 指定版本或改用 Quill CDN。

动手改

  • 放开 db.create_all(),跑通建表。
  • 删除改成 POST 表单。
  • 加 404 处理。
  • 用 bleach 过滤 body 的 HTML 再存。

源文件逐个讲解

10 个文件 + 一个整目录的第三方资源:

文件 行数/规模 职责 谁写的
main.py99一个模型 + 六个路由你
templates/header.html约 25公共 head(仍是完整文档,问题同 Day 59)模板
templates/footer.html约 30公共页脚模板
templates/index.html约 55文章列表(带 ✘ 删除)模板
templates/post.html约 45文章详情模板
templates/make-post.html40新建/编辑共用(靠 is_edit 切换)模板
templates/about.html / contact.html各约 40关于/联系(静态内容)模板
posts.db二进制SQLite,仓库里带着运行产物
static/css/*Clean Blog 主题样式第三方
static/js/*主题脚本交互第三方
static/scss/*Sass 源码main.css 的源码第三方
static/vendor/fontawesome、jquery、bootstrap 等第三方库第三方,跳过不讲
static/img/*5 张 jpg各页横幅模板自带

main.py(99 行)

(1)CKEditor:富文本编辑器

1
2
3
from flask_ckeditor import CKEditor, CKEditorField

ckeditor = CKEditor(app)

两个类:

  • CKEditor(app):注册扩展(提供 ckeditor.load() 等模板工具);
  • CKEditorField:一个表单字段类型——渲染成富文本编辑器,而不是普通 <textarea>。

body = CKEditorField("Blog Content", validators=[DataRequired()]):

用户能加粗、插图、列表,提交上来的是 HTML 字符串——存进 db.Text 列。

⚠️ 安全警告:{{ post.body }} 在模板里默认会转义 HTML——所以需要 |safe 才能显示格式。但 |safe + 用户输入 = XSS 漏洞(用户能注入 <script>)。

正确做法:用 bleach 之类的库白名单清洗 HTML,再 |safe。这份代码没有做。

(2)模型:body 用 db.Text

1
2
3
4
5
6
7
8
9
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(250), unique=True, nullable=False)
subtitle = db.Column(db.String(250), nullable=False)
date = db.Column(db.String(250), nullable=False)
body = db.Column(db.Text, nullable=False)
author = db.Column(db.String(250), nullable=False)
img_url = db.Column(db.String(250), nullable=False)
# db.create_all()

String(250) vs Text:

  • String(n):有长度上限(VARCHAR(n))
  • Text:不限长(TEXT)

博客正文用 Text 是对的(可能几千字)。

date 是 String 不是 Date——因为要存 "December 02, 2026" 这种人类可读格式。代价是不能按时间排序。

db.create_all() 被注释掉了:

1
# db.create_all()

为什么? 因为 posts.db 已经存在(仓库里带着),不需要重建。但第一次跑的人会 no such table: blog_post——这是一个「交付陷阱」。

(3)日期:strftime("%B %d, %Y")

1
date=date.today().strftime("%B %d, %Y")

%B 是「英文完整月份」(December)、%d 两位日(02)、%Y 四位年。

结果:"December 02, 2026"。

%B 依赖系统 locale——在中文系统上可能输出 "十二月"。要固定英文得 locale.setlocale(locale.LC_TIME, "en_US")。

(4)edit_post:用 obj= 预填表单

1
2
3
4
5
6
7
8
9
10
@app.route("/edit-post/<int:post_id>", methods=["GET", "POST"])
def edit_post(post_id):
post = BlogPost.query.get(post_id)
edit_form = CreatePostForm(
title=post.title,
subtitle=post.subtitle,
img_url=post.img_url,
author=post.author,
body=post.body
)

CreatePostForm(title=..., subtitle=...) 用「关键字参数」给字段赋初值——表单打开时输入框里就有原内容。

这是 WTForms 的「数据回填」机制:字段名 → 关键字参数。

⚠️ 这里有个真 bug:POST 提交时也会执行这段代码——用户填的新值被「数据库里的旧值」覆盖了?

不,不会——因为 WTForms 在 validate_on_submit() 时,表单数据优先于构造时传的值。所以 POST 时用户输入生效**。

但注意 body=post.body 传的是 HTML 字符串——CKEditor 能正确回填。

(5)edit_post 的 is_edit=True

1
return render_template("make-post.html", form=edit_form, is_edit=True)

一个模板服务「新建」和「编辑」两个场景,靠 is_edit 切换标题:

1
2
3
4
5
{% if is_edit: %}
<h1>Edit Post</h1>
{% else: %}
<h1>New Post</h1>
{% endif %}

这是「模板复用」的正确姿势——对比 Day 57 的三份 post.html。

(6)/delete/<id>:又是 GET 删除

1
2
3
4
5
6
@app.route("/delete/<int:post_id>")
def delete_post(post_id):
post_to_delete = BlogPost.query.get(post_id)
db.session.delete(post_to_delete)
db.session.commit()
return redirect(url_for('get_all_posts'))

Day 63/64 的老问题:GET 删除、无确认。而且这次更危险——列表页每条文章旁边就是一个 ✘ 链接,鼠标一滑就删了。

(7)show_post 用 query.get(post_id)

1
2
requested_post = BlogPost.query.get(post_id)
return render_template("post.html", post=requested_post)

post_id 不存在时返回 None → 模板里 {{post.title}} 渲染成空(Jinja 容错),页面空白但不报错。应该 abort(404)。

templates/index.html:删除按钮就嵌在列表里

1
2
3
4
5
          <p class="post-meta">Posted by
<a href="#">{{post.author}}</a>
on {{post.date}}
<a href="{{url_for('delete_post', post_id=post.id) }}">✘</a>
</p>

✘ 是个纯文本字符(U+2718),没有确认、没有权限——任何人点一下就删。

真实博客必须有「登录才能删」(Day 68/69 加了用户系统,但删除权限仍是 Day 69 才修)。

templates/make-post.html(40 行)——CKEditor 的加载

1
2
3
        {{ ckeditor.load() }}
{{ ckeditor.config(name='body') }}
{{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }}

三行各有作用:

① ckeditor.load():引入 CKEditor 的 JS/CSS(从 CDN)。

② ckeditor.config(name='body'):告诉 CKEditor「去接管名为 body 的那个 textarea」。

name='body' 必须和 CKEditorField 的字段名一致——写错就不生效,页面上还是个光秃秃的 textarea。

③ button_map={"submit": "primary"}:给提交按钮加 Bootstrap 的 btn-primary 类(默认是 btn-default)。

这是 quick_form 的一个小定制点——想改按钮颜色就靠它。

另外注意 {% extends 'bootstrap/base.html' %} + {% include "header.html" %} 同时用:

1
2
3
4
{% extends 'bootstrap/base.html' %}
...
{% block content %}
{% include "header.html" %}

bootstrap/base.html 已经提供了 <html><head><body> 骨架,再 include 一个「完整的 header.html」就又嵌套了一层。

这是「继承 + 包含」混用时的经典混乱——header.html 本该只提供 {% block head %} 的内容。

static/vendor/——第三方,跳过

目录里有:fontawesome-free/、jquery/、bootstrap/、simple-line-icons/ 等。

这是 Clean Blog 主题自带的本地化依赖(不靠 CDN,断网也能跑)。

这些库的源码不属于本课程教学内容,不逐个讲。你只需要知道:模板里 <link> 和 <script> 引的就是这些文件。

这份代码的问题

  1. db.create_all() 被注释,新环境跑起来没表。
  2. /delete 用 GET 且无确认(列表里一个 ✘ 就删)。
  3. |safe 渲染用户 HTML 有 XSS 风险(且没有清洗)。
  4. header.html 与 {% extends %} 混用,嵌套文档。
  5. show_post 找不到文章时返回空白页(应 404)。
  6. date 存字符串,无法按时间排序。
  7. %B 依赖系统 locale。
  8. SECRET_KEY 硬编码(和 Day 62 同一个值)。
  9. title 的 unique 约束没处理,重名 500。

README.md(8 行)

标题 Day 67 - Blog Capstone Project Part 4 - Adding a Rich Text Editor,知识点:Flask、WTForms、Bootstrap、CKEditor、SQLite、SQLAlchemy。

关键在 CKEditor:从「纯文本输入」升级到「所见即所得」。

这一天的项目形态已经很像真实 CMS 了:文章有标题、副标题、作者、日期、封面图、富文本正文——只差「用户」和「权限」,那正是 Day 68/69 的内容。

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