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

Python 100 天 · 第 69 天:博客项目(四):用户、权限与评论

这是「Python 100 天」系列第 69 天的学习笔记:博客项目(四):用户、权限与评论。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

把 Day 67/68 合成一个完整博客:用户注册登录、只有管理员(id=1)能发/改/删文章、任何登录用户都能评论、每条评论带头像。README 知识点:注册、登录、保护路由(需要登录 / 需要管理员)、关系型数据库、允许任何用户给文章评论。

这一天是整个课程里最有工程价值的一天:一对多关系 + 权限装饰器。

一、一对多关系

三个表:users、blog_posts、comments。

1
2
3
User 1 ──< N BlogPost        (一个用户写多篇文章)
User 1 ──< N Comment (一个用户发多条评论)
BlogPost 1 ──< N Comment (一篇文章有多条评论)

代码里两侧都要写:

1
2
3
4
5
6
class User(db.Model):
posts = relationship("BlogPost", back_populates="author")

class BlogPost(db.Model):
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
author = relationship("User", back_populates="posts")
  • ForeignKey("users.id") 是数据库层的约束(这一列的值必须存在于 users.id);
  • relationship(..., back_populates=...) 是ORM 层的便捷访问(post.author.name、user.posts[0].title);
  • 两边成对出现,名字互相对应。

于是发文章时可以这样写:

1
new_post = BlogPost(author=current_user, ...)   # 直接给对象,不用给 id

SQLAlchemy 会自动填 author_id。

二、__tablename__

1
2
class User(UserMixin, db.Model):
__tablename__ = "users"

不写的话表名默认是类名小写(user、blog_post)。这里显式指定,是因为 user 在 PostgreSQL 里是保留字,早晚要踩坑。从一开始就显式命名是好习惯。

三、权限装饰器

