Python 100 天 · 第 69 天:博客项目(四):用户、权限与评论
这是「Python 100 天」系列第 69 天的学习笔记:博客项目(四):用户、权限与评论。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。
今天要解决的问题
把 Day 67/68 合成一个完整博客:用户注册登录、只有管理员(id=1)能发/改/删文章、任何登录用户都能评论、每条评论带头像。README 知识点:注册、登录、保护路由(需要登录 / 需要管理员)、关系型数据库、允许任何用户给文章评论。
这一天是整个课程里最有工程价值的一天:一对多关系 + 权限装饰器。
一、一对多关系
三个表:users、blog_posts、comments。
1 | User 1 ──< N BlogPost (一个用户写多篇文章) |
代码里两侧都要写:
1 | class User(db.Model): |
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 | class User(UserMixin, db.Model): |
不写的话表名默认是类名小写(user、blog_post)。这里显式指定,是因为 user 在 PostgreSQL 里是保留字,早晚要踩坑。从一开始就显式命名是好习惯。
三、权限装饰器
1 | def admin_only(f): |
*args, **kwargs透传参数,所以@admin_only能用在/edit-post/<int:post_id>这种带参数的路由上;@wraps(f)必须加:否则被装饰函数的__name__变成decorated_function,Flask 会因为"多个路由函数同名"报错;abort(403)返回"禁止访问",比redirect更语义化。
用的时候:
1 | @app.route("/new-post", methods=["GET", "POST"]) |
current_user.id != 1 这个判断很粗暴——它把"第一个注册的用户"当管理员。真实系统应该有 is_admin 字段或角色表。
四、评论要"登录才能发"
1 | if form.validate_on_submit(): |
注意这里没有用 @login_required:因为同一个路由既要给未登录用户看文章,又要处理评论提交。所以校验写在函数内部。
五、头像:Gravatar
1 | gravatar = Gravatar(app, size=100, rating='g', default='retro', ...) |
模板里 {{ gravatar(post.author.email) }} 就会根据邮箱哈希生成头像 URL。同一个邮箱在任何支持 Gravatar 的站点显示同一张头像——不用自己存图片。
代码全文
forms.py(表单独立成模块)
1 | # ============================================================ |
main.py
1 | # ============================================================ |
代码走读
forms.py把四个表单(发文、注册、登录、评论)拆出去,main.py只 import——代码开始有模块划分了。- 三个模型 + 三组
relationship。 admin_only装饰器。/register:查重 → 哈希 → 建用户 → 自动登录。/login:查邮箱 → 校验哈希 →login_user。/post/<id>:GET 显示文章 + 评论表单;POST 校验登录后写Comment。/new-post、/edit-post/<id>、/delete/<id>:都挂@admin_only。- 每个
render_template都显式传current_user(其实模板里可以直接用,属于冗余但无害)。
这份代码的问题
(1) db.create_all() 又是注释状态
# db.create_all()。clone 后必须放开,否则 no such table: users。
(2) 评论提交后没有重定向
1 | db.session.add(new_comment) |
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。
易错点
relationship只写一边:InvalidRequestError: Mapper ... has no property。- 忘了
@wraps:AssertionError: View function mapping is overwriting an existing endpoint function。 ForeignKey("users.id")表名写错:建表时NoReferencedTableError。Comment(post_id=...)和parent_post=混用:给对象更省事,给 id 也行,别两个都漏。- 改了模型后旧 db 文件还在:字段对不上,删库重建。
动手改
- 加
is_admin布尔字段,替代id == 1。 - 评论提交后
redirect。 - 删掉
print。 - 给文章详情页加"相关文章"(同作者的其他文章):
BlogPost.query.filter_by(author_id=post.author_id).all()。
源文件逐个讲解
11 个文件——这一天是全书功能最完整的博客:
| 文件 | 行数 | 职责 |
|---|---|---|
main.py | 192 | 三个模型 + 十个路由 + admin_only 装饰器 |
forms.py | 32 | 四个表单类(从 main.py 拆出来) |
templates/header.html / footer.html | 约 25 / 30 | 公共片段 |
templates/index.html | 约 60 | 文章列表 |
templates/post.html | 58 | 文章详情 + 评论区 |
templates/make-post.html | 40 | 新建/编辑共用 |
templates/login.html / register.html | 各约 30 | 登录/注册 |
templates/about.html / contact.html | 各约 40 | 静态页 |
static/ | Clean Blog 主题 + vendor | 第三方 |
forms.py(32 行)——第一次「拆分模块」
1 | from flask_wtf import FlaskForm |
四个表单类:
| 类 | 字段 | 用途 |
|---|---|---|
CreatePostForm | title / subtitle / img_url / body | 新建 & 编辑文章 |
RegisterForm | email / password / name | 注册 |
LoginForm | email / password | 登录 |
CommentForm | comment_text | 发评论 |
关键设计:CreatePostForm 里删掉了 author 字段——因为「作者」现在是登录用户,不该让用户自己填:
1 | # Day 67 的版本有这一行 |
这是「认证」带来的必然变化:身份由系统确定,不由表单提交。
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 | from flask_gravatar import Gravatar |
Gravatar 是「全球头像服务」:把邮箱的 MD5 拼进 URL,就能拿到这个邮箱的头像。
五个参数:
| 参数 | 含义 |
|---|---|
size=100 | 100×100 像素 |
rating='g' | 内容分级(g = 全年龄) |
default='retro' | 没头像时用哪种默认图 |
use_ssl=False | 不用 https(过时参数) |
用法在模板里:
1 | <img src="{{ comment.comment_author.email | gravatar }}"/> |
| gravatar 是一个 Jinja 过滤器——把邮箱转成头像 URL。
⚠️ 隐私提示:Gravatar 会把你用户的邮箱哈希发给第三方——这本身就是一种信息泄露(能反查是否注册过某站)。很多站已经不用它了。
(2)三个模型与「关系」
1 | class User(UserMixin, db.Model): |
这是全书最复杂的数据建模——三张表、三条关系:
1 | User 1 ──< N BlogPost (一个用户写多篇文章) |
每一对关系都由「两半」组成:
| 外键列 | 关系属性 | 反向属性 |
|---|---|---|
BlogPost.author_id | BlogPost.author | User.posts |
Comment.post_id | Comment.parent_post | BlogPost.comments |
Comment.author_id | Comment.comment_author | User.comments |
back_populates 是「双向声明的名字」——两边必须互相指对,写错会 InvalidRequestError。
__tablename__ 现在显式写了——因为默认表名(blog_post)和自定义的(blog_posts)容易混。而且 ForeignKey("blog_posts.id") 必须和实际表名一致。
用法非常自然:
1 | {{ post.author.name }} # 从文章拿到作者 |
这就是 ORM 关系最大的价值:不用写 JOIN,直接点出来。
(3)admin_only:自定义装饰器
1 | def admin_only(f): |
这是 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 | @app.route("/post/<int:post_id>", methods=["GET", "POST"]) |
「同一个 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 | edit_form = CreatePostForm( |
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 | @app.route("/delete/<int:post_id>") |
加了 @admin_only——Day 67 的「谁都能删」被修掉了。
但仍然是 GET——没有确认框。
templates/post.html(58 行)——评论区
1 | {{ post.body|safe }} |
{{ post.body|safe }}:告诉 Jinja「不要转义 HTML」——因为 body 是 CKEditor 产生的富文本。
⚠️ 这就是 XSS 风险所在:如果用户在 CKEditor 里粘贴 <script>alert(1)</script>(源码模式),会被原样执行。
{% if current_user.id == 1 %}:只有管理员看到「Edit Post」按钮——前端隐藏只是体验,后端 @admin_only 才是真正的权限。两层都要有。
评论区:
1 | {{ ckeditor.load() }} |
{% for comment in post.comments %}:直接遍历关系属性——ORM 自动生成 SELECT * FROM comments WHERE post_id = ?。
comment.text|safe:评论也是 CKEditor 富文本——同样有 XSS 风险。
{% for %} 写在 <ul> 外面:
1 | {% for comment in post.comments: %} |
每条评论生成一个 <ul>——结构上应该是一个 <ul> 包多个 <li>。这是「循环位置放错」的典型。
{{ comment.comment_author.email | gravatar }}:链式访问「评论 → 作者 → 邮箱」。
这份代码的问题
edit_post传了不存在的author参数(可能 500)。post.body|safe+comment.text|safe有 XSS 风险(无 HTML 清洗)。show_post提交评论后不重定向(F5 重复提交)。/delete仍是 GET。admin_only用id == 1硬编码,数据库重建就失效。db.create_all()被注释。/post/999时requested_post是None→ 模板里报错。- Gravatar 泄露邮箱哈希。
<ul>在循环内(结构错误)。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 开发」这条路线的全部骨架。
- day69/README.md
- day69/forms.py
- day69/main.py
- day69/static/css/clean-blog.css
- day69/static/css/clean-blog.min.css
- day69/static/img/about-bg.jpg
- day69/static/img/contact-bg.jpg
- day69/static/img/edit-bg.jpg
- day69/static/js/clean-blog.js
- day69/static/js/clean-blog.min.js
- day69/static/js/contact_me.js
- day69/static/js/jqBootstrapValidation.js
- day69/static/scss/_bootstrap-overrides.scss
- day69/static/scss/_contact.scss
- day69/static/scss/_footer.scss
- day69/static/scss/_global.scss
- day69/static/scss/_masthead.scss
- day69/static/scss/_mixins.scss
- day69/static/scss/_navbar.scss
- day69/static/scss/_post.scss
- day69/static/scss/_variables.scss
- day69/static/scss/clean-blog.scss
- day69/templates/about.html
- day69/templates/contact.html
- day69/templates/footer.html
- day69/templates/header.html
- day69/templates/index.html
- day69/templates/login.html
- day69/templates/make-post.html
- day69/templates/post.html
- day69/templates/register.html
微信
支付宝