1
2
3
4
5
6
7
def admin_only(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.id != 1:
return abort(403)
return f(*args, **kwargs)
return decorated_function
  • *args, **kwargs 透传参数,所以 @admin_only 能用在 /edit-post/<int:post_id> 这种带参数的路由上;
  • @wraps(f) 必须加:否则被装饰函数的 __name__ 变成 decorated_function,Flask 会因为"多个路由函数同名"报错;
  • abort(403) 返回"禁止访问",比 redirect 更语义化。

用的时候:

1
2
3
@app.route("/new-post", methods=["GET", "POST"])
@admin_only
def add_new_post(): ...

current_user.id != 1 这个判断很粗暴——它把"第一个注册的用户"当管理员。真实系统应该有 is_admin 字段或角色表。

四、评论要"登录才能发"

1
2
3
4
5
if form.validate_on_submit():
if not current_user.is_authenticated:
flash("You need to login or register to comment.")
return redirect(url_for("login"))
new_comment = Comment(text=..., comment_author=current_user, parent_post=requested_post)

注意这里没有用 @login_required:因为同一个路由既要给未登录用户看文章,又要处理评论提交。所以校验写在函数内部。

五、头像:Gravatar

1
gravatar = Gravatar(app, size=100, rating='g', default='retro', ...)

模板里 {{ gravatar(post.author.email) }} 就会根据邮箱哈希生成头像 URL。同一个邮箱在任何支持 Gravatar 的站点显示同一张头像——不用自己存图片。

代码全文

forms.py(表单独立成模块)

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
# ============================================================
# day69/forms.py —— 把四个表单单独放一个模块
# 为什么要拆:main.py 越来越长;而且 templates 里多处要用表单类,
# 拆出来以后 main.py 只负责路由,职责清楚,也不会和 main 互相 import 成环。
# 知识点:FlaskForm 子类、StringField/PasswordField/CKEditorField、DataRequired/URL 校验器
# ============================================================

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, URL
from flask_ckeditor import CKEditorField


# WTForm
class CreatePostForm(FlaskForm):
title = StringField("Blog Post Title", validators=[DataRequired()])
# StringField(label, validators=[...]):
# label 显示在输入框上方的文字
# validators 验证器列表,按顺序依次执行,任一失败即整体不通过
subtitle = StringField("Subtitle", validators=[DataRequired()])
img_url = StringField("Blog Image URL", validators=[DataRequired(), URL()])
# URL() 要求是合法网址(带 scheme + host),否则报 "Invalid URL"。
body = CKEditorField("Blog Content", validators=[DataRequired()])
# CKEditorField 继承自 TextAreaField,只是渲染成富文本编辑器;值仍是 HTML 字符串。
submit = SubmitField("Submit Post")
# 按钮不参与验证,也不进 .data。


class RegisterForm(FlaskForm):
email = StringField("Email", validators=[DataRequired()])
# 这里只校验非空,没加 Email() 检查格式 —— 可以改进。
password = PasswordField("Password", validators=[DataRequired()])
# PasswordField 渲染成 type="password",输入内容显示为圆点;
# 但提交上来的仍是明文,服务端要自己哈希后再存。
name = StringField("Name", validators=[DataRequired()])
submit = SubmitField("Sign Me Up!")


class LoginForm(FlaskForm):
email = StringField("Email", validators=[DataRequired()])
password = PasswordField("Password", validators=[DataRequired()])
submit = SubmitField("Let Me In!")


class CommentForm(FlaskForm):
comment_text = CKEditorField("Comment", validators=[DataRequired()])
# 用富文本收集评论 = 用户可以提交任意 HTML。
# 渲染时必须过滤(bleach 白名单),否则就是存储型 XSS。
submit = SubmitField("Submit Comment")

main.py

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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# ============================================================
# day69/main.py —— 博客项目(四):用户表 + 文章作者 + 评论 + 管理员权限
# 作用:三张表互相关联(User 1—N BlogPost,User 1—N Comment,BlogPost 1—N Comment);
# 登录后可评论,只有 id=1 的管理员能发/改/删文章。
# 知识点:db.ForeignKey 与 relationship/back_populates 双向关系、
# 自定义装饰器 admin_only + functools.wraps、Gravatar 头像、
# 表单拆到 forms.py 避免循环导入
# 运行:python main.py(首次解开 db.create_all())
# ============================================================

from flask import Flask, render_template, redirect, url_for, flash, abort
# abort(403):立刻中断请求并返回 403 页面(不是抛异常给用户看堆栈)。
from flask_bootstrap import Bootstrap
from flask_ckeditor import CKEditor
from datetime import date
from functools import wraps
# wraps:写装饰器时用它保留被装饰函数的 __name__ 等元信息,
# 否则 Flask 会因为多个视图函数都叫 decorated_function 而报“端点重复”。
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
# relationship:在 ORM 层建立对象之间的导航属性(user.posts / post.author)。
from flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user
from forms import LoginForm, RegisterForm, CreatePostForm, CommentForm
# 表单单独放 forms.py:main.py 导入 forms,forms 不导入 main,避免循环导入。
from flask_gravatar import Gravatar
# Gravatar:根据邮箱哈希去 gravatar.com 取头像,模板里用 gravatar(email) 生成 <img>。

app = Flask(__name__)
app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
ckeditor = CKEditor(app)
Bootstrap(app)
gravatar = Gravatar(app, size=100, rating='g', default='retro', force_default=False, force_lower=False, use_ssl=False, base_url=None)
# size:头像像素边长;rating='g' 只要普通级内容;
# default='retro':该邮箱没注册 Gravatar 时用的默认头像风格(retro/identicon/monsterid…)。

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


@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))


# CONFIGURE TABLE
class User(UserMixin, db.Model):
__tablename__ = "users"
# 显式指定表名;不写默认是 user(单数小写)。
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(100))
posts = relationship("BlogPost", back_populates="author")
# 一对多:user.posts 得到这个用户写的所有文章(list)。
# back_populates 是“双向绑定”:在 BlogPost 那边写 author = relationship("User", back_populates="posts"),
# 两边名字必须对上,ORM 才知道它们描述的是同一个关系。
comments = relationship("Comment", back_populates="comment_author")


class BlogPost(db.Model):
__tablename__ = "blog_posts"
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
# 外键指向 users.id —— 这就是“多”的那一侧存的外键列。
# 表名必须和 __tablename__ 一致("users.id")。
author = relationship("User", back_populates="posts")
# 多对一:post.author 直接拿到 User 对象,不用手写 join。
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)
img_url = db.Column(db.String(250), nullable=False)
comments = relationship("Comment", back_populates="parent_post")


class Comment(db.Model):
__tablename__ = "comments"
id = db.Column(db.Integer, primary_key=True)
post_id = db.Column(db.Integer, db.ForeignKey("blog_posts.id"))
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
parent_post = relationship("BlogPost", back_populates="comments")
comment_author = relationship("User", back_populates="comments")
# Comment 同时连两张表:它既属于某篇文章,也属于某个用户。
text = db.Column(db.Text, nullable=False)
# db.create_all()


def admin_only(f):
# 自定义装饰器:包一层,先判断再决定是否执行原函数。
@wraps(f)
def decorated_function(*args, **kwargs):
# *args/**kwargs 把原函数的参数(比如 post_id)原样透传。
if current_user.id != 1:
# 当前用户不是 id=1 的管理员。
# 隐患:未登录时 current_user 是匿名对象,没有 id 属性 → AttributeError 500。
# 应该先 if not current_user.is_authenticated: return abort(403)。
return abort(403)
return f(*args, **kwargs)
return decorated_function


@app.route('/')
def get_all_posts():
posts = BlogPost.query.all()
return render_template("index.html", all_posts=posts, current_user=current_user)
# 把 current_user 也传进模板(其实 Jinja 里可直接用 current_user,Flask-Login 已注入)。


@app.route('/register', methods=["GET", "POST"])
def register():
form = RegisterForm()
if form.validate_on_submit():
# 已存在同邮箱 → 提示去登录
if User.query.filter_by(email=form.email.data).first():
print(User.query.filter_by(email=form.email.data).first())
#User already exists
flash("You've already signed up with that email, log in instead!")
return redirect(url_for('login'))

hash_and_salted_password = generate_password_hash(
form.password.data,
method='pbkdf2:sha256',
salt_length=8
)
new_user = User(
email=form.email.data,
name=form.name.data,
password=hash_and_salted_password,
)
db.session.add(new_user)
db.session.commit()
login_user(new_user)
return redirect(url_for("get_all_posts"))

return render_template("register.html", form=form, current_user=current_user)


@app.route('/login', methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
email = form.email.data
password = form.password.data

user = User.query.filter_by(email=email).first()
# Email doesn't exist or password incorrect.
if not user:
flash("That email does not exist, please try again.")
return redirect(url_for('login'))
elif not check_password_hash(user.password, password):
flash('Password incorrect, please try again.')
return redirect(url_for('login'))
else:
login_user(user)
# 想让登录“记住我”跨浏览器重启仍有效,传 remember=True 并配置 REMEMBER_COOKIE_*。
return redirect(url_for('get_all_posts'))
return render_template("login.html", form=form, current_user=current_user)


@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('get_all_posts'))


@app.route("/post/<int:post_id>", methods=["GET", "POST"])
def show_post(post_id):
form = CommentForm()
requested_post = BlogPost.query.get(post_id)

if form.validate_on_submit():
# validate_on_submit 里已经挡掉了 CSRF 和空内容
if not current_user.is_authenticated:
flash("You need to login or register to comment.")
return redirect(url_for("login"))
# 这个判断放在 validate 之后:未登录用户提交评论时表单本身能过校验,
# 但 CSRF 是会话级的,未登录也可能通过,所以必须再判一次身份。

new_comment = Comment(
text=form.comment_text.data,
comment_author=current_user,
# 直接赋对象(不是 author_id):ORM 会自动填外键。
parent_post=requested_post
)
db.session.add(new_comment)
db.session.commit()
# 提交后没有 redirect:刷新页面会再次 POST(浏览器会提示重复提交)。
# 正确做法是 redirect 回本页(PRG)。

return render_template("post.html", post=requested_post, form=form, current_user=current_user)


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


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


@app.route("/new-post", methods=["GET", "POST"])
@admin_only
def add_new_post():
form = CreatePostForm()
if form.validate_on_submit():
new_post = BlogPost(
title=form.title.data,
subtitle=form.subtitle.data,
body=form.body.data,
img_url=form.img_url.data,
author=current_user,
# 用对象赋值,author_id 由 ORM 填 —— 这样就不用手动取 current_user.id。
date=date.today().strftime("%B %d, %Y")
)
db.session.add(new_post)
db.session.commit()
return redirect(url_for("get_all_posts"))

return render_template("make-post.html", form=form, current_user=current_user)


@app.route("/edit-post/<int:post_id>", methods=["GET", "POST"])
@admin_only
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=current_user,
# 注意:CreatePostForm 里没有 author 字段(作者取当前用户),
# 传 author= 会被 WTForms 当作未知字段忽略,不影响功能但属冗余。
body=post.body
)
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.body = edit_form.body.data
db.session.commit()
return redirect(url_for("show_post", post_id=post.id))

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


@app.route("/delete/<int:post_id>")
@admin_only
def delete_post(post_id):
post_to_delete = BlogPost.query.get(post_id)
db.session.delete(post_to_delete)
# 坑:文章还有评论时,外键指向它 → 删除会因约束报错(SQLite 默认不检查外键,
# 但换了 MySQL/Postgres 就会报 IntegrityError)。
# 正确做法:关系上配 cascade="all, delete-orphan",或先删该文章的评论。
db.session.commit()
return redirect(url_for('get_all_posts'))


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

代码走读

  1. forms.py 把四个表单(发文、注册、登录、评论)拆出去,main.py 只 import——代码开始有模块划分了。
  2. 三个模型 + 三组 relationship。
  3. admin_only 装饰器。
  4. /register:查重 → 哈希 → 建用户 → 自动登录。
  5. /login:查邮箱 → 校验哈希 → login_user。
  6. /post/<id>:GET 显示文章 + 评论表单;POST 校验登录后写 Comment。
  7. /new-post、/edit-post/<id>、/delete/<id>:都挂 @admin_only。
  8. 每个 render_template 都显式传 current_user(其实模板里可以直接用,属于冗余但无害)。

这份代码的问题

(1) db.create_all() 又是注释状态

# db.create_all()。clone 后必须放开,否则 no such table: users。

(2) 评论提交后没有重定向

1
2
3
db.session.add(new_comment)
db.session.commit()
return render_template("post.html", ...)

POST 之后直接渲染,用户刷新会重复提交同一条评论。应该 redirect(url_for("show_post", post_id=post_id))(PRG 模式)。

(3) print(...) 留在注册逻辑里

1
print(User.query.filter_by(...).first())

调试残留,会打印用户邮箱到日志——这算隐私泄露。

(4) admin_only 里 current_user.id 对未登录用户会报错

未登录时 current_user 是 AnonymousUserMixin,没有 id 属性?实际上它提供了 id = None,所以能跑;但更稳的写法是 if not current_user.is_authenticated or current_user.id != 1。

(5) 评论内容没过 XSS 过滤

CommentForm.comment_text 是 CKEditorField,存的是 HTML,模板里渲染时如果用了 |safe 就有 XSS 风险。

(6) 删除仍然是 GET

/delete/<id> 是 GET + @admin_only,至少挡住了外人,但仍然违反"GET 不改状态"。

(7) 密码字段只有 DataRequired

没有长度和强度要求。

运行结果

注册 → 首页文章列表每篇显示作者名和头像 → 点进去能看评论、登录后能发评论 → 用 id=1 的账号登录后,每篇文章出现 Edit/Delete,右上角出现 New Post;用其他账号登录看不到这些按钮,直接访问 /new-post 会得到 403。

易错点

  1. relationship 只写一边:InvalidRequestError: Mapper ... has no property。
  2. 忘了 @wraps:AssertionError: View function mapping is overwriting an existing endpoint function。
  3. ForeignKey("users.id") 表名写错:建表时 NoReferencedTableError。
  4. Comment(post_id=...) 和 parent_post= 混用:给对象更省事,给 id 也行,别两个都漏。
  5. 改了模型后旧 db 文件还在:字段对不上,删库重建。

动手改

  • 加 is_admin 布尔字段,替代 id == 1。
  • 评论提交后 redirect。
  • 删掉 print。
  • 给文章详情页加"相关文章"(同作者的其他文章):BlogPost.query.filter_by(author_id=post.author_id).all()。

源文件逐个讲解

11 个文件——这一天是全书功能最完整的博客:

文件 行数 职责
main.py192三个模型 + 十个路由 + admin_only 装饰器
forms.py32四个表单类(从 main.py 拆出来)
templates/header.html / footer.html约 25 / 30公共片段
templates/index.html约 60文章列表
templates/post.html58文章详情 + 评论区
templates/make-post.html40新建/编辑共用
templates/login.html / register.html各约 30登录/注册
templates/about.html / contact.html各约 40静态页
static/Clean Blog 主题 + vendor第三方

forms.py(32 行)——第一次「拆分模块」

1
2
3
4
5
6
7
8
9
10
11
12
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, URL
from flask_ckeditor import CKEditorField


class CreatePostForm(FlaskForm):
title = StringField("Blog Post Title", validators=[DataRequired()])
subtitle = StringField("Subtitle", validators=[DataRequired()])
img_url = StringField("Blog Image URL", validators=[DataRequired(), URL()])
body = CKEditorField("Blog Content", validators=[DataRequired()])
submit = SubmitField("Submit Post")

四个表单类:

类 字段 用途
CreatePostFormtitle / subtitle / img_url / body新建 & 编辑文章
RegisterFormemail / password / name注册
LoginFormemail / password登录
CommentFormcomment_text发评论

关键设计:CreatePostForm 里删掉了 author 字段——因为「作者」现在是登录用户,不该让用户自己填:

1
2
3
4
5
# Day 67 的版本有这一行
author = StringField("Your Name", validators=[DataRequired()])

# Day 69 删掉了,改成从 current_user 取
new_post = BlogPost(..., author=current_user, ...)

这是「认证」带来的必然变化:身份由系统确定,不由表单提交。

main.py 里 from forms import LoginForm, RegisterForm, CreatePostForm, CommentForm——模块化拆分:表单归 forms.py,路由归 main.py。

forms.py 里的 from flask_ckeditor import CKEditorField 说明:表单依赖 CKEditor 扩展。

main.py(192 行)

(1)Gravatar:用邮箱生成头像

1
2
3
from flask_gravatar import Gravatar

gravatar = Gravatar(app, size=100, rating='g', default='retro', force_default=False, force_lower=False, use_ssl=False, base_url=None)

Gravatar 是「全球头像服务」:把邮箱的 MD5 拼进 URL,就能拿到这个邮箱的头像。

五个参数:

参数 含义
size=100100×100 像素
rating='g'内容分级(g = 全年龄)
default='retro'没头像时用哪种默认图
use_ssl=False不用 https(过时参数)

用法在模板里:

1
<img src="{{ comment.comment_author.email | gravatar }}"/>

| gravatar 是一个 Jinja 过滤器——把邮箱转成头像 URL。

⚠️ 隐私提示:Gravatar 会把你用户的邮箱哈希发给第三方——这本身就是一种信息泄露(能反查是否注册过某站)。很多站已经不用它了。

(2)三个模型与「关系」

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
class User(UserMixin, db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(100))
posts = relationship("BlogPost", back_populates="author")
comments = relationship("Comment", back_populates="comment_author")


class BlogPost(db.Model):
__tablename__ = "blog_posts"
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
author = relationship("User", back_populates="posts")
...
comments = relationship("Comment", back_populates="parent_post")


class Comment(db.Model):
__tablename__ = "comments"
id = db.Column(db.Integer, primary_key=True)
post_id = db.Column(db.Integer, db.ForeignKey("blog_posts.id"))
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
parent_post = relationship("BlogPost", back_populates="comments")
comment_author = relationship("User", back_populates="comments")
text = db.Column(db.Text, nullable=False)

这是全书最复杂的数据建模——三张表、三条关系:

1
2
3
User 1 ──< N BlogPost      (一个用户写多篇文章)
User 1 ──< N Comment (一个用户发多条评论)
BlogPost 1 ──< N Comment (一篇文章下多条评论)

每一对关系都由「两半」组成:

外键列 关系属性 反向属性
BlogPost.author_idBlogPost.authorUser.posts
Comment.post_idComment.parent_postBlogPost.comments
Comment.author_idComment.comment_authorUser.comments

back_populates 是「双向声明的名字」——两边必须互相指对,写错会 InvalidRequestError。

__tablename__ 现在显式写了——因为默认表名(blog_post)和自定义的(blog_posts)容易混。而且 ForeignKey("blog_posts.id") 必须和实际表名一致。

用法非常自然:

1
2
3
{{ post.author.name }}              # 从文章拿到作者
{% for comment in post.comments %} # 从文章拿到所有评论
{{ comment.comment_author.email }} # 从评论拿到评论者

这就是 ORM 关系最大的价值:不用写 JOIN,直接点出来。

(3)admin_only:自定义装饰器

1
2
3
4
5
6
7
def admin_only(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.id != 1:
return abort(403)
return f(*args, **kwargs)
return decorated_function

这是 Day 54 学的装饰器的第一次「实战」——逐行拆:

① @wraps(f)

functools.wraps 把原函数的 __name__、__doc__ 复制到装饰后的函数上——没有它,所有被装饰的路由函数都叫 decorated_function,Flask 会报「多个端点同名」。

这是装饰器写路由时的必备(Day 54 提到过「没保留元信息」的问题,这里补上了)。

② *args, **kwargs

接受任意参数——因为被装饰的 add_new_post() 无参,但 edit_post(post_id) 有一个参数。不写 *args 就无法通用。

③ if current_user.id != 1

「id 为 1 的用户是管理员」——硬编码的约定。

问题:id 是自增的,第一个注册的人才是 id=1。如果数据库重建,管理员可能变成别人。

更规范的做法是加 is_admin 布尔列。

④ abort(403)

返回 403 Forbidden——比 404 更准确(「你没权限」而不是「不存在」)。

(4)show_post:文章 + 评论

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@app.route("/post/<int:post_id>", methods=["GET", "POST"])
def show_post(post_id):
form = CommentForm()
requested_post = BlogPost.query.get(post_id)

if form.validate_on_submit():
if not current_user.is_authenticated:
flash("You need to login or register to comment.")
return redirect(url_for("login"))

new_comment = Comment(
text=form.comment_text.data,
comment_author=current_user,
parent_post=requested_post
)
db.session.add(new_comment)
db.session.commit()

return render_template("post.html", post=requested_post, form=form, current_user=current_user)

「同一个 URL 干两件事」:GET 显示文章 + 评论表单,POST 提交评论。

comment_author=current_user / parent_post=requested_post:

直接赋「对象」,不用赋 id——SQLAlchemy 会自动填外键。这是 ORM 关系的便利。

if not current_user.is_authenticated 的位置有点晚:form.validate_on_submit() 先执行了(浪费一次校验),然后才检查登录。应该在前面先判登录。

没有 redirect 到别处——提交后重新渲染当前页(F5 会重复提交评论)。应该 return redirect(url_for("show_post", post_id=post_id))。

(5)edit_post 里一个隐蔽 bug

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

CreatePostForm 里没有 author 字段(Day 69 删掉了)——所以 author=current_user 会被忽略。

不报错(FlaskForm 接受未知关键字参数?实际上会抛 TypeError: __init__() got an unexpected keyword argument 'author')。

这是一个真 bug:点「Edit Post」会 500。除非 Flask-WTF 的 Form.__init__ 用 **kwargs 吞掉它——不同版本行为不同,但至少是「传了个没用的参数」。

(6)delete_post 现在有保护了

1
2
3
@app.route("/delete/<int:post_id>")
@admin_only
def delete_post(post_id):

加了 @admin_only——Day 67 的「谁都能删」被修掉了。

但仍然是 GET——没有确认框。

templates/post.html(58 行)——评论区

1
2
3
4
5
6
7
            {{ post.body|safe }}
<hr>
{% if current_user.id == 1 %}
<div class="clearfix">
<a class="btn btn-primary float-right" href="{{url_for('edit_post', post_id=post.id)}}">Edit Post</a>
</div>
{% endif %}

{{ post.body|safe }}:告诉 Jinja「不要转义 HTML」——因为 body 是 CKEditor 产生的富文本。

⚠️ 这就是 XSS 风险所在:如果用户在 CKEditor 里粘贴 <script>alert(1)</script>(源码模式),会被原样执行。

{% if current_user.id == 1 %}:只有管理员看到「Edit Post」按钮——前端隐藏只是体验,后端 @admin_only 才是真正的权限。两层都要有。

评论区:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
            {{ ckeditor.load() }}
{{ ckeditor.config(name='comment_text') }}
{{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }}

<div class="col-lg-8 col-md-10 mx-auto comment">
{% for comment in post.comments: %}
<ul class="commentList">
<li>
<div class="commenterImage">
<img src="{{ comment.comment_author.email | gravatar }}"/>
</div>
<div class="commentText">
{{comment.text|safe}}
<span class="date sub-text">{{comment.comment_author.name}}</span>
</div>
</li>
{% endfor %}
</ul>
</div>

{% for comment in post.comments %}:直接遍历关系属性——ORM 自动生成 SELECT * FROM comments WHERE post_id = ?。

comment.text|safe:评论也是 CKEditor 富文本——同样有 XSS 风险。

{% for %} 写在 <ul> 外面:

1
2
3
{% for comment in post.comments: %}
<ul class="commentList"> ... </ul>
{% endfor %}

每条评论生成一个 <ul>——结构上应该是一个 <ul> 包多个 <li>。这是「循环位置放错」的典型。

{{ comment.comment_author.email | gravatar }}:链式访问「评论 → 作者 → 邮箱」。

这份代码的问题

  1. edit_post 传了不存在的 author 参数(可能 500)。
  2. post.body|safe + comment.text|safe 有 XSS 风险(无 HTML 清洗)。
  3. show_post 提交评论后不重定向(F5 重复提交)。
  4. /delete 仍是 GET。
  5. admin_only 用 id == 1 硬编码,数据库重建就失效。
  6. db.create_all() 被注释。
  7. /post/999 时 requested_post 是 None → 模板里报错。
  8. Gravatar 泄露邮箱哈希。
  9. <ul> 在循环内(结构错误)。
  10. SECRET_KEY 硬编码。

README.md(8 行)

标题 Day 69 - Blog Capstone Project Part 5 - Adding Users,知识点:Flask、WTForms、Bootstrap、CKEditor、SQLite、SQLAlchemy、Authentication、Flask-Login。

八条,是全书知识点最多的一天。

这一天完成了一个「真实博客」的全套:

1
用户注册/登录 → 只有管理员能写/改/删 → 所有人能评论 → 头像自动生成 → 富文本正文

从 Day 41 的静态 HTML,到 Day 69 的完整 CMS——这就是「Web 开发」这条路线的全部骨架。

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